pg.ddx.io  pgsql-hackers@postgresql.org mailing list archive  
help / color / mirror / Atom feed
Support EXCEPT for TABLES IN SCHEMA publications
196+ messages / 8 participants
[nested] [flat]

* Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-04-14 06:30  Nisha Moond <nisha.moond412@gmail.com>
  0 siblings, 4 replies; 196+ messages in thread

From: Nisha Moond @ 2026-04-14 06:30 UTC (permalink / raw)
  To: PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Hi hackers,

Following earlier work to support EXCEPT for FOR ALL TABLES [1]
publications, starting this thread to extend the same capability to
schema-level publications (TABLES IN SCHEMA).

Currently, TABLES IN SCHEMA publishes all tables in a schema with no
way to exclude a subset. Users who want to skip a few tables must
switch to an explicit FOR TABLE list, which loses the convenience of
schema-level publishing and requires ongoing maintenance as tables are
added.

Proposed syntax:
------------------------
CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1 EXCEPT (s1.t1, s1.t2);
ALTER PUBLICATION pub ADD TABLES IN SCHEMA s1 EXCEPT (s1.t1);
ALTER PUBLICATION pub SET TABLES IN SCHEMA s1 EXCEPT (s1.t1);

Note: Tables in the EXCEPT clause must be schema-qualified to avoid
ambiguity and must belong to the published schema; otherwise, an error
is raised.

Rules and behavior:
----------------------------
1) TABLES IN SCHEMA can be combined with FOR TABLE, but EXCEPT applies
only to the schema clause and must appear immediately after it.

Supported:
  CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1 EXCEPT (s1.t1), TABLE s2.t1;
  CREATE PUBLICATION pub FOR TABLE s2.t1, TABLES IN SCHEMA s1 EXCEPT (s1.t1);
  CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1 EXCEPT (s1.t1), s2
EXCEPT (s2.t1)

Not supported:
  CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1,  TABLE s2.t1 EXCEPT (s1.t1);

-- This same rule applies to ALTER PUBLICATION ... ADD/SET.

2) Conflicting definitions
Specifying the same table both in the EXCEPT clause and explicitly in
the TABLE clause results in an error, as this creates a conflicting
definition for the publication.

3) "ALTER PUBLICATION ... DROP TABLES IN SCHEMA" does not support
EXCEPT clause. Whereas, dropping a schema also removes any associated
entries from the EXCEPT list of the publication.
 -- To only remove/update except list entries, use SET instead.

4) Consistency with ALL TABLES EXCEPT rules:
  4a) Excluding a partitioned root excludes all its partitions
  4b) Individual partitions cannot be excluded directly; exclude the root table.
  4c) Excluding an inheritance parent (without ONLY) also excludes its children.

The patches are divided into three parts to simplify review:
  Patch-001: Basic framework to support EXCEPT in CREATE PUBLICATION
... TABLES IN SCHEMA
  Patch-002: Extend support to ALTER PUBLICATION ... ADD TABLES IN SCHEMA
  Patch-003: Extend support to ALTER PUBLICATION ... SET TABLES IN SCHEMA

The patches are attached, feedback and suggestions are welcome.

[1] https://www.postgresql.org/message-id/CALDaNm3%3DJrucjhiiwsYQw5-PGtBHFONa6F7hhWCXMsGvh%3DtamA%40mail...

--
Thanks,
Nisha

Attachments: download all (3 files, .tar.gz)

v1-0001-Support-EXCEPT-clause-for-schema-level-publicatio.patch (application/octet-stream, 37.7K) download From 1cc254b3416840d6c49773d4d309b876b2b5a8df Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Mon, 13 Apr 2026 17:49:44 +0530 Subject: [PATCH v1 1/3] Support EXCEPT clause for schema-level publications Extend table exclusion support in publications to allow specific tables to be excluded from schema-level publications using an EXCEPT clause in CREATE PUBLICATION. Supported syntax: CREATE PUBLICATION <pub> FOR TABLES IN SCHEMA s EXCEPT (s.t1,...); --- doc/src/sgml/logical-replication.sgml | 7 +- doc/src/sgml/ref/create_publication.sgml | 19 ++- src/backend/catalog/pg_publication.c | 79 +++++++++-- src/backend/commands/publicationcmds.c | 73 ++++++++++ src/backend/parser/gram.y | 42 +++++- src/backend/replication/pgoutput/pgoutput.c | 34 ++++- src/bin/pg_dump/pg_dump.c | 30 ++++- src/bin/pg_dump/t/002_pg_dump.pl | 38 +++++- src/bin/psql/describe.c | 18 +++ src/bin/psql/tab-complete.in.c | 12 +- src/include/nodes/parsenodes.h | 1 + src/test/regress/expected/publication.out | 42 +++++- src/test/regress/sql/publication.sql | 27 +++- src/test/subscription/t/037_except.pl | 139 +++++++++++++++++++- 14 files changed, 527 insertions(+), 34 deletions(-) diff --git a/doc/src/sgml/logical-replication.sgml b/doc/src/sgml/logical-replication.sgml index 23b268273b9..a9ecf483a57 100644 --- a/doc/src/sgml/logical-replication.sgml +++ b/doc/src/sgml/logical-replication.sgml @@ -117,10 +117,13 @@ or <literal>FOR ALL SEQUENCES</literal>. Unlike tables, sequences can be synchronized at any time. For more information, see <xref linkend="logical-replication-sequences"/>. When a publication is - created with <literal>FOR ALL TABLES</literal>, a table or set of tables can + created with <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal>, a table or set of tables can be explicitly excluded from publication using the <link linkend="sql-createpublication-params-for-except-table"><literal>EXCEPT</literal></link> - clause. + clause. When used with <literal>FOR TABLES IN SCHEMA</literal>, each + excluded table must belong to the schema named in the same + <literal>TABLES IN SCHEMA</literal> clause. </para> <para> diff --git a/doc/src/sgml/ref/create_publication.sgml b/doc/src/sgml/ref/create_publication.sgml index 0ac576d3f10..8715404f0cb 100644 --- a/doc/src/sgml/ref/create_publication.sgml +++ b/doc/src/sgml/ref/create_publication.sgml @@ -28,7 +28,7 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -142,6 +142,8 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <para> Marks the publication as one that replicates changes for all tables in the specified list of schemas, including tables created in the future. + Tables listed in <literal>EXCEPT</literal> for a given schema are + excluded from the publication. </para> <para> @@ -198,7 +200,11 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <listitem> <para> This clause specifies a list of tables to be excluded from the - publication. + publication. It can be used with both <literal>FOR ALL TABLES</literal> + and <literal>FOR TABLES IN SCHEMA</literal>. When used with + <literal>FOR TABLES IN SCHEMA</literal>, the excluded tables must belong + to the schema specified in the same <literal>TABLES IN SCHEMA</literal> + clause. </para> <para> For inherited tables, if <literal>ONLY</literal> is specified before the @@ -515,6 +521,15 @@ CREATE PUBLICATION production_publication FOR TABLE users, departments, TABLES I CREATE PUBLICATION sales_publication FOR TABLES IN SCHEMA marketing, sales; </programlisting></para> + <para> + Create a publication that publishes all changes for all the tables present in + the schema <structname>sales</structname>, except + <structname>sales.internal</structname> and <structname>sales.drafts</structname>: +<programlisting> +CREATE PUBLICATION sales_filtered FOR TABLES IN SCHEMA sales EXCEPT (sales.internal, sales.drafts); +</programlisting> + </para> + <para> Create a publication that publishes all changes for table <structname>users</structname>, but replicates only columns <structname>user_id</structname> and diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index a43d385c605..8e6c4015d86 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -620,19 +620,24 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, /* * Determine whether EXCEPT tables require explicit relcache invalidation. * - * For CREATE PUBLICATION with EXCEPT tables, invalidation is skipped - * here, as CreatePublication() function invalidates all relations as part - * of defining a FOR ALL TABLES publication. + * For CREATE PUBLICATION with EXCEPT tables, invalidation is skipped here + * because the excluded tables were never included in the publication, so + * no subscriber cache entry needs to be cleared. * - * For ALTER PUBLICATION, invalidation is needed only when adding an - * EXCEPT table to a publication already marked as ALL TABLES. For - * publications that were originally empty or defined as ALL SEQUENCES and - * are being converted to ALL TABLES, invalidation is skipped here, as - * AlterPublicationAllFlags() function invalidates all relations while - * marking the publication as ALL TABLES publication. + * For ALTER PUBLICATION, invalidation is needed when adding an EXCEPT + * table to either: - a FOR ALL TABLES publication (pub->alltables is + * true), or - a FOR TABLES IN SCHEMA publication (is_schema_publication + * is true). + * + * The exception: when a publication is being converted to FOR ALL TABLES + * (pub->alltables is still false at this point), + * AlterPublicationAllFlags() will perform a full invalidation, so we skip + * it here. */ - inval_except_table = (alter_stmt != NULL) && pub->alltables && - (alter_stmt->for_all_tables && pri->except); + inval_except_table = (alter_stmt != NULL) && pri->except && + (pub->alltables + ? alter_stmt->for_all_tables + : is_schema_publication(pubid)); if (!pri->except || inval_except_table) { @@ -975,7 +980,8 @@ GetIncludedPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) * Gets list of table oids that were specified in the EXCEPT clause for a * publication. * - * This should only be used FOR ALL TABLES publications. + * This is used for FOR ALL TABLES and FOR TABLES IN SCHEMA publications, + * both of which support EXCEPT TABLE. */ List * GetExcludedPublicationTables(Oid pubid, PublicationPartOpt pub_partopt) @@ -1225,22 +1231,67 @@ GetSchemaPublicationRelations(Oid schemaid, PublicationPartOpt pub_partopt) /* * Gets the list of all relations published by FOR TABLES IN SCHEMA - * publication. + * publication, excluding any tables listed in the EXCEPT clause. */ List * GetAllSchemaPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) { List *result = NIL; List *pubschemalist = GetPublicationSchemas(pubid); + List *exceptlist = NIL; ListCell *cell; + /* get the list of tables excluded via EXCEPT TABLE for this publication */ + if (pubschemalist != NIL) + exceptlist = get_publication_relations(pubid, pub_partopt, true); + foreach(cell, pubschemalist) { Oid schemaid = lfirst_oid(cell); List *schemaRels = NIL; schemaRels = GetSchemaPublicationRelations(schemaid, pub_partopt); - result = list_concat(result, schemaRels); + + if (exceptlist != NIL) + { + /* filter out any tables that appear in the EXCEPT list */ + ListCell *rlc; + + foreach(rlc, schemaRels) + { + Oid relid = lfirst_oid(rlc); + bool excluded = list_member_oid(exceptlist, relid); + + /* + * Also exclude any relation whose partition ancestor is in + * the EXCEPT list. This matters when pub_partopt is + * PUBLICATION_PART_ROOT: the except list holds only the root + * OID, but the schema scan may also return individual + * partition relations that live in the same schema. + */ + if (!excluded && get_rel_relispartition(relid)) + { + List *ancestors = get_partition_ancestors(relid); + ListCell *alc; + + foreach(alc, ancestors) + { + if (list_member_oid(exceptlist, lfirst_oid(alc))) + { + excluded = true; + break; + } + } + list_free(ancestors); + } + + if (!excluded) + result = lappend_oid(result, relid); + } + list_free(schemaRels); + } + else + result = list_concat(result, schemaRels); } return result; diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 440adb356ad..8beb806f507 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -959,6 +959,8 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) } else if (!stmt->for_all_sequences) { + List *explicitrelids = NIL; + /* FOR TABLES IN SCHEMA requires superuser */ if (schemaidlist != NIL && !superuser()) ereport(ERROR, @@ -968,6 +970,7 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) if (relations != NIL) { List *rels; + ListCell *lc; rels = OpenTableList(relations); TransformPubWhereClauses(rels, pstate->p_sourcetext, @@ -977,6 +980,20 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) schemaidlist != NIL, publish_via_partition_root); + /* + * Collect explicit table OIDs now, before we close the relation + * list, so that except-table validation below can check for + * contradictions without relying on a catalog scan that might not + * yet see the just-inserted rows. + */ + foreach(lc, rels) + { + PublicationRelInfo *pri = (PublicationRelInfo *) lfirst(lc); + + explicitrelids = lappend_oid(explicitrelids, + RelationGetRelid(pri->relation)); + } + PublicationAddTables(puboid, rels, true, NULL); CloseTableList(rels); } @@ -989,6 +1006,62 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) */ LockSchemaList(schemaidlist); PublicationAddSchemas(puboid, schemaidlist, true, NULL); + + if (exceptrelations != NIL) + { + List *rels; + ListCell *lc; + + /* + * For TABLES IN SCHEMA publications, require schema-qualified + * names to avoid ambiguity when multiple schemas in the + * publication have identically-named tables. + */ + foreach(lc, exceptrelations) + { + PublicationTable *t = (PublicationTable *) lfirst(lc); + + if (t->relation->schemaname == NULL) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" in EXCEPT clause must be schema-qualified", + t->relation->relname)); + } + + rels = OpenTableList(exceptrelations); + + /* + * Validate that each excluded table belongs to one of the + * schemas listed in this publication, and is not also in the + * explicit table list (which would be contradictory). Use the + * in-memory explicitrelids collected above rather than + * re-reading the catalog, which may not yet see the + * just-inserted rows. + */ + foreach(lc, rels) + { + PublicationRelInfo *pri = (PublicationRelInfo *) lfirst(lc); + Oid relid = RelationGetRelid(pri->relation); + Oid relns = RelationGetNamespace(pri->relation); + + if (!list_member_oid(schemaidlist, relns)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s.%s\" in EXCEPT clause does not belong to any schema listed in the publication", + get_namespace_name(relns), + RelationGetRelationName(pri->relation))); + + if (list_member_oid(explicitrelids, relid)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s.%s\" cannot appear in both the table list and the EXCEPT clause", + get_namespace_name(relns), + RelationGetRelationName(pri->relation))); + } + + PublicationAddTables(puboid, rels, true, NULL); + CloseTableList(rels); + } } } diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y index 2d1b19d1f53..e1adff0f131 100644 --- a/src/backend/parser/gram.y +++ b/src/backend/parser/gram.y @@ -457,7 +457,8 @@ static Node *makeRecursiveViewSelect(char *relname, List *aliases, Node *query); TriggerTransitions TriggerReferencing vacuum_relation_list opt_vacuum_relation_list drop_option_list pub_obj_list pub_all_obj_type_list - pub_except_obj_list opt_pub_except_clause + pub_except_obj_list pub_schema_except_obj_list + opt_pub_except_clause opt_pub_schema_except_clause %type <retclause> returning_clause %type <node> returning_option @@ -11272,7 +11273,7 @@ AlterOwnerStmt: ALTER AGGREGATE aggregate_with_argtypes OWNER TO RoleSpec * pub_obj is one of: * * TABLE table [, ...] - * TABLES IN SCHEMA schema [, ...] + * TABLES IN SCHEMA schema [EXCEPT ( table [, ...] )] [, ...] * *****************************************************************************/ @@ -11332,23 +11333,26 @@ PublicationObjSpec: $$->pubtable->columns = $3; $$->pubtable->whereClause = $4; } - | TABLES IN_P SCHEMA ColId + | TABLES IN_P SCHEMA ColId opt_pub_schema_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_SCHEMA; $$->name = $4; + $$->except_tables = $5; $$->location = @4; } - | TABLES IN_P SCHEMA CURRENT_SCHEMA + | TABLES IN_P SCHEMA CURRENT_SCHEMA opt_pub_schema_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_CUR_SCHEMA; + $$->except_tables = $5; $$->location = @4; } - | ColId opt_column_list OptWhereClause + | ColId opt_column_list OptWhereClause opt_pub_schema_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $4; /* * If either a row filter or column list is specified, create * a PublicationTable object. @@ -11392,10 +11396,11 @@ PublicationObjSpec: $$->pubtable->columns = $2; $$->pubtable->whereClause = $3; } - | CURRENT_SCHEMA + | CURRENT_SCHEMA opt_pub_schema_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $2; $$->location = @1; } ; @@ -11411,6 +11416,11 @@ opt_pub_except_clause: | /*EMPTY*/ { $$ = NIL; } ; +opt_pub_schema_except_clause: + EXCEPT '(' pub_schema_except_obj_list ')' { $$ = $3; } + | /*EMPTY*/ { $$ = NIL; } + ; + PublicationAllObjSpec: ALL TABLES opt_pub_except_clause { @@ -11451,6 +11461,13 @@ pub_except_obj_list: PublicationExceptObjSpec { $$ = lappend($1, $4); } ; +/* Like pub_except_obj_list but without opt_table; used for TABLES IN SCHEMA EXCEPT. */ +pub_schema_except_obj_list: PublicationExceptObjSpec + { $$ = list_make1($1); } + | pub_schema_except_obj_list ',' PublicationExceptObjSpec + { $$ = lappend($1, $3); } + ; + /***************************************************************************** * * ALTER PUBLICATION name SET ( options ) @@ -20784,6 +20801,8 @@ preprocess_pub_all_objtype_list(List *all_objects_list, List **pubobjects, /* * Process pubobjspec_list to check for errors in any of the objects and * convert PUBLICATIONOBJ_CONTINUATION into appropriate PublicationObjSpecType. + * Also flattens except_tables from TABLES IN SCHEMA nodes into the list so + * that ObjectsInPublicationToOids() sees them as top-level EXCEPT_TABLE entries. */ static void preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) @@ -20812,6 +20831,13 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLE) { + /* EXCEPT is not valid for table objects */ + if (pubobj->except_tables != NIL) + ereport(ERROR, + errcode(ERRCODE_SYNTAX_ERROR), + errmsg("EXCEPT is not allowed for TABLE publication objects"), + parser_errposition(pubobj->location)); + /* relation name or pubtable must be set for this type of object */ if (!pubobj->name && !pubobj->pubtable) ereport(ERROR, @@ -20860,6 +20886,10 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) errcode(ERRCODE_SYNTAX_ERROR), errmsg("invalid schema name"), parser_errposition(pubobj->location)); + + /* Flatten EXCEPT entries into the top-level list */ + pubobjspec_list = list_concat(pubobjspec_list, pubobj->except_tables); + pubobj->except_tables = NIL; } prevobjtype = pubobj->pubobjtype; diff --git a/src/backend/replication/pgoutput/pgoutput.c b/src/backend/replication/pgoutput/pgoutput.c index 4ecfcbff7ab..942ddb51d3a 100644 --- a/src/backend/replication/pgoutput/pgoutput.c +++ b/src/backend/replication/pgoutput/pgoutput.c @@ -2097,6 +2097,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) * are absorbed while decoding WAL. */ List *schemaPubids = GetSchemaPublications(schemaId); + List *schemaExceptPubids; ListCell *lc; Oid publish_as_relid = relid; int publish_ancestor_level = 0; @@ -2104,6 +2105,25 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) char relkind = get_rel_relkind(relid); List *rel_publications = NIL; + /* + * For the schema EXCEPT check, we must look up the top-most ancestor + * rather than the relation itself. check_publication_add_relation() + * prevents individual partitions from appearing in the EXCEPT clause, + * so only a root (non-partition) table can have prexcept = true. + * Using the partition's own OID would always return NIL and miss the + * exclusion. + */ + if (am_partition) + { + List *pancestore = get_partition_ancestors(relid); + + schemaExceptPubids = + GetRelationExcludedPublications(llast_oid(pancestore)); + list_free(pancestore); + } + else + schemaExceptPubids = GetRelationExcludedPublications(relid); + /* Reload publications if needed before use. */ if (!publications_valid) { @@ -2269,7 +2289,15 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) ancestors, &level); - if (ancestor != InvalidOid) + /* + * The ancestor is only considered published if it is not + * in the EXCEPT clause of this schema publication. + * GetTopMostAncestorInPublication checks schema + * membership but does not account for the EXCEPT list, so + * we must filter that out here. + */ + if (ancestor != InvalidOid && + !list_member_oid(schemaExceptPubids, pub->oid)) { ancestor_published = true; if (pub->pubviaroot) @@ -2281,7 +2309,8 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) } if (list_member_oid(pubids, pub->oid) || - list_member_oid(schemaPubids, pub->oid) || + (list_member_oid(schemaPubids, pub->oid) && + !list_member_oid(schemaExceptPubids, pub->oid)) || ancestor_published) publish = true; } @@ -2360,6 +2389,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) list_free(pubids); list_free(schemaPubids); + list_free(schemaExceptPubids); list_free(rel_publications); entry->replicate_valid = true; diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c index 1ca03d6b278..a1ca6edd80d 100644 --- a/src/bin/pg_dump/pg_dump.c +++ b/src/bin/pg_dump/pg_dump.c @@ -5019,6 +5019,7 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) PublicationInfo *pubinfo = pubsinfo->publication; PQExpBuffer query; char *tag; + bool first_except = true; /* Do nothing if not dumping schema */ if (!dopt->dumpSchema) @@ -5029,7 +5030,34 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) query = createPQExpBuffer(); appendPQExpBuffer(query, "ALTER PUBLICATION %s ", fmtId(pubinfo->dobj.name)); - appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s;\n", fmtId(schemainfo->dobj.name)); + appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s", fmtId(schemainfo->dobj.name)); + + /* + * Append EXCEPT clause for any tables that belong to this schema + * and are excluded from the publication. + */ + for (SimplePtrListCell *cell = pubinfo->except_tables.head; cell; cell = cell->next) + { + TableInfo *tbinfo = (TableInfo *) cell->ptr; + + if (strcmp(tbinfo->dobj.namespace->dobj.name, schemainfo->dobj.name) == 0) + { + if (first_except) + { + appendPQExpBufferStr(query, " EXCEPT ("); + first_except = false; + } + else + appendPQExpBufferStr(query, ", "); + + appendPQExpBuffer(query, "ONLY %s", fmtQualifiedDumpable(tbinfo)); + } + } + + if (!first_except) + appendPQExpBufferStr(query, ")"); + + appendPQExpBufferStr(query, ";\n"); /* * There is no point in creating drop query as the drop is done by schema diff --git a/src/bin/pg_dump/t/002_pg_dump.pl b/src/bin/pg_dump/t/002_pg_dump.pl index 3bc8e51561d..2a0546b9dc9 100644 --- a/src/bin/pg_dump/t/002_pg_dump.pl +++ b/src/bin/pg_dump/t/002_pg_dump.pl @@ -3242,6 +3242,42 @@ my %tests = ( like => { %full_runs, section_post_data => 1, }, }, + 'CREATE PUBLICATION pub11' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub11 FOR TABLES IN SCHEMA dump_test EXCEPT (dump_test.test_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub11 WITH (publish = 'insert, update, delete, truncate');\E + /xm, + like => { %full_runs, section_post_data => 1, }, + }, + + 'ALTER PUBLICATION pub11 ADD TABLES IN SCHEMA dump_test EXCEPT (dump_test.test_table)' + => { + regexp => qr/^ + \QALTER PUBLICATION pub11 ADD TABLES IN SCHEMA dump_test EXCEPT (ONLY dump_test.test_table);\E + /xm, + like => { %full_runs, section_post_data => 1, }, + }, + + 'CREATE PUBLICATION pub12' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub12 FOR TABLES IN SCHEMA dump_test EXCEPT (dump_test.test_table, dump_test.test_second_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub12 WITH (publish = 'insert, update, delete, truncate');\E + /xm, + like => { %full_runs, section_post_data => 1, }, + }, + + 'ALTER PUBLICATION pub12 ADD TABLES IN SCHEMA dump_test EXCEPT (dump_test.test_table, dump_test.test_second_table)' + => { + regexp => qr/^ + \QALTER PUBLICATION pub12 ADD TABLES IN SCHEMA dump_test EXCEPT (ONLY dump_test.test_table, ONLY dump_test.test_second_table);\E + /xm, + like => { %full_runs, section_post_data => 1, }, + }, + 'CREATE SUBSCRIPTION sub1' => { create_order => 50, create_sql => 'CREATE SUBSCRIPTION sub1 @@ -5279,7 +5315,7 @@ foreach my $run (sort keys %pgdump_runs) # # Either "all_runs" should be set or there should be a "like" list, # even if it is empty. (This makes the test more self-documenting.) - if (!defined($tests{$test}->{all_runs}) + if ( !defined($tests{$test}->{all_runs}) && !defined($tests{$test}->{like})) { die "missing \"like\" in test \"$test\""; diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c index dd1179ef927..b751206e5a4 100644 --- a/src/bin/psql/describe.c +++ b/src/bin/psql/describe.c @@ -7038,6 +7038,24 @@ describePublications(const char *pattern) if (!addFooterToPublicationDesc(&buf, _("Tables from schemas:"), true, &cont)) goto error_return; + + if (pset.sversion >= 190000) + { + /* + * Get tables in the EXCEPT clause for this schema + * publication. + */ + printfPQExpBuffer(&buf, + "SELECT concat(c.relnamespace::regnamespace, '.', c.relname)\n" + "FROM pg_catalog.pg_class c\n" + " JOIN pg_catalog.pg_publication_rel pr ON c.oid = pr.prrelid\n" + "WHERE pr.prpubid = '%s'\n" + " AND pr.prexcept\n" + "ORDER BY 1", pubid); + if (!addFooterToPublicationDesc(&buf, _("Except tables:"), + true, &cont)) + goto error_return; + } } } else diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index 9990f818942..166d03e3a1f 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -3784,8 +3784,16 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); - else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && (!ends_with(prev_wd, ','))) - COMPLETE_WITH("WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT (", "WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", MatchAnyN) && ends_with(prev_wd, ',')) + COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* Complete "CREATE PUBLICATION <name> [...] WITH" */ else if (Matches("CREATE", "PUBLICATION", MatchAnyN, "WITH", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h index 91377a6cde3..a9177de0d43 100644 --- a/src/include/nodes/parsenodes.h +++ b/src/include/nodes/parsenodes.h @@ -4493,6 +4493,7 @@ typedef struct PublicationObjSpec PublicationObjSpecType pubobjtype; /* type of this publication object */ char *name; PublicationTable *pubtable; + List *except_tables; /* tables to exclude (for TABLES IN SCHEMA) */ ParseLoc location; /* token location, or -1 if unknown */ } PublicationObjSpec; diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index d028e9be866..f6aadc1e835 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -461,7 +461,47 @@ HINT: Change the publication's EXCEPT clause using ALTER PUBLICATION ... SET AL RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + Publication testpub_schema_except1 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- Exclude multiple tables from a schema publication +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (pub_test.testpub_nopk, pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except2 + Publication testpub_schema_except2 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_nopk" + "pub_test.testpub_tbl_s1" + +-- fail: EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2 EXCEPT (pub_test.testpub_nopk); +ERROR: EXCEPT is not allowed for TABLE publication objects +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2; CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; -- FOR ALL SEQUENCES diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 642e32fa098..3f46e8c5e03 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -218,7 +218,32 @@ RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); + +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + +-- Exclude multiple tables from a schema publication +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (pub_test.testpub_nopk, pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except2 + +-- fail: EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2 EXCEPT (pub_test.testpub_nopk); + +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2; + CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 8c58d282eee..0801d3a77c7 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -24,14 +24,16 @@ my $result; sub test_except_root_partition { - my ($pubviaroot) = @_; + my ($pubviaroot, $pubsql) = @_; + $pubsql //= + "CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1) WITH (publish_via_partition_root = $pubviaroot)"; # If the root partitioned table is in the EXCEPT clause, all its # partitions are excluded from publication, regardless of the # publish_via_partition_root setting. $node_publisher->safe_psql( 'postgres', qq( - CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1) WITH (publish_via_partition_root = $pubviaroot); + $pubsql; INSERT INTO root1 VALUES (1), (101); )); $node_subscriber->safe_psql('postgres', @@ -223,6 +225,138 @@ $node_subscriber->safe_psql( test_except_root_partition('false'); test_except_root_partition('true'); +# Same validation using TABLES IN SCHEMA instead of FOR ALL TABLES. +my $schema_pub = + "CREATE PUBLICATION tap_pub_part FOR TABLES IN SCHEMA public EXCEPT (public.root1)"; +test_except_root_partition('false', + "$schema_pub WITH (publish_via_partition_root = false)"); +test_except_root_partition('true', + "$schema_pub WITH (publish_via_partition_root = true)"); + +# ============================================ +# EXCEPT test cases for TABLES IN SCHEMA +# ============================================ + +# Create a dedicated schema with two tables: one to be published and one to be +# excluded. Also create inherited tables to verify ONLY semantics. +$node_publisher->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_pub AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.tab_exc AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.par (a int); + CREATE TABLE sch1.chi (b int) INHERITS (sch1.par); +)); + +$node_subscriber->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_pub (a int); + CREATE TABLE sch1.tab_exc (a int); + CREATE TABLE sch1.par (a int); + CREATE TABLE sch1.chi (b int) INHERITS (sch1.par); +)); + +# Basic test: initial sync respects EXCEPT. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (sch1.tab_exc)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_pub"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: initial sync copies included table'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_exc"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: initial sync skips excluded table'); + +# DML: only the included table should be replicated. +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_pub VALUES (6); + INSERT INTO sch1.tab_exc VALUES (6); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_pub"); +is($result, qq(6), + 'TABLES IN SCHEMA EXCEPT: DML on included table is replicated'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_exc"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: DML on excluded table is not replicated'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Inherited tables: excluding the parent (without ONLY) also excludes the child. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (sch1.par)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.chi VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.chi"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: excluding parent (without ONLY) also excludes child' +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Truncate chi on the publisher so the next test starts with a clean slate. +# (The previous test inserted rows into chi that would otherwise be copied by +# the initial table sync of the next subscription.) +$node_publisher->safe_psql('postgres', 'TRUNCATE sch1.chi'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE sch1.chi'); +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (ONLY sch1.par)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.chi VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.chi"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: ONLY parent in EXCEPT does not exclude child' +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); +$node_publisher->safe_psql('postgres', + 'TRUNCATE sch1.par, sch1.chi, sch1.tab_exc'); +$node_subscriber->safe_psql('postgres', + 'TRUNCATE sch1.par, sch1.chi, sch1.tab_pub, sch1.tab_exc'); + +# Cleanup schema tables before the multi-publication section. +$node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); +$node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); + # ============================================ # Test when a subscription is subscribing to multiple publications # ============================================ @@ -254,6 +388,7 @@ $node_publisher->safe_psql( DROP PUBLICATION tap_pub2; TRUNCATE tab1; )); +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_subscriber->safe_psql('postgres', qq(TRUNCATE tab1)); # OK when a table is excluded by pub1 EXCEPT clause, but it is included by pub2 -- 2.50.1 (Apple Git-155)
v1-0002-Add-EXCEPT-support-to-ALTER-PUBLICATION-ADD-TABLE.patch (application/octet-stream, 15.5K) download From 12b32acd846309f745498923fab2852e3c986766 Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Tue, 14 Apr 2026 11:04:44 +0530 Subject: [PATCH v1 2/3] Add EXCEPT support to ALTER PUBLICATION ADD TABLES IN SCHEMA Extend the EXCEPT clause support to allow tables to be excluded when adding a schema to a publication via ALTER PUBLICATION ... ADD: Syntax: ALTER PUBLICATION pub ADD TABLES IN SCHEMA s EXCEPT (s.t1, s.t2); --- doc/src/sgml/ref/alter_publication.sgml | 48 +++++++- src/backend/commands/publicationcmds.c | 136 +++++++++++++++++++++- src/test/regress/expected/publication.out | 20 +++- src/test/regress/sql/publication.sql | 11 +- src/test/subscription/t/037_except.pl | 28 +++++ 5 files changed, 239 insertions(+), 4 deletions(-) diff --git a/doc/src/sgml/ref/alter_publication.sgml b/doc/src/sgml/ref/alter_publication.sgml index aa32bb169e9..54e1cba4b70 100644 --- a/doc/src/sgml/ref/alter_publication.sgml +++ b/doc/src/sgml/ref/alter_publication.sgml @@ -31,7 +31,7 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -54,6 +54,10 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <phrase>and <replaceable class="parameter">table_object</replaceable> is:</phrase> [ ONLY ] <replaceable class="parameter">table_name</replaceable> [ * ] + +<phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> + + [ ONLY ] <replaceable class="parameter">table_name</replaceable> [ * ] </synopsis> </refsynopsisdiv> @@ -110,6 +114,21 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <literal>ADD TABLE</literal>. </para> + <para> + The <literal>EXCEPT</literal> clause can be used with + <literal>ADD TABLES IN SCHEMA</literal> and + <literal>SET TABLES IN SCHEMA</literal> to exclude specific tables from a + schema-level publication. Each excluded table must belong to the schema + named in the same <literal>TABLES IN SCHEMA</literal> clause and must be + schema-qualified. <literal>EXCEPT</literal> is not supported with + <literal>DROP TABLES IN SCHEMA</literal>; instead, dropping a schema from + the publication automatically removes all of its associated + <literal>EXCEPT</literal> entries. To clear the + <literal>EXCEPT</literal> list for a schema without removing the schema + itself, use <literal>SET TABLES IN SCHEMA</literal> without an + <literal>EXCEPT</literal> clause. + </para> + <para> The fourth variant of this command listed in the synopsis can change all of the publication properties specified in @@ -198,6 +217,23 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r </listitem> </varlistentry> + <varlistentry> + <term><literal>EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] )</literal></term> + <listitem> + <para> + Specifies tables to be excluded from a schema-level publication entry. + This clause may be used with <literal>ADD TABLES IN SCHEMA</literal> + and <literal>SET TABLES IN SCHEMA</literal>, but not with + <literal>DROP TABLES IN SCHEMA</literal>. Each named table must + belong to the schema specified in the same + <literal>TABLES IN SCHEMA</literal> clause and must be + schema-qualified. See + <xref linkend="sql-createpublication"/> for further details on the + semantics of <literal>EXCEPT</literal>. + </para> + </listitem> + </varlistentry> + <varlistentry> <term><literal>SET ( <replaceable class="parameter">publication_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] )</literal></term> <listitem> @@ -288,6 +324,16 @@ ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA marketing, sales; </programlisting> </para> + <para> + Add schema <structname>sales</structname> to the publication + <structname>sales_publication</structname>, excluding the + <structname>sales.internal</structname> and + <structname>sales.drafts</structname> tables: +<programlisting> +ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA sales EXCEPT (sales.internal, sales.drafts); +</programlisting> + </para> + <para> Add tables <structname>users</structname>, <structname>departments</structname> and schema diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 8beb806f507..fd73511220d 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -70,6 +70,9 @@ static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok); static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); +static void AlterPublicationExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, List *exceptrelations, + List *schemaidlist); static char defGetGeneratedColsOption(DefElem *def); @@ -1549,6 +1552,13 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, } PublicationAddSchemas(pubform->oid, schemaidlist, false, stmt); + + /* + * Increment the command counter so that is_schema_publication() in + * GetExcludedPublicationTables() can see the just-inserted schema + * rows when AlterPublicationExceptTables runs next. + */ + CommandCounterIncrement(); } else if (stmt->action == AP_DropObjects) PublicationDropSchemas(pubform->oid, schemaidlist, false); @@ -1574,6 +1584,123 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, * skip existing ones when doing catalog update. */ PublicationAddSchemas(pubform->oid, schemaidlist, true, stmt); + + /* + * Increment the command counter so that is_schema_publication() in + * GetExcludedPublicationTables() can see the just-inserted schema + * rows when AlterPublicationExceptTables runs next. + */ + CommandCounterIncrement(); + } +} + +/* + * Alter the EXCEPT list of a publication. + * + * Adds, removes, or replaces except-table entries in pg_publication_rel + * (rows with prexcept = true). These entries suppress publication of the + * named tables that would otherwise be covered by a FOR TABLES IN SCHEMA + * or FOR ALL TABLES clause. + */ +static void +AlterPublicationExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, List *exceptrelations, + List *schemaidlist) +{ + Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); + Oid pubid = pubform->oid; + + /* + * Nothing to do if no EXCEPT entries. + */ + if (!exceptrelations) + return; + + /* + * This function handles EXCEPT entries for schema-level publications + * only. For FOR ALL TABLES publications, EXCEPT entries are already + * processed by AlterPublicationTables(). + */ + if (schemaidlist == NIL && !is_schema_publication(pubid)) + return; + + /* + * EXCEPT is not meaningful with DROP: dropping a schema from a + * publication already removes all its except entries via cascade, and + * there is no sensible interpretation of "drop only the except entry but + * keep the schema". + */ + if (stmt->action == AP_DropObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); + + /* + * For TABLES IN SCHEMA publications, require schema-qualified names to + * avoid ambiguity when multiple schemas have identically-named tables. + * This does not apply to FOR ALL TABLES publications. + */ + if (exceptrelations != NIL && + (schemaidlist != NIL || is_schema_publication(pubid))) + { + ListCell *lc; + + foreach(lc, exceptrelations) + { + PublicationTable *t = (PublicationTable *) lfirst(lc); + + if (t->relation->schemaname == NULL) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" in EXCEPT clause must be schema-qualified", + t->relation->relname)); + } + } + + if (stmt->action == AP_AddObjects) + { + List *rels; + List *explicitrelids; + List *pubschemaidlist; + ListCell *lc; + + rels = OpenTableList(exceptrelations); + + /* + * Build the effective schema list: schemas already in the publication + * plus any being added in this same command. The latter may not yet + * be visible via a catalog scan if CommandCounterIncrement has not + * been issued, so we include them explicitly. + */ + pubschemaidlist = GetPublicationSchemas(pubid); + pubschemaidlist = list_concat_unique_oid(pubschemaidlist, schemaidlist); + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + foreach(lc, rels) + { + PublicationRelInfo *pri = (PublicationRelInfo *) lfirst(lc); + Oid relid = RelationGetRelid(pri->relation); + Oid relns = RelationGetNamespace(pri->relation); + + if (!list_member_oid(pubschemaidlist, relns)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s.%s\" in EXCEPT clause does not belong to any schema listed in the publication", + get_namespace_name(relns), + RelationGetRelationName(pri->relation))); + + if (list_member_oid(explicitrelids, relid)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s.%s\" cannot appear in both the table list and the EXCEPT clause", + get_namespace_name(relns), + RelationGetRelationName(pri->relation))); + } + + PublicationAddTables(pubid, rels, false, stmt); + + CloseTableList(rels); } } @@ -1784,10 +1911,17 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) errmsg("publication \"%s\" does not exist", stmt->pubname)); - relations = list_concat(relations, exceptrelations); + /* + * For FOR ALL TABLES, EXCEPT entries are processed by + * AlterPublicationTables(), so merge them in. For TABLES IN SCHEMA, + * they are handled separately by AlterPublicationExceptTables(). + */ + if (stmt->for_all_tables) + relations = list_concat(relations, exceptrelations); AlterPublicationTables(stmt, tup, relations, pstate->p_sourcetext, schemaidlist != NIL); AlterPublicationSchemas(stmt, tup, schemaidlist); + AlterPublicationExceptTables(stmt, tup, exceptrelations, schemaidlist); AlterPublicationAllFlags(stmt, rel, tup); } diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index f6aadc1e835..e563553e8eb 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -499,9 +499,27 @@ Except tables: CREATE PUBLICATION testpub_except_err FOR TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2 EXCEPT (pub_test.testpub_nopk); ERROR: EXCEPT is not allowed for TABLE publication objects +LINE 2: FOR TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2 EXCEPT... + ^ +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; +-- ADD: add a schema with an excepted table +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (pub_test.testpub_tbl_s1); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_alter_except; CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; -- FOR ALL SEQUENCES diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 3f46e8c5e03..3436b832eca 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -240,9 +240,18 @@ CREATE PUBLICATION testpub_schema_except2 CREATE PUBLICATION testpub_except_err FOR TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2 EXCEPT (pub_test.testpub_nopk); +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; + +-- ADD: add a schema with an excepted table +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (pub_test.testpub_tbl_s1); +\dRp+ testpub_alter_except + RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_alter_except; CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 0801d3a77c7..9675db18bef 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -353,6 +353,34 @@ $node_publisher->safe_psql('postgres', $node_subscriber->safe_psql('postgres', 'TRUNCATE sch1.par, sch1.chi, sch1.tab_pub, sch1.tab_exc'); +# ============================================ +# ALTER PUBLICATION EXCEPT for TABLES IN SCHEMA +# ============================================ + +# ADD: add a schema with an excepted table; verify the except entry takes effect. +$node_publisher->safe_psql('postgres', "CREATE PUBLICATION sch_pub"); +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub ADD TABLES IN SCHEMA sch1 EXCEPT (sch1.tab_exc)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_pub"); +is($result, qq(6), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: included table synced'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_exc"); +is($result, qq(0), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + # Cleanup schema tables before the multi-publication section. $node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); $node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); -- 2.50.1 (Apple Git-155)
v1-0003-Add-EXCEPT-support-to-ALTER-PUBLICATION-SET-TABLE.patch (application/octet-stream, 14.8K) download From 197d69c52b7946a1e17d122fa037db5d5194ed4f Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Tue, 14 Apr 2026 11:34:07 +0530 Subject: [PATCH v1 3/3] Add EXCEPT support to ALTER PUBLICATION SET TABLES IN SCHEMA Extend AlterPublicationExceptTables() with the AP_SetObjects case, which redefine the publication and replaces the entire EXCEPT list. Syntax: ALTER PUBLICATION pub SET TABLES IN SCHEMA s EXCEPT (s.t1, s.t2); --- src/backend/catalog/pg_publication.c | 2 +- src/backend/commands/publicationcmds.c | 145 +++++++++++++++++++++- src/test/regress/expected/publication.out | 21 ++++ src/test/regress/sql/publication.sql | 12 ++ src/test/subscription/t/037_except.pl | 90 ++++++++++++++ 5 files changed, 267 insertions(+), 3 deletions(-) diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index 8e6c4015d86..c03548413e8 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -986,7 +986,7 @@ GetIncludedPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) List * GetExcludedPublicationTables(Oid pubid, PublicationPartOpt pub_partopt) { - Assert(GetPublication(pubid)->alltables); + Assert(GetPublication(pubid)->alltables || is_schema_publication(pubid)); return get_publication_relations(pubid, pub_partopt, true); } diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index fd73511220d..bde99d6bb90 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -1611,9 +1611,11 @@ AlterPublicationExceptTables(AlterPublicationStmt *stmt, Oid pubid = pubform->oid; /* - * Nothing to do if no EXCEPT entries. + * Nothing to do if no EXCEPT entries, except in SET: for that it is + * quite possible that the user has removed all exceptions, in which case + * we need to drop any existing ones. */ - if (!exceptrelations) + if (!exceptrelations && stmt->action != AP_SetObjects) return; /* @@ -1700,6 +1702,106 @@ AlterPublicationExceptTables(AlterPublicationStmt *stmt, PublicationAddTables(pubid, rels, false, stmt); + CloseTableList(rels); + } + else /* AP_SetObjects */ + { + List *oldexceptrelids = NIL; + List *newexceptrelids = NIL; + List *delrelids = NIL; + List *rels; + List *explicitrelids; + List *pubschemaidlist; + ListCell *lc; + + rels = OpenTableList(exceptrelations); + + /* Collect OIDs of the desired new except list. */ + foreach(lc, rels) + { + PublicationRelInfo *pri = (PublicationRelInfo *) lfirst(lc); + + newexceptrelids = lappend_oid(newexceptrelids, + RelationGetRelid(pri->relation)); + } + + /* + * Build the effective schema list: schemas already in the publication + * plus any being set in this same command. The latter may not yet be + * visible via a catalog scan, so we include them explicitly. + */ + pubschemaidlist = GetPublicationSchemas(pubid); + pubschemaidlist = list_concat_unique_oid(pubschemaidlist, schemaidlist); + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + foreach(lc, rels) + { + PublicationRelInfo *pri = (PublicationRelInfo *) lfirst(lc); + Oid relid = RelationGetRelid(pri->relation); + Oid relns = RelationGetNamespace(pri->relation); + + if (!list_member_oid(pubschemaidlist, relns)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s.%s\" in EXCEPT clause does not belong to any schema listed in the publication", + get_namespace_name(relns), + RelationGetRelationName(pri->relation))); + + if (list_member_oid(explicitrelids, relid)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s.%s\" cannot appear in both the table list and the EXCEPT clause", + get_namespace_name(relns), + RelationGetRelationName(pri->relation))); + } + + /* + * Get the current set of except entries. Only FOR ALL TABLES and + * schema-level publications can have except entries; for any other + * publication type oldexceptrelids stays NIL. + * + * Note: we check is_schema_publication() against the current catalog + * state (before AlterPublicationSchemas has run), so if the caller is + * doing SET TABLE t1 to convert a schema publication into a plain table + * publication, is_schema_publication() still returns true here. That + * is intentional: it lets us discover and clean up any stale except + * entries that belong to the old schema definition. + */ + if (GetPublication(pubid)->alltables || is_schema_publication(pubid)) + oldexceptrelids = GetExcludedPublicationTables(pubid, + PUBLICATION_PART_ROOT); + + /* Build a list of old except entries not present in the new list. */ + foreach(lc, oldexceptrelids) + { + Oid oldrelid = lfirst_oid(lc); + + if (!list_member_oid(newexceptrelids, oldrelid)) + delrelids = lappend_oid(delrelids, oldrelid); + } + + /* Drop old except entries not present in the new list. */ + foreach(lc, delrelids) + { + Oid relid = lfirst_oid(lc); + Oid proid; + ObjectAddress obj; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (!OidIsValid(proid)) + continue; /* already gone */ + + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + + /* Add new except entries, skipping any already present. */ + PublicationAddTables(pubid, rels, true, stmt); + CloseTableList(rels); } } @@ -2354,6 +2456,8 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) foreach(lc, schemas) { Oid schemaid = lfirst_oid(lc); + List *exceptoids; + ListCell *elc; psid = GetSysCacheOid2(PUBLICATIONNAMESPACEMAP, Anum_pg_publication_namespace_oid, @@ -2370,8 +2474,45 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) get_namespace_name(schemaid)))); } + /* + * Collect prexcept rows for tables belonging to this schema before + * removing the schema entry. GetExcludedPublicationTables relies on + * is_schema_publication(), which scans pg_publication_namespace; if + * this is the last schema in the publication, performDeletion() below + * would remove that row and make is_schema_publication() return + * false, tripping the assertion. + */ + exceptoids = GetExcludedPublicationTables(pubid, PUBLICATION_PART_ROOT); + ObjectAddressSet(obj, PublicationNamespaceRelationId, psid); performDeletion(&obj, DROP_CASCADE, 0); + + /* + * Drop any prexcept rows for tables belonging to this schema. These + * rows have no pg_depend entry pointing at the + * pg_publication_namespace row, so they are not cascaded by the + * performDeletion() call above and must be cleaned up explicitly. + */ + foreach(elc, exceptoids) + { + Oid relid = lfirst_oid(elc); + Oid proid; + + if (get_rel_namespace(relid) != schemaid) + continue; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (!OidIsValid(proid)) + continue; /* already gone */ + + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + + list_free(exceptoids); } } diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index e563553e8eb..f346e77ee57 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -517,6 +517,27 @@ Tables from schemas: Except tables: "pub_test.testpub_tbl_s1" +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s2" + +-- error: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (pub_test.testpub_tbl_s2); +ERROR: EXCEPT clause is not supported with DROP in ALTER PUBLICATION +-- error: except table must be schema-qualified +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (testpub_tbl_s1); +ERROR: table "testpub_tbl_s1" in EXCEPT clause must be schema-qualified +-- error: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to any schema listed in the publication RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_alter_except; diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 3436b832eca..6de78800aa5 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -249,6 +249,18 @@ CREATE PUBLICATION testpub_alter_except; ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (pub_test.testpub_tbl_s1); \dRp+ testpub_alter_except +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + +-- error: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (pub_test.testpub_tbl_s2); + +-- error: except table must be schema-qualified +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (testpub_tbl_s1); +-- error: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (public.testpub_tbl1); + RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_alter_except; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 9675db18bef..e622bfb3d7f 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -378,6 +378,66 @@ $result = is($result, qq(0), 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); +# SET: replace the except list; tab_exc is now included and tab_pub is excluded. +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1 EXCEPT (sch1.tab_pub)" +); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_pub VALUES (7); + INSERT INTO sch1.tab_exc VALUES (7); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_exc"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: newly included table is replicated' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_pub"); +is($result, qq(6), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: now-excluded table is not replicated' +); + +# SET without EXCEPT: clears the except list; both tables are now published. +# tab_pub will be re-synced because REFRESH removed its entry when it was +# excluded. Truncate the subscriber copy beforehand so the re-sync produces +# a predictable count: publisher has 7 rows (6 original + INSERT(7)), so the +# subscriber ends up with 7 after re-sync, then 8 after INSERT(8). +$node_subscriber->safe_psql('postgres', 'TRUNCATE sch1.tab_pub'); +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1"); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_pub VALUES (8); + INSERT INTO sch1.tab_exc VALUES (8); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_pub"); +is($result, qq(8), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_pub replicated after except list cleared' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_exc"); +is($result, qq(2), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_exc replicated after except list cleared' +); + $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); @@ -445,6 +505,36 @@ $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); +# OK when a table is excluded by a TABLES IN SCHEMA EXCEPT publication, +# but is included by another publication. +$node_publisher->safe_psql('postgres', 'TRUNCATE tab1'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE tab1'); + +$node_publisher->safe_psql( + 'postgres', qq( + CREATE PUBLICATION tap_pub1 FOR TABLES IN SCHEMA public EXCEPT (public.tab1); + CREATE PUBLICATION tap_pub2 FOR TABLE tab1; + INSERT INTO tab1 VALUES(1); +)); +$node_subscriber->psql('postgres', + "CREATE SUBSCRIPTION tap_sub CONNECTION '$publisher_connstr' PUBLICATION tap_pub1, tap_pub2" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'tap_sub'); + +$node_publisher->safe_psql('postgres', qq(INSERT INTO tab1 VALUES(2))); +$node_publisher->wait_for_catchup('tap_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT * FROM tab1 ORDER BY a"); +is( $result, qq(1 +2), + "TABLES IN SCHEMA EXCEPT: table excluded in schema pub but included by another pub is replicated" +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); + $node_publisher->stop('fast'); done_testing(); -- 2.50.1 (Apple Git-155)
^ permalink raw reply [nested|flat] 196+ messages in thread

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-04-14 07:32  Peter Smith <smithpb2250@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  3 siblings, 3 replies; 196+ messages in thread

From: Peter Smith @ 2026-04-14 07:32 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Tue, Apr 14, 2026 at 4:30 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
>
> Hi hackers,
>
> Following earlier work to support EXCEPT for FOR ALL TABLES [1]
> publications, starting this thread to extend the same capability to
> schema-level publications (TABLES IN SCHEMA).

Hi Nisha.

+1 for adding this new kind of exclusion clause to CREATE PUBLICATION command.

>
> Currently, TABLES IN SCHEMA publishes all tables in a schema with no
> way to exclude a subset. Users who want to skip a few tables must
> switch to an explicit FOR TABLE list, which loses the convenience of
> schema-level publishing and requires ongoing maintenance as tables are
> added.
>
> Proposed syntax:
> ------------------------
> CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1 EXCEPT (s1.t1, s1.t2);
> ALTER PUBLICATION pub ADD TABLES IN SCHEMA s1 EXCEPT (s1.t1);
> ALTER PUBLICATION pub SET TABLES IN SCHEMA s1 EXCEPT (s1.t1);
>
> Note: Tables in the EXCEPT clause must be schema-qualified to avoid
> ambiguity and must belong to the published schema; otherwise, an error
> is raised.
>

The proposed syntax is almost, but not quite, what I was anticipating.
IMO the syntax shouldn't just be similar to the FOR ALL TABLES EXCEPT;
It can be *identical* to it. e.g., your examples are missing the
'TABLE' keyword necessary to achieve the same command flexibility.

Furthermore, what is the ambiguity referred to? An excluded table is
clearly associated with the preceding schema. Can't the code infer the
schema internally even when it is not provided by the user? Of course,
the user *can* specify a schema-qualified name if they want to, but I
didn't see why we are forcing that rule upon them.

e.g.

-- Syntax can be *identical* to the "EXCEPT (TABLE ...)" clause already pushed.
-- Both of these below are equivalent.
CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1 EXCEPT (TABLE t1, t2, t3);
CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1 EXCEPT (TABLE t1, TABLE
t2, TABLE t3);

--  Below is an example of multiple schemas and multiple except clauses:
-- publish all tables of schema s1 except s1.t1 and s1.t2
-- publish all tables of schema s2
-- publish all tables of schema s3 except table s3.t2 (how is this
ambiguous with the excluded s1.t2?)
CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1 EXCEPT (TABLE t1, t2),
s2, s3 EXCEPT (TABLE t2);

======
Kind Regards,
Peter Smith.
Fujitsu Australia.





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-04-14 07:51  Amit Kapila <amit.kapila16@gmail.com>
  parent: Peter Smith <smithpb2250@gmail.com>
  2 siblings, 1 reply; 196+ messages in thread

From: Amit Kapila @ 2026-04-14 07:51 UTC (permalink / raw)
  To: Peter Smith <smithpb2250@gmail.com>; +Cc: Nisha Moond <nisha.moond412@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Tue, Apr 14, 2026 at 1:03 PM Peter Smith <smithpb2250@gmail.com> wrote:
>
>
> -- Syntax can be *identical* to the "EXCEPT (TABLE ...)" clause already pushed.
> -- Both of these below are equivalent.
> CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1 EXCEPT (TABLE t1, t2, t3);
> CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1 EXCEPT (TABLE t1, TABLE
> t2, TABLE t3);
>
> --  Below is an example of multiple schemas and multiple except clauses:
> -- publish all tables of schema s1 except s1.t1 and s1.t2
> -- publish all tables of schema s2
> -- publish all tables of schema s3 except table s3.t2 (how is this
> ambiguous with the excluded s1.t2?)
> CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1 EXCEPT (TABLE t1, t2),
> s2, s3 EXCEPT (TABLE t2);
>

We can go in the direction as proposed by you but my preference would
be to avoid using EXCEPT keyword multiple times.

-- 
With Regards,
Amit Kapila.





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-04-14 08:09  Peter Smith <smithpb2250@gmail.com>
  parent: Amit Kapila <amit.kapila16@gmail.com>
  0 siblings, 0 replies; 196+ messages in thread

From: Peter Smith @ 2026-04-14 08:09 UTC (permalink / raw)
  To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: Nisha Moond <nisha.moond412@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Tue, Apr 14, 2026 at 5:52 PM Amit Kapila <amit.kapila16@gmail.com> wrote:
>
> On Tue, Apr 14, 2026 at 1:03 PM Peter Smith <smithpb2250@gmail.com> wrote:
> >
> >
> > -- Syntax can be *identical* to the "EXCEPT (TABLE ...)" clause already pushed.
> > -- Both of these below are equivalent.
> > CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1 EXCEPT (TABLE t1, t2, t3);
> > CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1 EXCEPT (TABLE t1, TABLE
> > t2, TABLE t3);
> >
> > --  Below is an example of multiple schemas and multiple except clauses:
> > -- publish all tables of schema s1 except s1.t1 and s1.t2
> > -- publish all tables of schema s2
> > -- publish all tables of schema s3 except table s3.t2 (how is this
> > ambiguous with the excluded s1.t2?)
> > CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1 EXCEPT (TABLE t1, t2),
> > s2, s3 EXCEPT (TABLE t2);
> >
>
> We can go in the direction as proposed by you but my preference would
> be to avoid using EXCEPT keyword multiple times.
>
> --

Using the "EXCEPT keyword multiple times" wasn't anything different
proposed by me. That was already part of the original post.

e.g. in the 3rd example.

------
Supported:
  CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1 EXCEPT (s1.t1), TABLE s2.t1;
  CREATE PUBLICATION pub FOR TABLE s2.t1, TABLES IN SCHEMA s1 EXCEPT (s1.t1);
  CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1 EXCEPT (s1.t1), s2
EXCEPT (s2.t1);
------

======
Kind Regards,
Peter Smith.
Fujitsu Australia





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-04-14 08:34  shveta malik <shveta.malik@gmail.com>
  parent: Peter Smith <smithpb2250@gmail.com>
  2 siblings, 1 reply; 196+ messages in thread

From: shveta malik @ 2026-04-14 08:34 UTC (permalink / raw)
  To: Peter Smith <smithpb2250@gmail.com>; +Cc: Nisha Moond <nisha.moond412@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>; shveta malik <shveta.malik@gmail.com>

On Tue, Apr 14, 2026 at 1:03 PM Peter Smith <smithpb2250@gmail.com> wrote:
>
> On Tue, Apr 14, 2026 at 4:30 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
> >
> > Hi hackers,
> >
> > Following earlier work to support EXCEPT for FOR ALL TABLES [1]
> > publications, starting this thread to extend the same capability to
> > schema-level publications (TABLES IN SCHEMA).
>
> Hi Nisha.
>
> +1 for adding this new kind of exclusion clause to CREATE PUBLICATION command.
>
> >
> > Currently, TABLES IN SCHEMA publishes all tables in a schema with no
> > way to exclude a subset. Users who want to skip a few tables must
> > switch to an explicit FOR TABLE list, which loses the convenience of
> > schema-level publishing and requires ongoing maintenance as tables are
> > added.
> >
> > Proposed syntax:
> > ------------------------
> > CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1 EXCEPT (s1.t1, s1.t2);
> > ALTER PUBLICATION pub ADD TABLES IN SCHEMA s1 EXCEPT (s1.t1);
> > ALTER PUBLICATION pub SET TABLES IN SCHEMA s1 EXCEPT (s1.t1);
> >
> > Note: Tables in the EXCEPT clause must be schema-qualified to avoid
> > ambiguity and must belong to the published schema; otherwise, an error
> > is raised.
> >
>
> The proposed syntax is almost, but not quite, what I was anticipating.
> IMO the syntax shouldn't just be similar to the FOR ALL TABLES EXCEPT;
> It can be *identical* to it. e.g., your examples are missing the
> 'TABLE' keyword necessary to achieve the same command flexibility.
> Furthermore, what is the ambiguity referred to? An excluded table is
> clearly associated with the preceding schema. Can't the code infer the
> schema internally even when it is not provided by the user? Of course,
> the user *can* specify a schema-qualified name if they want to, but I
> didn't see why we are forcing that rule upon them.

+1. I also feel specifying only the table name is clear enough. Or are
we referring to implementation complexity here?

> e.g.
>
> -- Syntax can be *identical* to the "EXCEPT (TABLE ...)" clause already pushed.
> -- Both of these below are equivalent.
> CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1 EXCEPT (TABLE t1, t2, t3);
> CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1 EXCEPT (TABLE t1, TABLE
> t2, TABLE t3);
>
> --  Below is an example of multiple schemas and multiple except clauses:
> -- publish all tables of schema s1 except s1.t1 and s1.t2
> -- publish all tables of schema s2
> -- publish all tables of schema s3 except table s3.t2 (how is this
> ambiguous with the excluded s1.t2?)
> CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1 EXCEPT (TABLE t1, t2),
> s2, s3 EXCEPT (TABLE t2);
>
> ======
> Kind Regards,
> Peter Smith.
> Fujitsu Australia.
>
>





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-04-14 09:36  Amit Kapila <amit.kapila16@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: Amit Kapila @ 2026-04-14 09:36 UTC (permalink / raw)
  To: shveta malik <shveta.malik@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; Nisha Moond <nisha.moond412@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Tue, Apr 14, 2026 at 2:05 PM shveta malik <shveta.malik@gmail.com> wrote:
>
> On Tue, Apr 14, 2026 at 1:03 PM Peter Smith <smithpb2250@gmail.com> wrote:
> >
> > On Tue, Apr 14, 2026 at 4:30 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
> > >
> > > Hi hackers,
> > >
> > > Following earlier work to support EXCEPT for FOR ALL TABLES [1]
> > > publications, starting this thread to extend the same capability to
> > > schema-level publications (TABLES IN SCHEMA).
> >
> > Hi Nisha.
> >
> > +1 for adding this new kind of exclusion clause to CREATE PUBLICATION command.
> >
> > >
> > > Currently, TABLES IN SCHEMA publishes all tables in a schema with no
> > > way to exclude a subset. Users who want to skip a few tables must
> > > switch to an explicit FOR TABLE list, which loses the convenience of
> > > schema-level publishing and requires ongoing maintenance as tables are
> > > added.
> > >
> > > Proposed syntax:
> > > ------------------------
> > > CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1 EXCEPT (s1.t1, s1.t2);
> > > ALTER PUBLICATION pub ADD TABLES IN SCHEMA s1 EXCEPT (s1.t1);
> > > ALTER PUBLICATION pub SET TABLES IN SCHEMA s1 EXCEPT (s1.t1);
> > >
> > > Note: Tables in the EXCEPT clause must be schema-qualified to avoid
> > > ambiguity and must belong to the published schema; otherwise, an error
> > > is raised.
> > >
> >
> > The proposed syntax is almost, but not quite, what I was anticipating.
> > IMO the syntax shouldn't just be similar to the FOR ALL TABLES EXCEPT;
> > It can be *identical* to it. e.g., your examples are missing the
> > 'TABLE' keyword necessary to achieve the same command flexibility.
> > Furthermore, what is the ambiguity referred to? An excluded table is
> > clearly associated with the preceding schema. Can't the code infer the
> > schema internally even when it is not provided by the user? Of course,
> > the user *can* specify a schema-qualified name if they want to, but I
> > didn't see why we are forcing that rule upon them.
>
> +1. I also feel specifying only the table name is clear enough. Or are
> we referring to implementation complexity here?
>

I think it will add complexity. Consider an example:
CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1, s2, s3 EXCEPT (t1, t2);

So, which schema's exclusion list will these tables should be
considered for? Say, if table with name t1 is present in all schemas
then shall we exclude from all schemas or just consider it excluded
from the first one (s1)?

-- 
With Regards,
Amit Kapila.





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-04-14 09:45  Nisha Moond <nisha.moond412@gmail.com>
  parent: Peter Smith <smithpb2250@gmail.com>
  2 siblings, 1 reply; 196+ messages in thread

From: Nisha Moond @ 2026-04-14 09:45 UTC (permalink / raw)
  To: Peter Smith <smithpb2250@gmail.com>; +Cc: PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Tue, Apr 14, 2026 at 1:03 PM Peter Smith <smithpb2250@gmail.com> wrote:
>
> On Tue, Apr 14, 2026 at 4:30 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
> >
> > Hi hackers,
> >
> > Following earlier work to support EXCEPT for FOR ALL TABLES [1]
> > publications, starting this thread to extend the same capability to
> > schema-level publications (TABLES IN SCHEMA).
>
> Hi Nisha.
>
> +1 for adding this new kind of exclusion clause to CREATE PUBLICATION command.
>
> >
> > Currently, TABLES IN SCHEMA publishes all tables in a schema with no
> > way to exclude a subset. Users who want to skip a few tables must
> > switch to an explicit FOR TABLE list, which loses the convenience of
> > schema-level publishing and requires ongoing maintenance as tables are
> > added.
> >
> > Proposed syntax:
> > ------------------------
> > CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1 EXCEPT (s1.t1, s1.t2);
> > ALTER PUBLICATION pub ADD TABLES IN SCHEMA s1 EXCEPT (s1.t1);
> > ALTER PUBLICATION pub SET TABLES IN SCHEMA s1 EXCEPT (s1.t1);
> >
> > Note: Tables in the EXCEPT clause must be schema-qualified to avoid
> > ambiguity and must belong to the published schema; otherwise, an error
> > is raised.
> >
>
> The proposed syntax is almost, but not quite, what I was anticipating.
> IMO the syntax shouldn't just be similar to the FOR ALL TABLES EXCEPT;
> It can be *identical* to it. e.g., your examples are missing the
> 'TABLE' keyword necessary to achieve the same command flexibility.
>

I intentionally didn’t use the TABLE keyword inside EXCEPT.
IIUC, for FOR ALL TABLES EXCEPT, there may be a future need to
distinguish object types (e.g., tables vs schemas), which is why
specifying TABLE makes sense there.

However, for TABLES IN SCHEMA, only tables can be specified, so
omitting TABLE keeps the syntax simpler and more intuitive.

Let's hear others’ opinions too on this and I'll adjust if there’s a
preference for including it.

--
Thanks,
Nisha





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-04-14 09:52  shveta malik <shveta.malik@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: shveta malik @ 2026-04-14 09:52 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>; shveta malik <shveta.malik@gmail.com>

On Tue, Apr 14, 2026 at 3:15 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
>
> On Tue, Apr 14, 2026 at 1:03 PM Peter Smith <smithpb2250@gmail.com> wrote:
> >
> > On Tue, Apr 14, 2026 at 4:30 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
> > >
> > > Hi hackers,
> > >
> > > Following earlier work to support EXCEPT for FOR ALL TABLES [1]
> > > publications, starting this thread to extend the same capability to
> > > schema-level publications (TABLES IN SCHEMA).
> >
> > Hi Nisha.
> >
> > +1 for adding this new kind of exclusion clause to CREATE PUBLICATION command.
> >
> > >
> > > Currently, TABLES IN SCHEMA publishes all tables in a schema with no
> > > way to exclude a subset. Users who want to skip a few tables must
> > > switch to an explicit FOR TABLE list, which loses the convenience of
> > > schema-level publishing and requires ongoing maintenance as tables are
> > > added.
> > >
> > > Proposed syntax:
> > > ------------------------
> > > CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1 EXCEPT (s1.t1, s1.t2);
> > > ALTER PUBLICATION pub ADD TABLES IN SCHEMA s1 EXCEPT (s1.t1);
> > > ALTER PUBLICATION pub SET TABLES IN SCHEMA s1 EXCEPT (s1.t1);
> > >
> > > Note: Tables in the EXCEPT clause must be schema-qualified to avoid
> > > ambiguity and must belong to the published schema; otherwise, an error
> > > is raised.
> > >
> >
> > The proposed syntax is almost, but not quite, what I was anticipating.
> > IMO the syntax shouldn't just be similar to the FOR ALL TABLES EXCEPT;
> > It can be *identical* to it. e.g., your examples are missing the
> > 'TABLE' keyword necessary to achieve the same command flexibility.
> >
>
> I intentionally didn’t use the TABLE keyword inside EXCEPT.
> IIUC, for FOR ALL TABLES EXCEPT, there may be a future need to
> distinguish object types (e.g., tables vs schemas), which is why
> specifying TABLE makes sense there.
>
> However, for TABLES IN SCHEMA, only tables can be specified, so
> omitting TABLE keeps the syntax simpler and more intuitive.
>
> Let's hear others’ opinions too on this and I'll adjust if there’s a
> preference for including it.
>

Nisha, please see pt 1 in [1]. If we plan to support that, then we
need TABLE keyword, otherwise we are fine.

[1]: https://www.postgresql.org/message-id/CAJpy0uB%3DJxTYXOB7VmrhVLR%2B1PG0%3DTtHuGekaqibOPpo2UBLiQ%40ma...

thanks
Shveta





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-04-14 11:31  vignesh C <vignesh21@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  3 siblings, 1 reply; 196+ messages in thread

From: vignesh C @ 2026-04-14 11:31 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Tue, 14 Apr 2026 at 12:00, Nisha Moond <nisha.moond412@gmail.com> wrote:
>
> Hi hackers,
>
> Following earlier work to support EXCEPT for FOR ALL TABLES [1]
> publications, starting this thread to extend the same capability to
> schema-level publications (TABLES IN SCHEMA).
>
> Currently, TABLES IN SCHEMA publishes all tables in a schema with no
> way to exclude a subset. Users who want to skip a few tables must
> switch to an explicit FOR TABLE list, which loses the convenience of
> schema-level publishing and requires ongoing maintenance as tables are
> added.
>
> Proposed syntax:
> ------------------------
> CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1 EXCEPT (s1.t1, s1.t2);
> ALTER PUBLICATION pub ADD TABLES IN SCHEMA s1 EXCEPT (s1.t1);
> ALTER PUBLICATION pub SET TABLES IN SCHEMA s1 EXCEPT (s1.t1);
>
> Note: Tables in the EXCEPT clause must be schema-qualified to avoid
> ambiguity and must belong to the published schema; otherwise, an error
> is raised.
>
> Rules and behavior:
> ----------------------------
> 1) TABLES IN SCHEMA can be combined with FOR TABLE, but EXCEPT applies
> only to the schema clause and must appear immediately after it.
>
> Supported:
>   CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1 EXCEPT (s1.t1), TABLE s2.t1;
>   CREATE PUBLICATION pub FOR TABLE s2.t1, TABLES IN SCHEMA s1 EXCEPT (s1.t1);
>   CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1 EXCEPT (s1.t1), s2
> EXCEPT (s2.t1)
>
> Not supported:
>   CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1,  TABLE s2.t1 EXCEPT (s1.t1);
>
> -- This same rule applies to ALTER PUBLICATION ... ADD/SET.
>
> 2) Conflicting definitions
> Specifying the same table both in the EXCEPT clause and explicitly in
> the TABLE clause results in an error, as this creates a conflicting
> definition for the publication.
>
> 3) "ALTER PUBLICATION ... DROP TABLES IN SCHEMA" does not support
> EXCEPT clause. Whereas, dropping a schema also removes any associated
> entries from the EXCEPT list of the publication.
>  -- To only remove/update except list entries, use SET instead.
>
> 4) Consistency with ALL TABLES EXCEPT rules:
>   4a) Excluding a partitioned root excludes all its partitions
>   4b) Individual partitions cannot be excluded directly; exclude the root table.
>   4c) Excluding an inheritance parent (without ONLY) also excludes its children.
>
> The patches are divided into three parts to simplify review:
>   Patch-001: Basic framework to support EXCEPT in CREATE PUBLICATION
> ... TABLES IN SCHEMA
>   Patch-002: Extend support to ALTER PUBLICATION ... ADD TABLES IN SCHEMA
>   Patch-003: Extend support to ALTER PUBLICATION ... SET TABLES IN SCHEMA
>
> The patches are attached, feedback and suggestions are welcome.

+1 for this.
Few comments for the first patch:
1) This should be collected only if except relation was specified, we
can skip it if it is not specified:
+                       /*
+                        * Collect explicit table OIDs now, before we
close the relation
+                        * list, so that except-table validation below
can check for
+                        * contradictions without relying on a catalog
scan that might not
+                        * yet see the just-inserted rows.
+                        */
+                       foreach(lc, rels)
+                       {
+                               PublicationRelInfo *pri =
(PublicationRelInfo *) lfirst(lc);
+
+                               explicitrelids = lappend_oid(explicitrelids,
+
                  RelationGetRelid(pri->relation));
+                       }

2) Tab completion for except table of that particular schema lists
other schema, but currently specifying other schema tables is not
allowed:
+       else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR",
"TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "("))
+               COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables);

Can we list only the tables from the specified schema.

3) Can this check be done at parser itself, it can be done in
preprocess_pubobj_list parser function to detect the error early:
+                               /*
+                                * For TABLES IN SCHEMA publications,
require schema-qualified
+                                * names to avoid ambiguity when
multiple schemas in the
+                                * publication have identically-named tables.
+                                */
+                               foreach(lc, exceptrelations)
+                               {
+                                       PublicationTable *t =
(PublicationTable *) lfirst(lc);
+
+                                       if (t->relation->schemaname == NULL)
+                                               ereport(ERROR,
+
errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+
errmsg("table \"%s\" in EXCEPT clause must be schema-qualified",
+
    t->relation->relname));
+                               }

4) This error message does not seems to be conveying the correct error message:
postgres=# create publication pub1 for tables in schema sch3 except (
sch3.t1 ) ;
CREATE PUBLICATION
postgres=# alter publication pub1 add table sch3.t1 ;
ERROR:  relation "t1" is already member of publication "pub1"

How about an error message like:
ERROR: table "sch3.t1" cannot be added explicitly because it is listed
in the EXCEPT clause of schema "sch3" in publication "pub1"

5) This change is not related to this patch:
@@ -5279,7 +5315,7 @@ foreach my $run (sort keys %pgdump_runs)
                #
                # Either "all_runs" should be set or there should be a
"like" list,
                # even if it is empty.  (This makes the test more
self-documenting.)
-               if (!defined($tests{$test}->{all_runs})
+               if (   !defined($tests{$test}->{all_runs})
                        && !defined($tests{$test}->{like}))
                {
                        die "missing \"like\" in test \"$test\"";

6) There is an indentation issue here:
-                               pub_except_obj_list opt_pub_except_clause
+                               pub_except_obj_list pub_schema_except_obj_list
+                       opt_pub_except_clause opt_pub_schema_except_clause

Regards,
Vignesh





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-04-14 15:16  vignesh C <vignesh21@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  3 siblings, 1 reply; 196+ messages in thread

From: vignesh C @ 2026-04-14 15:16 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Tue, 14 Apr 2026 at 12:00, Nisha Moond <nisha.moond412@gmail.com> wrote:
>
> Hi hackers,
>
> Following earlier work to support EXCEPT for FOR ALL TABLES [1]
> publications, starting this thread to extend the same capability to
> schema-level publications (TABLES IN SCHEMA).
>
> Currently, TABLES IN SCHEMA publishes all tables in a schema with no
> way to exclude a subset. Users who want to skip a few tables must
> switch to an explicit FOR TABLE list, which loses the convenience of
> schema-level publishing and requires ongoing maintenance as tables are
> added.
>
> Proposed syntax:
> ------------------------
> CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1 EXCEPT (s1.t1, s1.t2);
> ALTER PUBLICATION pub ADD TABLES IN SCHEMA s1 EXCEPT (s1.t1);
> ALTER PUBLICATION pub SET TABLES IN SCHEMA s1 EXCEPT (s1.t1);
>
> Note: Tables in the EXCEPT clause must be schema-qualified to avoid
> ambiguity and must belong to the published schema; otherwise, an error
> is raised.
>
> Rules and behavior:
> ----------------------------
> 1) TABLES IN SCHEMA can be combined with FOR TABLE, but EXCEPT applies
> only to the schema clause and must appear immediately after it.
>
> Supported:
>   CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1 EXCEPT (s1.t1), TABLE s2.t1;
>   CREATE PUBLICATION pub FOR TABLE s2.t1, TABLES IN SCHEMA s1 EXCEPT (s1.t1);
>   CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1 EXCEPT (s1.t1), s2
> EXCEPT (s2.t1)
>
> Not supported:
>   CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1,  TABLE s2.t1 EXCEPT (s1.t1);
>
> -- This same rule applies to ALTER PUBLICATION ... ADD/SET.
>
> 2) Conflicting definitions
> Specifying the same table both in the EXCEPT clause and explicitly in
> the TABLE clause results in an error, as this creates a conflicting
> definition for the publication.
>
> 3) "ALTER PUBLICATION ... DROP TABLES IN SCHEMA" does not support
> EXCEPT clause. Whereas, dropping a schema also removes any associated
> entries from the EXCEPT list of the publication.
>  -- To only remove/update except list entries, use SET instead.
>
> 4) Consistency with ALL TABLES EXCEPT rules:
>   4a) Excluding a partitioned root excludes all its partitions
>   4b) Individual partitions cannot be excluded directly; exclude the root table.
>   4c) Excluding an inheritance parent (without ONLY) also excludes its children.
>
> The patches are divided into three parts to simplify review:
>   Patch-001: Basic framework to support EXCEPT in CREATE PUBLICATION
> ... TABLES IN SCHEMA
>   Patch-002: Extend support to ALTER PUBLICATION ... ADD TABLES IN SCHEMA
>   Patch-003: Extend support to ALTER PUBLICATION ... SET TABLES IN SCHEMA
>
> The patches are attached, feedback and suggestions are welcome.

When an EXCEPT table is specified together with TABLES IN SCHEMA sch1,
the EXCEPT entry is correctly created:
postgres=# create publication pub1 for tables in schema sch1 except (sch1.t1);
CREATE PUBLICATION

postgres=# \dRp+ pub1
                                                      Publication pub1
  Owner  | All tables | All sequences | Inserts | Updates | Deletes |
Truncates | Generated columns | Via root | Description
---------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+-------------
 vignesh | f          | f             | t       | t       | t       |
t         | none              | f        |
Tables from schemas:
    "sch1"
Except tables:
    "sch1.t1"
However, after dropping the schema from the publication, the
previously recorded EXCEPT table entry is still retained:
postgres=# alter publication pub1 drop TABLES IN SCHEMA sch1 ;
ALTER PUBLICATION
postgres=# \dRp+ pub1
                                                      Publication pub1
  Owner  | All tables | All sequences | Inserts | Updates | Deletes |
Truncates | Generated columns | Via root | Description
---------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+-------------
 vignesh | f          | f             | t       | t       | t       |
t         | none              | f        |
Except tables:
    "sch1.t1"

This seems incorrect, because once sch1 is no longer part of the
publication, retaining "sch1.t1" as an EXCEPT entry no longer has any
semantic meaning and leaves behind stale catalog state.

Regards,
Vignesh





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-04-15 02:05  Peter Smith <smithpb2250@gmail.com>
  parent: Amit Kapila <amit.kapila16@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: Peter Smith @ 2026-04-15 02:05 UTC (permalink / raw)
  To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Nisha Moond <nisha.moond412@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Tue, Apr 14, 2026 at 7:37 PM Amit Kapila <amit.kapila16@gmail.com> wrote:
>
> On Tue, Apr 14, 2026 at 2:05 PM shveta malik <shveta.malik@gmail.com> wrote:
> >
> > On Tue, Apr 14, 2026 at 1:03 PM Peter Smith <smithpb2250@gmail.com> wrote:
> > >
> > > On Tue, Apr 14, 2026 at 4:30 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
> > > >
> > > > Hi hackers,
> > > >
> > > > Following earlier work to support EXCEPT for FOR ALL TABLES [1]
> > > > publications, starting this thread to extend the same capability to
> > > > schema-level publications (TABLES IN SCHEMA).
> > >
> > > Hi Nisha.
> > >
> > > +1 for adding this new kind of exclusion clause to CREATE PUBLICATION command.
> > >
> > > >
> > > > Currently, TABLES IN SCHEMA publishes all tables in a schema with no
> > > > way to exclude a subset. Users who want to skip a few tables must
> > > > switch to an explicit FOR TABLE list, which loses the convenience of
> > > > schema-level publishing and requires ongoing maintenance as tables are
> > > > added.
> > > >
> > > > Proposed syntax:
> > > > ------------------------
> > > > CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1 EXCEPT (s1.t1, s1.t2);
> > > > ALTER PUBLICATION pub ADD TABLES IN SCHEMA s1 EXCEPT (s1.t1);
> > > > ALTER PUBLICATION pub SET TABLES IN SCHEMA s1 EXCEPT (s1.t1);
> > > >
> > > > Note: Tables in the EXCEPT clause must be schema-qualified to avoid
> > > > ambiguity and must belong to the published schema; otherwise, an error
> > > > is raised.
> > > >
> > >
> > > The proposed syntax is almost, but not quite, what I was anticipating.
> > > IMO the syntax shouldn't just be similar to the FOR ALL TABLES EXCEPT;
> > > It can be *identical* to it. e.g., your examples are missing the
> > > 'TABLE' keyword necessary to achieve the same command flexibility.
> > > Furthermore, what is the ambiguity referred to? An excluded table is
> > > clearly associated with the preceding schema. Can't the code infer the
> > > schema internally even when it is not provided by the user? Of course,
> > > the user *can* specify a schema-qualified name if they want to, but I
> > > didn't see why we are forcing that rule upon them.
> >
> > +1. I also feel specifying only the table name is clear enough. Or are
> > we referring to implementation complexity here?
> >
>
> I think it will add complexity. Consider an example:
> CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1, s2, s3 EXCEPT (t1, t2);
>
> So, which schema's exclusion list will these tables should be
> considered for? Say, if table with name t1 is present in all schemas
> then shall we exclude from all schemas or just consider it excluded
> from the first one (s1)?
>

The exact pattern is already in common usage for row-filters and
column-lists, yet nobody is confused.

-- all these tables have the same column names
-- (analogous to multiple schemas having same table names)
CREATE TABLE t1(c1 int, c2 int);
CREATE TABLE t2(c1 int, c2 int);
CREATE TABLE t3(c1 int, c2 int);

-- all tables have a column c1
-- but this c1 means t3.c1 because the column-list is only for the adjacent t3.
CREATE PUBLICATION pub1 FOR TABLE t1, t2, t3 (c1);

-- all tables have a column c2
-- but this c2 means t3.c2 because the row-filter is only for the adjacent t3.
CREATE PUBLICATION pub2 FOR TABLE t1, t2, t3 WHERE (c2 > 99);

\dRp+
                                                       Publication pub1
  Owner   | All tables | All sequences | Inserts | Updates | Deletes |
Truncates | Generated columns | Via root | Description
----------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+-------------
 postgres | f          | f             | t       | t       | t       |
t         | none              | f        |
Tables:
    "public.t1"
    "public.t2"
    "public.t3" (c1)

                                                       Publication pub2
  Owner   | All tables | All sequences | Inserts | Updates | Deletes |
Truncates | Generated columns | Via root | Description
----------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+-------------
 postgres | f          | f             | t       | t       | t       |
t         | none              | f        |
Tables:
    "public.t1"
    "public.t2"
    "public.t3" WHERE (c2 > 99)

======
Kind Regards,
Peter Smith.
Fujitsu Australia





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-04-15 05:48  vignesh C <vignesh21@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  3 siblings, 1 reply; 196+ messages in thread

From: vignesh C @ 2026-04-15 05:48 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Tue, 14 Apr 2026 at 12:00, Nisha Moond <nisha.moond412@gmail.com> wrote:
>
> Hi hackers,
>
> Following earlier work to support EXCEPT for FOR ALL TABLES [1]
> publications, starting this thread to extend the same capability to
> schema-level publications (TABLES IN SCHEMA).
>
> Currently, TABLES IN SCHEMA publishes all tables in a schema with no
> way to exclude a subset. Users who want to skip a few tables must
> switch to an explicit FOR TABLE list, which loses the convenience of
> schema-level publishing and requires ongoing maintenance as tables are
> added.
>
> Proposed syntax:
> ------------------------
> CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1 EXCEPT (s1.t1, s1.t2);
> ALTER PUBLICATION pub ADD TABLES IN SCHEMA s1 EXCEPT (s1.t1);
> ALTER PUBLICATION pub SET TABLES IN SCHEMA s1 EXCEPT (s1.t1);
>
> Note: Tables in the EXCEPT clause must be schema-qualified to avoid
> ambiguity and must belong to the published schema; otherwise, an error
> is raised.
>
> Rules and behavior:
> ----------------------------
> 1) TABLES IN SCHEMA can be combined with FOR TABLE, but EXCEPT applies
> only to the schema clause and must appear immediately after it.
>
> Supported:
>   CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1 EXCEPT (s1.t1), TABLE s2.t1;
>   CREATE PUBLICATION pub FOR TABLE s2.t1, TABLES IN SCHEMA s1 EXCEPT (s1.t1);
>   CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1 EXCEPT (s1.t1), s2
> EXCEPT (s2.t1)
>
> Not supported:
>   CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1,  TABLE s2.t1 EXCEPT (s1.t1);
>
> -- This same rule applies to ALTER PUBLICATION ... ADD/SET.
>
> 2) Conflicting definitions
> Specifying the same table both in the EXCEPT clause and explicitly in
> the TABLE clause results in an error, as this creates a conflicting
> definition for the publication.
>
> 3) "ALTER PUBLICATION ... DROP TABLES IN SCHEMA" does not support
> EXCEPT clause. Whereas, dropping a schema also removes any associated
> entries from the EXCEPT list of the publication.
>  -- To only remove/update except list entries, use SET instead.
>
> 4) Consistency with ALL TABLES EXCEPT rules:
>   4a) Excluding a partitioned root excludes all its partitions
>   4b) Individual partitions cannot be excluded directly; exclude the root table.
>   4c) Excluding an inheritance parent (without ONLY) also excludes its children.
>
> The patches are divided into three parts to simplify review:
>   Patch-001: Basic framework to support EXCEPT in CREATE PUBLICATION
> ... TABLES IN SCHEMA
>   Patch-002: Extend support to ALTER PUBLICATION ... ADD TABLES IN SCHEMA
>   Patch-003: Extend support to ALTER PUBLICATION ... SET TABLES IN SCHEMA
>
> The patches are attached, feedback and suggestions are welcome.

Few comments for the second patch:
1) This patch adds support only for:
  ALTER PUBLICATION pub ADD TABLES IN SCHEMA s EXCEPT (s.t1, s.t2);

But documentation mentions for both add and set:
@@ -31,7 +31,7 @@ ALTER PUBLICATION <replaceable
class="parameter">name</replaceable> RENAME TO <r
 <phrase>where <replaceable
class="parameter">publication_object</replaceable> is one of:</phrase>

     TABLE <replaceable
class="parameter">table_and_columns</replaceable> [, ... ]
-    TABLES IN SCHEMA { <replaceable
class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ...
]
+    TABLES IN SCHEMA { <replaceable
class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [
EXCEPT ( <replaceable
class="parameter">except_table_object</replaceable> [, ... ] ) ] [,
... ]

2) Tab completion missing for:
alter publication pub1 add TABLES IN SCHEMA sch1

3) Currently Set tables in schema sch1 also works partially with the
second patch without adding the except tables:
postgres=# alter publication pub1 set tables in schema sch1 except (sch1.t1);
ALTER PUBLICATION
postgres=# \dRp+ pub1
                                                      Publication pub1
  Owner  | All tables | All sequences | Inserts | Updates | Deletes |
Truncates | Generated columns | Via root | Description
---------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+-------------
 vignesh | f          | f             | t       | t       | t       |
t         | none              | f        |
Tables from schemas:
    "sch1"

Should there be a check here to throw an error:
+static void
+AlterPublicationExceptTables(AlterPublicationStmt *stmt,
+                                                        HeapTuple
tup, List *exceptrelations,
+                                                        List *schemaidlist)
+{
+       Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup);
+       Oid                     pubid = pubform->oid;
+
+       /*
+        * Nothing to do if no EXCEPT entries.
+        */
+       if (!exceptrelations)
+               return;
+

4) Can this check be done at parser itself, it can be done in
preprocess_pubobj_list parser function to detect the error early:
+               foreach(lc, exceptrelations)
+               {
+                       PublicationTable *t = (PublicationTable *) lfirst(lc);
+
+                       if (t->relation->schemaname == NULL)
+                               ereport(ERROR,
+
errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+                                               errmsg("table \"%s\"
in EXCEPT clause must be schema-qualified",
+
t->relation->relname));
+               }

Regards,
Vignesh





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-04-15 08:52  Nisha Moond <nisha.moond412@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: Nisha Moond @ 2026-04-15 08:52 UTC (permalink / raw)
  To: shveta malik <shveta.malik@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Tue, Apr 14, 2026 at 3:22 PM shveta malik <shveta.malik@gmail.com> wrote:
>
> On Tue, Apr 14, 2026 at 3:15 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
> >
> > On Tue, Apr 14, 2026 at 1:03 PM Peter Smith <smithpb2250@gmail.com> wrote:
> > >
> > > On Tue, Apr 14, 2026 at 4:30 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
> > > >
> > > > Hi hackers,
> > > >
> > > > Following earlier work to support EXCEPT for FOR ALL TABLES [1]
> > > > publications, starting this thread to extend the same capability to
> > > > schema-level publications (TABLES IN SCHEMA).
> > >
> > > Hi Nisha.
> > >
> > > +1 for adding this new kind of exclusion clause to CREATE PUBLICATION command.
> > >
> > > >
> > > > Currently, TABLES IN SCHEMA publishes all tables in a schema with no
> > > > way to exclude a subset. Users who want to skip a few tables must
> > > > switch to an explicit FOR TABLE list, which loses the convenience of
> > > > schema-level publishing and requires ongoing maintenance as tables are
> > > > added.
> > > >
> > > > Proposed syntax:
> > > > ------------------------
> > > > CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1 EXCEPT (s1.t1, s1.t2);
> > > > ALTER PUBLICATION pub ADD TABLES IN SCHEMA s1 EXCEPT (s1.t1);
> > > > ALTER PUBLICATION pub SET TABLES IN SCHEMA s1 EXCEPT (s1.t1);
> > > >
> > > > Note: Tables in the EXCEPT clause must be schema-qualified to avoid
> > > > ambiguity and must belong to the published schema; otherwise, an error
> > > > is raised.
> > > >
> > >
> > > The proposed syntax is almost, but not quite, what I was anticipating.
> > > IMO the syntax shouldn't just be similar to the FOR ALL TABLES EXCEPT;
> > > It can be *identical* to it. e.g., your examples are missing the
> > > 'TABLE' keyword necessary to achieve the same command flexibility.
> > >
> >
> > I intentionally didn’t use the TABLE keyword inside EXCEPT.
> > IIUC, for FOR ALL TABLES EXCEPT, there may be a future need to
> > distinguish object types (e.g., tables vs schemas), which is why
> > specifying TABLE makes sense there.
> >
> > However, for TABLES IN SCHEMA, only tables can be specified, so
> > omitting TABLE keeps the syntax simpler and more intuitive.
> >
> > Let's hear others’ opinions too on this and I'll adjust if there’s a
> > preference for including it.
> >
>
> Nisha, please see pt 1 in [1]. If we plan to support that, then we
> need TABLE keyword, otherwise we are fine.
>
> [1]: https://www.postgresql.org/message-id/CAJpy0uB%3DJxTYXOB7VmrhVLR%2B1PG0%3DTtHuGekaqibOPpo2UBLiQ%40ma...
>

Thank you Shveta for pointing to the discussion.
So, if we were to extend CREATE PUBLICATION to support something like:
 "CREATE PUBLICATION pub FOR TABLES, SEQUENCES IN SCHEMA sch1 EXCEPT
(TABLE t1,  SEQUENCE s1);"
then, introducing TABLE inside EXCEPT could make sense, but at this
stage we’re not sure how the syntax for supporting SEQUENCES IN SCHEMA
will evolve. The overall grammar may require broader changes rather
than a simple extension. So, we can always introduce keywords like
TABLE or SEQUENCE later, if and when they are actually needed. Just my
thoughts.

--
Thanks,
Nisha





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-04-15 08:52  Nisha Moond <nisha.moond412@gmail.com>
  parent: vignesh C <vignesh21@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: Nisha Moond @ 2026-04-15 08:52 UTC (permalink / raw)
  To: vignesh C <vignesh21@gmail.com>; +Cc: PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Tue, Apr 14, 2026 at 8:46 PM vignesh C <vignesh21@gmail.com> wrote:
>
> When an EXCEPT table is specified together with TABLES IN SCHEMA sch1,
> the EXCEPT entry is correctly created:
> postgres=# create publication pub1 for tables in schema sch1 except (sch1.t1);
> CREATE PUBLICATION
>
> postgres=# \dRp+ pub1
>                                                       Publication pub1
>   Owner  | All tables | All sequences | Inserts | Updates | Deletes |
> Truncates | Generated columns | Via root | Description
> ---------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+-------------
>  vignesh | f          | f             | t       | t       | t       |
> t         | none              | f        |
> Tables from schemas:
>     "sch1"
> Except tables:
>     "sch1.t1"
> However, after dropping the schema from the publication, the
> previously recorded EXCEPT table entry is still retained:
> postgres=# alter publication pub1 drop TABLES IN SCHEMA sch1 ;
> ALTER PUBLICATION
> postgres=# \dRp+ pub1
>                                                       Publication pub1
>   Owner  | All tables | All sequences | Inserts | Updates | Deletes |
> Truncates | Generated columns | Via root | Description
> ---------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+-------------
>  vignesh | f          | f             | t       | t       | t       |
> t         | none              | f        |
> Except tables:
>     "sch1.t1"
>
> This seems incorrect, because once sch1 is no longer part of the
> publication, retaining "sch1.t1" as an EXCEPT entry no longer has any
> semantic meaning and leaves behind stale catalog state.
>

This is handled in v1-003 (last) patch along with other ALTER
PUBLICATION related modifications.

--
Thanks,
Nisha





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-04-15 10:15  shveta malik <shveta.malik@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: shveta malik @ 2026-04-15 10:15 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>; shveta malik <shveta.malik@gmail.com>

On Wed, Apr 15, 2026 at 2:22 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
>
> On Tue, Apr 14, 2026 at 3:22 PM shveta malik <shveta.malik@gmail.com> wrote:
> >
> > On Tue, Apr 14, 2026 at 3:15 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
> > >
> > > On Tue, Apr 14, 2026 at 1:03 PM Peter Smith <smithpb2250@gmail.com> wrote:
> > > >
> > > > On Tue, Apr 14, 2026 at 4:30 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
> > > > >
> > > > > Hi hackers,
> > > > >
> > > > > Following earlier work to support EXCEPT for FOR ALL TABLES [1]
> > > > > publications, starting this thread to extend the same capability to
> > > > > schema-level publications (TABLES IN SCHEMA).
> > > >
> > > > Hi Nisha.
> > > >
> > > > +1 for adding this new kind of exclusion clause to CREATE PUBLICATION command.
> > > >
> > > > >
> > > > > Currently, TABLES IN SCHEMA publishes all tables in a schema with no
> > > > > way to exclude a subset. Users who want to skip a few tables must
> > > > > switch to an explicit FOR TABLE list, which loses the convenience of
> > > > > schema-level publishing and requires ongoing maintenance as tables are
> > > > > added.
> > > > >
> > > > > Proposed syntax:
> > > > > ------------------------
> > > > > CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1 EXCEPT (s1.t1, s1.t2);
> > > > > ALTER PUBLICATION pub ADD TABLES IN SCHEMA s1 EXCEPT (s1.t1);
> > > > > ALTER PUBLICATION pub SET TABLES IN SCHEMA s1 EXCEPT (s1.t1);
> > > > >
> > > > > Note: Tables in the EXCEPT clause must be schema-qualified to avoid
> > > > > ambiguity and must belong to the published schema; otherwise, an error
> > > > > is raised.
> > > > >
> > > >
> > > > The proposed syntax is almost, but not quite, what I was anticipating.
> > > > IMO the syntax shouldn't just be similar to the FOR ALL TABLES EXCEPT;
> > > > It can be *identical* to it. e.g., your examples are missing the
> > > > 'TABLE' keyword necessary to achieve the same command flexibility.
> > > >
> > >
> > > I intentionally didn’t use the TABLE keyword inside EXCEPT.
> > > IIUC, for FOR ALL TABLES EXCEPT, there may be a future need to
> > > distinguish object types (e.g., tables vs schemas), which is why
> > > specifying TABLE makes sense there.
> > >
> > > However, for TABLES IN SCHEMA, only tables can be specified, so
> > > omitting TABLE keeps the syntax simpler and more intuitive.
> > >
> > > Let's hear others’ opinions too on this and I'll adjust if there’s a
> > > preference for including it.
> > >
> >
> > Nisha, please see pt 1 in [1]. If we plan to support that, then we
> > need TABLE keyword, otherwise we are fine.
> >
> > [1]: https://www.postgresql.org/message-id/CAJpy0uB%3DJxTYXOB7VmrhVLR%2B1PG0%3DTtHuGekaqibOPpo2UBLiQ%40ma...
> >
>
> Thank you Shveta for pointing to the discussion.
> So, if we were to extend CREATE PUBLICATION to support something like:
>  "CREATE PUBLICATION pub FOR TABLES, SEQUENCES IN SCHEMA sch1 EXCEPT
> (TABLE t1,  SEQUENCE s1);"
> then, introducing TABLE inside EXCEPT could make sense, but at this
> stage we’re not sure how the syntax for supporting SEQUENCES IN SCHEMA
> will evolve. The overall grammar may require broader changes rather
> than a simple extension. So, we can always introduce keywords like
> TABLE or SEQUENCE later, if and when they are actually needed. Just my
> thoughts.
>

It works for me Nisha. I also agree that the 'TABLE' keyword seems
redundant in the case you proposed:
CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1 EXCEPT (s1.t1, s1.t2);

But I am just worried this might confuse users, as one command
requires specifying the TABLE with EXCEPT, while another requires
omitting it. But we can first focus on implementation and come back to
it later when more people join and share their thoughts.

thanks
Shveta





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-04-15 13:08  vignesh C <vignesh21@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  0 siblings, 0 replies; 196+ messages in thread

From: vignesh C @ 2026-04-15 13:08 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Wed, 15 Apr 2026 at 14:22, Nisha Moond <nisha.moond412@gmail.com> wrote:
>
> On Tue, Apr 14, 2026 at 8:46 PM vignesh C <vignesh21@gmail.com> wrote:
> >
> > When an EXCEPT table is specified together with TABLES IN SCHEMA sch1,
> > the EXCEPT entry is correctly created:
> > postgres=# create publication pub1 for tables in schema sch1 except (sch1.t1);
> > CREATE PUBLICATION
> >
> > postgres=# \dRp+ pub1
> >                                                       Publication pub1
> >   Owner  | All tables | All sequences | Inserts | Updates | Deletes |
> > Truncates | Generated columns | Via root | Description
> > ---------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+-------------
> >  vignesh | f          | f             | t       | t       | t       |
> > t         | none              | f        |
> > Tables from schemas:
> >     "sch1"
> > Except tables:
> >     "sch1.t1"
> > However, after dropping the schema from the publication, the
> > previously recorded EXCEPT table entry is still retained:
> > postgres=# alter publication pub1 drop TABLES IN SCHEMA sch1 ;
> > ALTER PUBLICATION
> > postgres=# \dRp+ pub1
> >                                                       Publication pub1
> >   Owner  | All tables | All sequences | Inserts | Updates | Deletes |
> > Truncates | Generated columns | Via root | Description
> > ---------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+-------------
> >  vignesh | f          | f             | t       | t       | t       |
> > t         | none              | f        |
> > Except tables:
> >     "sch1.t1"
> >
> > This seems incorrect, because once sch1 is no longer part of the
> > publication, retaining "sch1.t1" as an EXCEPT entry no longer has any
> > semantic meaning and leaves behind stale catalog state.
> >
>
> This is handled in v1-003 (last) patch along with other ALTER
> PUBLICATION related modifications.

I was reviewing the patches individually and noticed this. If it is
handled in the 003 ignore that comment.

Regards,
Vignesh





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-04-15 14:07  Nisha Moond <nisha.moond412@gmail.com>
  parent: vignesh C <vignesh21@gmail.com>
  0 siblings, 0 replies; 196+ messages in thread

From: Nisha Moond @ 2026-04-15 14:07 UTC (permalink / raw)
  To: vignesh C <vignesh21@gmail.com>; +Cc: PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Tue, Apr 14, 2026 at 5:01 PM vignesh C <vignesh21@gmail.com> wrote:
>
> +1 for this.
> Few comments for the first patch:

Thank you Vignesh for the review.

> 1) This should be collected only if except relation was specified, we
> can skip it if it is not specified:
> +                       /*
> +                        * Collect explicit table OIDs now, before we
> close the relation
> +                        * list, so that except-table validation below
> can check for
> +                        * contradictions without relying on a catalog
> scan that might not
> +                        * yet see the just-inserted rows.
> +                        */
> +                       foreach(lc, rels)
> +                       {
> +                               PublicationRelInfo *pri =
> (PublicationRelInfo *) lfirst(lc);
> +
> +                               explicitrelids = lappend_oid(explicitrelids,
> +
>                   RelationGetRelid(pri->relation));
> +                       }
>

Fixed

> 2) Tab completion for except table of that particular schema lists
> other schema, but currently specifying other schema tables is not
> allowed:
> +       else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR",
> "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "("))
> +               COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables);
>
> Can we list only the tables from the specified schema.
>

Fixed. Required a new query to fetch schema tables.

> 3) Can this check be done at parser itself, it can be done in
> preprocess_pubobj_list parser function to detect the error early:
> +                               /*
> +                                * For TABLES IN SCHEMA publications,
> require schema-qualified
> +                                * names to avoid ambiguity when
> multiple schemas in the
> +                                * publication have identically-named tables.
> +                                */
> +                               foreach(lc, exceptrelations)
> +                               {
> +                                       PublicationTable *t =
> (PublicationTable *) lfirst(lc);
> +
> +                                       if (t->relation->schemaname == NULL)
> +                                               ereport(ERROR,
> +
> errcode(ERRCODE_INVALID_PARAMETER_VALUE),
> +
> errmsg("table \"%s\" in EXCEPT clause must be schema-qualified",
> +
>     t->relation->relname));
> +                               }
>

Fixed

> 4) This error message does not seems to be conveying the correct error message:
> postgres=# create publication pub1 for tables in schema sch3 except (
> sch3.t1 ) ;
> CREATE PUBLICATION
> postgres=# alter publication pub1 add table sch3.t1 ;
> ERROR:  relation "t1" is already member of publication "pub1"
>
> How about an error message like:
> ERROR: table "sch3.t1" cannot be added explicitly because it is listed
> in the EXCEPT clause of schema "sch3" in publication "pub1"
>

Fixed with a bit short error message -
postgres=# alter publication pub8 add table s1.t1;
ERROR:  table "s1.t1" cannot be added because it is listed in EXCEPT
clause of publication "pub8"

> 5) This change is not related to this patch:
> @@ -5279,7 +5315,7 @@ foreach my $run (sort keys %pgdump_runs)
>                 #
>                 # Either "all_runs" should be set or there should be a
> "like" list,
>                 # even if it is empty.  (This makes the test more
> self-documenting.)
> -               if (!defined($tests{$test}->{all_runs})
> +               if (   !defined($tests{$test}->{all_runs})
>                         && !defined($tests{$test}->{like}))
>                 {
>                         die "missing \"like\" in test \"$test\"";
>

Fixed

> 6) There is an indentation issue here:
> -                               pub_except_obj_list opt_pub_except_clause
> +                               pub_except_obj_list pub_schema_except_obj_list
> +                       opt_pub_except_clause opt_pub_schema_except_clause
>

Fixed

Please find the updated patches (v2) attached.
Patch-001: addressed above comments
Patch-002: addressed Vignesh's comments from [1]
Patch-003: updated the documentation and also added tab-completion for
the SET TABLES IN SCHEMA EXCEPT

[1] https://www.postgresql.org/message-id/CALDaNm3pBWnJJ9ynVj3KeZ%2BNQQXboU-goObvF9fZ0GYzyuJFhQ%40mail.g...

--
Thanks,
Nisha

Attachments: download all (3 files, .tar.gz)

v2-0001-Support-EXCEPT-clause-for-schema-level-publicatio.patch (application/octet-stream, 40.3K) download From 3f406f82ae5d890b95a49fa6c3d87720a6591767 Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Mon, 13 Apr 2026 17:49:44 +0530 Subject: [PATCH v2 1/3] Support EXCEPT clause for schema-level publications Extend table exclusion support in publications to allow specific tables to be excluded from schema-level publications using an EXCEPT clause in CREATE PUBLICATION. Supported syntax: CREATE PUBLICATION <pub> FOR TABLES IN SCHEMA s EXCEPT (s.t1,...); --- doc/src/sgml/logical-replication.sgml | 7 +- doc/src/sgml/ref/create_publication.sgml | 19 ++- src/backend/catalog/pg_publication.c | 107 ++++++++++++--- src/backend/commands/publicationcmds.c | 60 +++++++++ src/backend/parser/gram.y | 55 +++++++- src/backend/replication/pgoutput/pgoutput.c | 34 ++++- src/bin/pg_dump/pg_dump.c | 30 ++++- src/bin/pg_dump/t/002_pg_dump.pl | 36 +++++ src/bin/psql/describe.c | 18 +++ src/bin/psql/tab-complete.in.c | 35 ++++- src/include/nodes/parsenodes.h | 1 + src/test/regress/expected/publication.out | 44 ++++++- src/test/regress/sql/publication.sql | 27 +++- src/test/subscription/t/037_except.pl | 139 +++++++++++++++++++- 14 files changed, 573 insertions(+), 39 deletions(-) diff --git a/doc/src/sgml/logical-replication.sgml b/doc/src/sgml/logical-replication.sgml index 23b268273b9..a9ecf483a57 100644 --- a/doc/src/sgml/logical-replication.sgml +++ b/doc/src/sgml/logical-replication.sgml @@ -117,10 +117,13 @@ or <literal>FOR ALL SEQUENCES</literal>. Unlike tables, sequences can be synchronized at any time. For more information, see <xref linkend="logical-replication-sequences"/>. When a publication is - created with <literal>FOR ALL TABLES</literal>, a table or set of tables can + created with <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal>, a table or set of tables can be explicitly excluded from publication using the <link linkend="sql-createpublication-params-for-except-table"><literal>EXCEPT</literal></link> - clause. + clause. When used with <literal>FOR TABLES IN SCHEMA</literal>, each + excluded table must belong to the schema named in the same + <literal>TABLES IN SCHEMA</literal> clause. </para> <para> diff --git a/doc/src/sgml/ref/create_publication.sgml b/doc/src/sgml/ref/create_publication.sgml index 0ac576d3f10..8715404f0cb 100644 --- a/doc/src/sgml/ref/create_publication.sgml +++ b/doc/src/sgml/ref/create_publication.sgml @@ -28,7 +28,7 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -142,6 +142,8 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <para> Marks the publication as one that replicates changes for all tables in the specified list of schemas, including tables created in the future. + Tables listed in <literal>EXCEPT</literal> for a given schema are + excluded from the publication. </para> <para> @@ -198,7 +200,11 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <listitem> <para> This clause specifies a list of tables to be excluded from the - publication. + publication. It can be used with both <literal>FOR ALL TABLES</literal> + and <literal>FOR TABLES IN SCHEMA</literal>. When used with + <literal>FOR TABLES IN SCHEMA</literal>, the excluded tables must belong + to the schema specified in the same <literal>TABLES IN SCHEMA</literal> + clause. </para> <para> For inherited tables, if <literal>ONLY</literal> is specified before the @@ -515,6 +521,15 @@ CREATE PUBLICATION production_publication FOR TABLE users, departments, TABLES I CREATE PUBLICATION sales_publication FOR TABLES IN SCHEMA marketing, sales; </programlisting></para> + <para> + Create a publication that publishes all changes for all the tables present in + the schema <structname>sales</structname>, except + <structname>sales.internal</structname> and <structname>sales.drafts</structname>: +<programlisting> +CREATE PUBLICATION sales_filtered FOR TABLES IN SCHEMA sales EXCEPT (sales.internal, sales.drafts); +</programlisting> + </para> + <para> Create a publication that publishes all changes for table <structname>users</structname>, but replicates only columns <structname>user_id</structname> and diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index a43d385c605..85c2528873f 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -529,6 +529,7 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, referenced; List *relids = NIL; int i; + HeapTuple existing; bool inval_except_table; rel = table_open(PublicationRelRelationId, RowExclusiveLock); @@ -538,18 +539,33 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, * duplicates, it's here just to provide nicer error message in common * case. The real protection is the unique key on the catalog. */ - if (SearchSysCacheExists2(PUBLICATIONRELMAP, ObjectIdGetDatum(relid), - ObjectIdGetDatum(pubid))) + existing = SearchSysCache2(PUBLICATIONRELMAP, ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + + if (HeapTupleIsValid(existing)) { + Form_pg_publication_rel existing_form = + (Form_pg_publication_rel) GETSTRUCT(existing); + bool is_except = existing_form->prexcept; + + ReleaseSysCache(existing); table_close(rel, RowExclusiveLock); if (if_not_exists) return InvalidObjectAddress; - ereport(ERROR, - (errcode(ERRCODE_DUPLICATE_OBJECT), - errmsg("relation \"%s\" is already member of publication \"%s\"", - RelationGetRelationName(targetrel), pub->name))); + if (is_except) + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("table \"%s.%s\" cannot be added because it is listed in EXCEPT clause of publication \"%s\"", + get_namespace_name(RelationGetNamespace(targetrel)), + RelationGetRelationName(targetrel), + pub->name))); + else + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("relation \"%s\" is already member of publication \"%s\"", + RelationGetRelationName(targetrel), pub->name))); } check_publication_add_relation(pri); @@ -620,19 +636,24 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, /* * Determine whether EXCEPT tables require explicit relcache invalidation. * - * For CREATE PUBLICATION with EXCEPT tables, invalidation is skipped - * here, as CreatePublication() function invalidates all relations as part - * of defining a FOR ALL TABLES publication. + * For CREATE PUBLICATION with EXCEPT tables, invalidation is skipped here + * because the excluded tables were never included in the publication, so + * no subscriber cache entry needs to be cleared. + * + * For ALTER PUBLICATION, invalidation is needed when adding an EXCEPT + * table to either: - a FOR ALL TABLES publication (pub->alltables is + * true), or - a FOR TABLES IN SCHEMA publication (is_schema_publication + * is true). * - * For ALTER PUBLICATION, invalidation is needed only when adding an - * EXCEPT table to a publication already marked as ALL TABLES. For - * publications that were originally empty or defined as ALL SEQUENCES and - * are being converted to ALL TABLES, invalidation is skipped here, as - * AlterPublicationAllFlags() function invalidates all relations while - * marking the publication as ALL TABLES publication. + * The exception: when a publication is being converted to FOR ALL TABLES + * (pub->alltables is still false at this point), + * AlterPublicationAllFlags() will perform a full invalidation, so we skip + * it here. */ - inval_except_table = (alter_stmt != NULL) && pub->alltables && - (alter_stmt->for_all_tables && pri->except); + inval_except_table = (alter_stmt != NULL) && pri->except && + (pub->alltables + ? alter_stmt->for_all_tables + : is_schema_publication(pubid)); if (!pri->except || inval_except_table) { @@ -975,7 +996,8 @@ GetIncludedPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) * Gets list of table oids that were specified in the EXCEPT clause for a * publication. * - * This should only be used FOR ALL TABLES publications. + * This is used for FOR ALL TABLES and FOR TABLES IN SCHEMA publications, + * both of which support EXCEPT TABLE. */ List * GetExcludedPublicationTables(Oid pubid, PublicationPartOpt pub_partopt) @@ -1225,22 +1247,67 @@ GetSchemaPublicationRelations(Oid schemaid, PublicationPartOpt pub_partopt) /* * Gets the list of all relations published by FOR TABLES IN SCHEMA - * publication. + * publication, excluding any tables listed in the EXCEPT clause. */ List * GetAllSchemaPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) { List *result = NIL; List *pubschemalist = GetPublicationSchemas(pubid); + List *exceptlist = NIL; ListCell *cell; + /* get the list of tables excluded via EXCEPT TABLE for this publication */ + if (pubschemalist != NIL) + exceptlist = get_publication_relations(pubid, pub_partopt, true); + foreach(cell, pubschemalist) { Oid schemaid = lfirst_oid(cell); List *schemaRels = NIL; schemaRels = GetSchemaPublicationRelations(schemaid, pub_partopt); - result = list_concat(result, schemaRels); + + if (exceptlist != NIL) + { + /* filter out any tables that appear in the EXCEPT list */ + ListCell *rlc; + + foreach(rlc, schemaRels) + { + Oid relid = lfirst_oid(rlc); + bool excluded = list_member_oid(exceptlist, relid); + + /* + * Also exclude any relation whose partition ancestor is in + * the EXCEPT list. This matters when pub_partopt is + * PUBLICATION_PART_ROOT: the except list holds only the root + * OID, but the schema scan may also return individual + * partition relations that live in the same schema. + */ + if (!excluded && get_rel_relispartition(relid)) + { + List *ancestors = get_partition_ancestors(relid); + ListCell *alc; + + foreach(alc, ancestors) + { + if (list_member_oid(exceptlist, lfirst_oid(alc))) + { + excluded = true; + break; + } + } + list_free(ancestors); + } + + if (!excluded) + result = lappend_oid(result, relid); + } + list_free(schemaRels); + } + else + result = list_concat(result, schemaRels); } return result; diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 440adb356ad..064e35accbb 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -959,6 +959,8 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) } else if (!stmt->for_all_sequences) { + List *explicitrelids = NIL; + /* FOR TABLES IN SCHEMA requires superuser */ if (schemaidlist != NIL && !superuser()) ereport(ERROR, @@ -968,6 +970,7 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) if (relations != NIL) { List *rels; + ListCell *lc; rels = OpenTableList(relations); TransformPubWhereClauses(rels, pstate->p_sourcetext, @@ -977,6 +980,23 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) schemaidlist != NIL, publish_via_partition_root); + /* + * Collect explicit table OIDs now, before we close the relation + * list, so that except-table validation below can check for + * contradictions without relying on a catalog scan that might not + * yet see the just-inserted rows. + */ + if (exceptrelations != NIL) + { + foreach(lc, rels) + { + PublicationRelInfo *pri = (PublicationRelInfo *) lfirst(lc); + + explicitrelids = lappend_oid(explicitrelids, + RelationGetRelid(pri->relation)); + } + } + PublicationAddTables(puboid, rels, true, NULL); CloseTableList(rels); } @@ -989,6 +1009,46 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) */ LockSchemaList(schemaidlist); PublicationAddSchemas(puboid, schemaidlist, true, NULL); + + if (exceptrelations != NIL) + { + List *rels; + ListCell *lc; + + rels = OpenTableList(exceptrelations); + + /* + * Validate that each excluded table belongs to one of the + * schemas listed in this publication, and is not also in the + * explicit table list (which would be contradictory). Use the + * in-memory explicitrelids collected above rather than + * re-reading the catalog, which may not yet see the + * just-inserted rows. + */ + foreach(lc, rels) + { + PublicationRelInfo *pri = (PublicationRelInfo *) lfirst(lc); + Oid relid = RelationGetRelid(pri->relation); + Oid relns = RelationGetNamespace(pri->relation); + + if (!list_member_oid(schemaidlist, relns)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s.%s\" in EXCEPT clause does not belong to any schema listed in the publication", + get_namespace_name(relns), + RelationGetRelationName(pri->relation))); + + if (list_member_oid(explicitrelids, relid)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s.%s\" cannot appear in both the table list and the EXCEPT clause", + get_namespace_name(relns), + RelationGetRelationName(pri->relation))); + } + + PublicationAddTables(puboid, rels, true, NULL); + CloseTableList(rels); + } } } diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y index 2d1b19d1f53..7cd4c8c53af 100644 --- a/src/backend/parser/gram.y +++ b/src/backend/parser/gram.y @@ -457,7 +457,8 @@ static Node *makeRecursiveViewSelect(char *relname, List *aliases, Node *query); TriggerTransitions TriggerReferencing vacuum_relation_list opt_vacuum_relation_list drop_option_list pub_obj_list pub_all_obj_type_list - pub_except_obj_list opt_pub_except_clause + pub_except_obj_list pub_schema_except_obj_list + opt_pub_except_clause opt_pub_schema_except_clause %type <retclause> returning_clause %type <node> returning_option @@ -11272,7 +11273,7 @@ AlterOwnerStmt: ALTER AGGREGATE aggregate_with_argtypes OWNER TO RoleSpec * pub_obj is one of: * * TABLE table [, ...] - * TABLES IN SCHEMA schema [, ...] + * TABLES IN SCHEMA schema [EXCEPT ( table [, ...] )] [, ...] * *****************************************************************************/ @@ -11332,23 +11333,26 @@ PublicationObjSpec: $$->pubtable->columns = $3; $$->pubtable->whereClause = $4; } - | TABLES IN_P SCHEMA ColId + | TABLES IN_P SCHEMA ColId opt_pub_schema_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_SCHEMA; $$->name = $4; + $$->except_tables = $5; $$->location = @4; } - | TABLES IN_P SCHEMA CURRENT_SCHEMA + | TABLES IN_P SCHEMA CURRENT_SCHEMA opt_pub_schema_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_CUR_SCHEMA; + $$->except_tables = $5; $$->location = @4; } - | ColId opt_column_list OptWhereClause + | ColId opt_column_list OptWhereClause opt_pub_schema_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $4; /* * If either a row filter or column list is specified, create * a PublicationTable object. @@ -11392,10 +11396,11 @@ PublicationObjSpec: $$->pubtable->columns = $2; $$->pubtable->whereClause = $3; } - | CURRENT_SCHEMA + | CURRENT_SCHEMA opt_pub_schema_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $2; $$->location = @1; } ; @@ -11411,6 +11416,11 @@ opt_pub_except_clause: | /*EMPTY*/ { $$ = NIL; } ; +opt_pub_schema_except_clause: + EXCEPT '(' pub_schema_except_obj_list ')' { $$ = $3; } + | /*EMPTY*/ { $$ = NIL; } + ; + PublicationAllObjSpec: ALL TABLES opt_pub_except_clause { @@ -11451,6 +11461,13 @@ pub_except_obj_list: PublicationExceptObjSpec { $$ = lappend($1, $4); } ; +/* Like pub_except_obj_list but without opt_table; used for TABLES IN SCHEMA EXCEPT. */ +pub_schema_except_obj_list: PublicationExceptObjSpec + { $$ = list_make1($1); } + | pub_schema_except_obj_list ',' PublicationExceptObjSpec + { $$ = lappend($1, $3); } + ; + /***************************************************************************** * * ALTER PUBLICATION name SET ( options ) @@ -20784,11 +20801,14 @@ preprocess_pub_all_objtype_list(List *all_objects_list, List **pubobjects, /* * Process pubobjspec_list to check for errors in any of the objects and * convert PUBLICATIONOBJ_CONTINUATION into appropriate PublicationObjSpecType. + * Also flattens except_tables from TABLES IN SCHEMA nodes into the list so + * that ObjectsInPublicationToOids() sees them as top-level EXCEPT_TABLE entries. */ static void preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) { ListCell *cell; + ListCell *lc; PublicationObjSpec *pubobj; PublicationObjSpecType prevobjtype = PUBLICATIONOBJ_CONTINUATION; @@ -20812,6 +20832,13 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLE) { + /* EXCEPT is not valid for table objects */ + if (pubobj->except_tables != NIL) + ereport(ERROR, + errcode(ERRCODE_SYNTAX_ERROR), + errmsg("EXCEPT is not allowed for TABLE publication objects"), + parser_errposition(pubobj->location)); + /* relation name or pubtable must be set for this type of object */ if (!pubobj->name && !pubobj->pubtable) ereport(ERROR, @@ -20860,6 +20887,22 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) errcode(ERRCODE_SYNTAX_ERROR), errmsg("invalid schema name"), parser_errposition(pubobj->location)); + + /* Flatten EXCEPT entries into the top-level list */ + foreach(lc, pubobj->except_tables) + { + PublicationObjSpec *eobj = (PublicationObjSpec *) lfirst(lc); + + if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLES_IN_SCHEMA && + eobj->pubtable->relation->schemaname == NULL) + ereport(ERROR, + errcode(ERRCODE_SYNTAX_ERROR), + errmsg("table \"%s\" in EXCEPT clause must be schema-qualified", + eobj->pubtable->relation->relname), + parser_errposition(eobj->location)); + } + pubobjspec_list = list_concat(pubobjspec_list, pubobj->except_tables); + pubobj->except_tables = NIL; } prevobjtype = pubobj->pubobjtype; diff --git a/src/backend/replication/pgoutput/pgoutput.c b/src/backend/replication/pgoutput/pgoutput.c index 4ecfcbff7ab..942ddb51d3a 100644 --- a/src/backend/replication/pgoutput/pgoutput.c +++ b/src/backend/replication/pgoutput/pgoutput.c @@ -2097,6 +2097,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) * are absorbed while decoding WAL. */ List *schemaPubids = GetSchemaPublications(schemaId); + List *schemaExceptPubids; ListCell *lc; Oid publish_as_relid = relid; int publish_ancestor_level = 0; @@ -2104,6 +2105,25 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) char relkind = get_rel_relkind(relid); List *rel_publications = NIL; + /* + * For the schema EXCEPT check, we must look up the top-most ancestor + * rather than the relation itself. check_publication_add_relation() + * prevents individual partitions from appearing in the EXCEPT clause, + * so only a root (non-partition) table can have prexcept = true. + * Using the partition's own OID would always return NIL and miss the + * exclusion. + */ + if (am_partition) + { + List *pancestore = get_partition_ancestors(relid); + + schemaExceptPubids = + GetRelationExcludedPublications(llast_oid(pancestore)); + list_free(pancestore); + } + else + schemaExceptPubids = GetRelationExcludedPublications(relid); + /* Reload publications if needed before use. */ if (!publications_valid) { @@ -2269,7 +2289,15 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) ancestors, &level); - if (ancestor != InvalidOid) + /* + * The ancestor is only considered published if it is not + * in the EXCEPT clause of this schema publication. + * GetTopMostAncestorInPublication checks schema + * membership but does not account for the EXCEPT list, so + * we must filter that out here. + */ + if (ancestor != InvalidOid && + !list_member_oid(schemaExceptPubids, pub->oid)) { ancestor_published = true; if (pub->pubviaroot) @@ -2281,7 +2309,8 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) } if (list_member_oid(pubids, pub->oid) || - list_member_oid(schemaPubids, pub->oid) || + (list_member_oid(schemaPubids, pub->oid) && + !list_member_oid(schemaExceptPubids, pub->oid)) || ancestor_published) publish = true; } @@ -2360,6 +2389,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) list_free(pubids); list_free(schemaPubids); + list_free(schemaExceptPubids); list_free(rel_publications); entry->replicate_valid = true; diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c index 1ca03d6b278..a1ca6edd80d 100644 --- a/src/bin/pg_dump/pg_dump.c +++ b/src/bin/pg_dump/pg_dump.c @@ -5019,6 +5019,7 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) PublicationInfo *pubinfo = pubsinfo->publication; PQExpBuffer query; char *tag; + bool first_except = true; /* Do nothing if not dumping schema */ if (!dopt->dumpSchema) @@ -5029,7 +5030,34 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) query = createPQExpBuffer(); appendPQExpBuffer(query, "ALTER PUBLICATION %s ", fmtId(pubinfo->dobj.name)); - appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s;\n", fmtId(schemainfo->dobj.name)); + appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s", fmtId(schemainfo->dobj.name)); + + /* + * Append EXCEPT clause for any tables that belong to this schema + * and are excluded from the publication. + */ + for (SimplePtrListCell *cell = pubinfo->except_tables.head; cell; cell = cell->next) + { + TableInfo *tbinfo = (TableInfo *) cell->ptr; + + if (strcmp(tbinfo->dobj.namespace->dobj.name, schemainfo->dobj.name) == 0) + { + if (first_except) + { + appendPQExpBufferStr(query, " EXCEPT ("); + first_except = false; + } + else + appendPQExpBufferStr(query, ", "); + + appendPQExpBuffer(query, "ONLY %s", fmtQualifiedDumpable(tbinfo)); + } + } + + if (!first_except) + appendPQExpBufferStr(query, ")"); + + appendPQExpBufferStr(query, ";\n"); /* * There is no point in creating drop query as the drop is done by schema diff --git a/src/bin/pg_dump/t/002_pg_dump.pl b/src/bin/pg_dump/t/002_pg_dump.pl index 3bc8e51561d..3391058a4c2 100644 --- a/src/bin/pg_dump/t/002_pg_dump.pl +++ b/src/bin/pg_dump/t/002_pg_dump.pl @@ -3242,6 +3242,42 @@ my %tests = ( like => { %full_runs, section_post_data => 1, }, }, + 'CREATE PUBLICATION pub11' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub11 FOR TABLES IN SCHEMA dump_test EXCEPT (dump_test.test_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub11 WITH (publish = 'insert, update, delete, truncate');\E + /xm, + like => { %full_runs, section_post_data => 1, }, + }, + + 'ALTER PUBLICATION pub11 ADD TABLES IN SCHEMA dump_test EXCEPT (dump_test.test_table)' + => { + regexp => qr/^ + \QALTER PUBLICATION pub11 ADD TABLES IN SCHEMA dump_test EXCEPT (ONLY dump_test.test_table);\E + /xm, + like => { %full_runs, section_post_data => 1, }, + }, + + 'CREATE PUBLICATION pub12' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub12 FOR TABLES IN SCHEMA dump_test EXCEPT (dump_test.test_table, dump_test.test_second_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub12 WITH (publish = 'insert, update, delete, truncate');\E + /xm, + like => { %full_runs, section_post_data => 1, }, + }, + + 'ALTER PUBLICATION pub12 ADD TABLES IN SCHEMA dump_test EXCEPT (dump_test.test_table, dump_test.test_second_table)' + => { + regexp => qr/^ + \QALTER PUBLICATION pub12 ADD TABLES IN SCHEMA dump_test EXCEPT (ONLY dump_test.test_table, ONLY dump_test.test_second_table);\E + /xm, + like => { %full_runs, section_post_data => 1, }, + }, + 'CREATE SUBSCRIPTION sub1' => { create_order => 50, create_sql => 'CREATE SUBSCRIPTION sub1 diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c index dd1179ef927..b751206e5a4 100644 --- a/src/bin/psql/describe.c +++ b/src/bin/psql/describe.c @@ -7038,6 +7038,24 @@ describePublications(const char *pattern) if (!addFooterToPublicationDesc(&buf, _("Tables from schemas:"), true, &cont)) goto error_return; + + if (pset.sversion >= 190000) + { + /* + * Get tables in the EXCEPT clause for this schema + * publication. + */ + printfPQExpBuffer(&buf, + "SELECT concat(c.relnamespace::regnamespace, '.', c.relname)\n" + "FROM pg_catalog.pg_class c\n" + " JOIN pg_catalog.pg_publication_rel pr ON c.oid = pr.prrelid\n" + "WHERE pr.prpubid = '%s'\n" + " AND pr.prexcept\n" + "ORDER BY 1", pubid); + if (!addFooterToPublicationDesc(&buf, _("Except tables:"), + true, &cont)) + goto error_return; + } } } else diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index 9990f818942..12271f7e2b1 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -1064,6 +1064,15 @@ static const SchemaQuery Query_for_trigger_of_table = { "SELECT nspname FROM pg_catalog.pg_namespace "\ " WHERE nspname LIKE '%s'" +#define Query_for_list_of_tables_in_schema \ +"SELECT n.nspname || '.' || c.relname "\ +" FROM pg_catalog.pg_class c "\ +" JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "\ +" WHERE c.relkind IN (" CppAsString2(RELKIND_RELATION) ", " \ + CppAsString2(RELKIND_PARTITIONED_TABLE) ") "\ +" AND (n.nspname || '.' || c.relname) LIKE '%s' "\ +" AND n.nspname = '%s'" + /* Use COMPLETE_WITH_QUERY_VERBATIM with these queries for GUC names: */ #define Query_for_list_of_alter_system_set_vars \ "SELECT pg_catalog.lower(name) FROM pg_catalog.pg_settings "\ @@ -3784,8 +3793,30 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); - else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && (!ends_with(prev_wd, ','))) - COMPLETE_WITH("WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT (", "WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + { + if (strchr(prev3_wd, ',') == NULL) + { + set_completion_reference(prev3_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + } + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", MatchAnyN) && ends_with(prev_wd, ',')) + { + char *schema_word = previous_words[previous_words_count - 8]; + + if (strchr(schema_word, ',') == NULL) + { + set_completion_reference(schema_word); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + } + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* Complete "CREATE PUBLICATION <name> [...] WITH" */ else if (Matches("CREATE", "PUBLICATION", MatchAnyN, "WITH", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h index 91377a6cde3..a9177de0d43 100644 --- a/src/include/nodes/parsenodes.h +++ b/src/include/nodes/parsenodes.h @@ -4493,6 +4493,7 @@ typedef struct PublicationObjSpec PublicationObjSpecType pubobjtype; /* type of this publication object */ char *name; PublicationTable *pubtable; + List *except_tables; /* tables to exclude (for TABLES IN SCHEMA) */ ParseLoc location; /* token location, or -1 if unknown */ } PublicationObjSpec; diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index d028e9be866..50b3a819d14 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -461,7 +461,49 @@ HINT: Change the publication's EXCEPT clause using ALTER PUBLICATION ... SET AL RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + Publication testpub_schema_except1 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- Exclude multiple tables from a schema publication +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (pub_test.testpub_nopk, pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except2 + Publication testpub_schema_except2 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_nopk" + "pub_test.testpub_tbl_s1" + +-- fail: EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2 EXCEPT (pub_test.testpub_nopk); +ERROR: EXCEPT is not allowed for TABLE publication objects +LINE 2: FOR TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2 EXCEPT... + ^ +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2; CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; -- FOR ALL SEQUENCES diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 642e32fa098..3f46e8c5e03 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -218,7 +218,32 @@ RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); + +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + +-- Exclude multiple tables from a schema publication +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (pub_test.testpub_nopk, pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except2 + +-- fail: EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2 EXCEPT (pub_test.testpub_nopk); + +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2; + CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 8c58d282eee..0801d3a77c7 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -24,14 +24,16 @@ my $result; sub test_except_root_partition { - my ($pubviaroot) = @_; + my ($pubviaroot, $pubsql) = @_; + $pubsql //= + "CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1) WITH (publish_via_partition_root = $pubviaroot)"; # If the root partitioned table is in the EXCEPT clause, all its # partitions are excluded from publication, regardless of the # publish_via_partition_root setting. $node_publisher->safe_psql( 'postgres', qq( - CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1) WITH (publish_via_partition_root = $pubviaroot); + $pubsql; INSERT INTO root1 VALUES (1), (101); )); $node_subscriber->safe_psql('postgres', @@ -223,6 +225,138 @@ $node_subscriber->safe_psql( test_except_root_partition('false'); test_except_root_partition('true'); +# Same validation using TABLES IN SCHEMA instead of FOR ALL TABLES. +my $schema_pub = + "CREATE PUBLICATION tap_pub_part FOR TABLES IN SCHEMA public EXCEPT (public.root1)"; +test_except_root_partition('false', + "$schema_pub WITH (publish_via_partition_root = false)"); +test_except_root_partition('true', + "$schema_pub WITH (publish_via_partition_root = true)"); + +# ============================================ +# EXCEPT test cases for TABLES IN SCHEMA +# ============================================ + +# Create a dedicated schema with two tables: one to be published and one to be +# excluded. Also create inherited tables to verify ONLY semantics. +$node_publisher->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_pub AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.tab_exc AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.par (a int); + CREATE TABLE sch1.chi (b int) INHERITS (sch1.par); +)); + +$node_subscriber->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_pub (a int); + CREATE TABLE sch1.tab_exc (a int); + CREATE TABLE sch1.par (a int); + CREATE TABLE sch1.chi (b int) INHERITS (sch1.par); +)); + +# Basic test: initial sync respects EXCEPT. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (sch1.tab_exc)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_pub"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: initial sync copies included table'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_exc"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: initial sync skips excluded table'); + +# DML: only the included table should be replicated. +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_pub VALUES (6); + INSERT INTO sch1.tab_exc VALUES (6); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_pub"); +is($result, qq(6), + 'TABLES IN SCHEMA EXCEPT: DML on included table is replicated'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_exc"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: DML on excluded table is not replicated'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Inherited tables: excluding the parent (without ONLY) also excludes the child. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (sch1.par)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.chi VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.chi"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: excluding parent (without ONLY) also excludes child' +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Truncate chi on the publisher so the next test starts with a clean slate. +# (The previous test inserted rows into chi that would otherwise be copied by +# the initial table sync of the next subscription.) +$node_publisher->safe_psql('postgres', 'TRUNCATE sch1.chi'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE sch1.chi'); +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (ONLY sch1.par)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.chi VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.chi"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: ONLY parent in EXCEPT does not exclude child' +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); +$node_publisher->safe_psql('postgres', + 'TRUNCATE sch1.par, sch1.chi, sch1.tab_exc'); +$node_subscriber->safe_psql('postgres', + 'TRUNCATE sch1.par, sch1.chi, sch1.tab_pub, sch1.tab_exc'); + +# Cleanup schema tables before the multi-publication section. +$node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); +$node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); + # ============================================ # Test when a subscription is subscribing to multiple publications # ============================================ @@ -254,6 +388,7 @@ $node_publisher->safe_psql( DROP PUBLICATION tap_pub2; TRUNCATE tab1; )); +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_subscriber->safe_psql('postgres', qq(TRUNCATE tab1)); # OK when a table is excluded by pub1 EXCEPT clause, but it is included by pub2 -- 2.50.1 (Apple Git-155)
v2-0002-Add-EXCEPT-support-to-ALTER-PUBLICATION-ADD-TABLE.patch (application/octet-stream, 16.7K) download From 3b92c58c977a7f449373f5f2c2e8d95e712af2ae Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Wed, 15 Apr 2026 18:27:36 +0530 Subject: [PATCH v2 2/3] Add EXCEPT support to ALTER PUBLICATION ADD TABLES IN SCHEMA Extend the EXCEPT clause support to allow tables to be excluded when adding a schema to a publication via ALTER PUBLICATION ... ADD: Syntax: ALTER PUBLICATION pub ADD TABLES IN SCHEMA s EXCEPT (s.t1, s.t2); --- doc/src/sgml/ref/alter_publication.sgml | 41 ++++++- src/backend/commands/publicationcmds.c | 125 +++++++++++++++++++++- src/bin/psql/tab-complete.in.c | 26 +++++ src/test/regress/expected/publication.out | 18 +++- src/test/regress/sql/publication.sql | 11 +- src/test/subscription/t/037_except.pl | 28 +++++ 6 files changed, 245 insertions(+), 4 deletions(-) diff --git a/doc/src/sgml/ref/alter_publication.sgml b/doc/src/sgml/ref/alter_publication.sgml index aa32bb169e9..e901163a89b 100644 --- a/doc/src/sgml/ref/alter_publication.sgml +++ b/doc/src/sgml/ref/alter_publication.sgml @@ -31,7 +31,7 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -54,6 +54,10 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <phrase>and <replaceable class="parameter">table_object</replaceable> is:</phrase> [ ONLY ] <replaceable class="parameter">table_name</replaceable> [ * ] + +<phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> + + [ ONLY ] <replaceable class="parameter">table_name</replaceable> [ * ] </synopsis> </refsynopsisdiv> @@ -110,6 +114,17 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <literal>ADD TABLE</literal>. </para> + <para> + The <literal>EXCEPT</literal> clause can be used with + <literal>ADD TABLES IN SCHEMA</literal> to exclude specific tables from a + schema-level publication. Each excluded table must belong to the schema + named in the same <literal>TABLES IN SCHEMA</literal> clause and must be + schema-qualified. <literal>EXCEPT</literal> is not supported with + <literal>DROP TABLES IN SCHEMA</literal>; instead, dropping a schema from + the publication automatically removes all of its associated + <literal>EXCEPT</literal> entries. + </para> + <para> The fourth variant of this command listed in the synopsis can change all of the publication properties specified in @@ -198,6 +213,20 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r </listitem> </varlistentry> + <varlistentry> + <term><literal>EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] )</literal></term> + <listitem> + <para> + Specifies tables to be excluded from a schema-level publication entry. + This clause may be used with <literal>ADD TABLES IN SCHEMA</literal> + and not with <literal>DROP TABLES IN SCHEMA</literal>. Each named + table must belong to the schema specified in the same <literal>TABLES IN SCHEMA</literal> + clause and must be schema-qualified. See <xref linkend="sql-createpublication"/> + for further details on the semantics of <literal>EXCEPT</literal>. + </para> + </listitem> + </varlistentry> + <varlistentry> <term><literal>SET ( <replaceable class="parameter">publication_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] )</literal></term> <listitem> @@ -288,6 +317,16 @@ ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA marketing, sales; </programlisting> </para> + <para> + Add schema <structname>sales</structname> to the publication + <structname>sales_publication</structname>, excluding the + <structname>sales.internal</structname> and + <structname>sales.drafts</structname> tables: +<programlisting> +ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA sales EXCEPT (sales.internal, sales.drafts); +</programlisting> + </para> + <para> Add tables <structname>users</structname>, <structname>departments</structname> and schema diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 064e35accbb..b26706b5d1d 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -70,6 +70,9 @@ static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok); static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); +static void AlterPublicationExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, List *exceptrelations, + List *schemaidlist); static char defGetGeneratedColsOption(DefElem *def); @@ -1536,6 +1539,13 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, } PublicationAddSchemas(pubform->oid, schemaidlist, false, stmt); + + /* + * Increment the command counter so that is_schema_publication() in + * GetExcludedPublicationTables() can see the just-inserted schema + * rows when AlterPublicationExceptTables runs next. + */ + CommandCounterIncrement(); } else if (stmt->action == AP_DropObjects) PublicationDropSchemas(pubform->oid, schemaidlist, false); @@ -1561,6 +1571,112 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, * skip existing ones when doing catalog update. */ PublicationAddSchemas(pubform->oid, schemaidlist, true, stmt); + + /* + * Increment the command counter so that is_schema_publication() in + * GetExcludedPublicationTables() can see the just-inserted schema + * rows when AlterPublicationExceptTables runs next. + */ + CommandCounterIncrement(); + } +} + +/* + * Alter the EXCEPT list of a publication. + * + * Adds, removes, or replaces except-table entries in pg_publication_rel + * (rows with prexcept = true). These entries suppress publication of the + * named tables that would otherwise be covered by a FOR TABLES IN SCHEMA + * or FOR ALL TABLES clause. + */ +static void +AlterPublicationExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, List *exceptrelations, + List *schemaidlist) +{ + Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); + Oid pubid = pubform->oid; + + /* + * Nothing to do if no EXCEPT entries. + */ + if (!exceptrelations) + return; + + /* + * This function handles EXCEPT entries for schema-level publications + * only. For FOR ALL TABLES publications, EXCEPT entries are already + * processed by AlterPublicationTables(). + */ + if (schemaidlist == NIL && !is_schema_publication(pubid)) + return; + + /* + * EXCEPT is not meaningful with DROP: dropping a schema from a + * publication already removes all its except entries via cascade, and + * there is no sensible interpretation of "drop only the except entry but + * keep the schema". + */ + if (stmt->action == AP_DropObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); + + /* + * EXCEPT with SET is not supported: SET replaces the schema list but does + * not have a well-defined semantics for merging or replacing existing + * except entries. Users should DROP and re-ADD the schema with the + * desired EXCEPT list instead. + */ + if (stmt->action == AP_SetObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"))); + + if (stmt->action == AP_AddObjects) + { + List *rels; + List *explicitrelids; + List *pubschemaidlist; + ListCell *lc; + + rels = OpenTableList(exceptrelations); + + /* + * Build the effective schema list: schemas already in the publication + * plus any being added in this same command. The latter may not yet + * be visible via a catalog scan if CommandCounterIncrement has not + * been issued, so we include them explicitly. + */ + pubschemaidlist = GetPublicationSchemas(pubid); + pubschemaidlist = list_concat_unique_oid(pubschemaidlist, schemaidlist); + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + foreach(lc, rels) + { + PublicationRelInfo *pri = (PublicationRelInfo *) lfirst(lc); + Oid relid = RelationGetRelid(pri->relation); + Oid relns = RelationGetNamespace(pri->relation); + + if (!list_member_oid(pubschemaidlist, relns)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s.%s\" in EXCEPT clause does not belong to any schema listed in the publication", + get_namespace_name(relns), + RelationGetRelationName(pri->relation))); + + if (list_member_oid(explicitrelids, relid)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s.%s\" cannot appear in both the table list and the EXCEPT clause", + get_namespace_name(relns), + RelationGetRelationName(pri->relation))); + } + + PublicationAddTables(pubid, rels, false, stmt); + + CloseTableList(rels); } } @@ -1771,10 +1887,17 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) errmsg("publication \"%s\" does not exist", stmt->pubname)); - relations = list_concat(relations, exceptrelations); + /* + * For FOR ALL TABLES, EXCEPT entries are processed by + * AlterPublicationTables(), so merge them in. For TABLES IN SCHEMA, + * they are handled separately by AlterPublicationExceptTables(). + */ + if (stmt->for_all_tables) + relations = list_concat(relations, exceptrelations); AlterPublicationTables(stmt, tup, relations, pstate->p_sourcetext, schemaidlist != NIL); AlterPublicationSchemas(stmt, tup, schemaidlist); + AlterPublicationExceptTables(stmt, tup, exceptrelations, schemaidlist); AlterPublicationAllFlags(stmt, rel, tup); } diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index 12271f7e2b1..15b7551dcdc 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2363,6 +2363,32 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); + /* After a single schema name in ADD context, offer EXCEPT ( */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ("); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("("); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + { + if (strchr(prev3_wd, ',') == NULL) + { + set_completion_reference(prev3_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", MatchAnyN) && ends_with(prev_wd, ',')) + { + char *schema_word = previous_words[previous_words_count - 8]; + + if (strchr(schema_word, ',') == NULL) + { + set_completion_reference(schema_word); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 50b3a819d14..e563553e8eb 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -501,9 +501,25 @@ CREATE PUBLICATION testpub_except_err ERROR: EXCEPT is not allowed for TABLE publication objects LINE 2: FOR TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2 EXCEPT... ^ +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; +-- ADD: add a schema with an excepted table +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (pub_test.testpub_tbl_s1); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_alter_except; CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; -- FOR ALL SEQUENCES diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 3f46e8c5e03..3436b832eca 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -240,9 +240,18 @@ CREATE PUBLICATION testpub_schema_except2 CREATE PUBLICATION testpub_except_err FOR TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2 EXCEPT (pub_test.testpub_nopk); +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; + +-- ADD: add a schema with an excepted table +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (pub_test.testpub_tbl_s1); +\dRp+ testpub_alter_except + RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_alter_except; CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 0801d3a77c7..9675db18bef 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -353,6 +353,34 @@ $node_publisher->safe_psql('postgres', $node_subscriber->safe_psql('postgres', 'TRUNCATE sch1.par, sch1.chi, sch1.tab_pub, sch1.tab_exc'); +# ============================================ +# ALTER PUBLICATION EXCEPT for TABLES IN SCHEMA +# ============================================ + +# ADD: add a schema with an excepted table; verify the except entry takes effect. +$node_publisher->safe_psql('postgres', "CREATE PUBLICATION sch_pub"); +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub ADD TABLES IN SCHEMA sch1 EXCEPT (sch1.tab_exc)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_pub"); +is($result, qq(6), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: included table synced'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_exc"); +is($result, qq(0), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + # Cleanup schema tables before the multi-publication section. $node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); $node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); -- 2.50.1 (Apple Git-155)
v2-0003-Add-EXCEPT-support-to-ALTER-PUBLICATION-SET-TABLE.patch (application/octet-stream, 21.6K) download From 8576fe57f11c9224e28b7fd365134d8ce5a26c6b Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Tue, 14 Apr 2026 11:34:07 +0530 Subject: [PATCH v2 3/3] Add EXCEPT support to ALTER PUBLICATION SET TABLES IN SCHEMA Extend AlterPublicationExceptTables() with the AP_SetObjects case, which redefine the publication and replaces the entire EXCEPT list. Syntax: ALTER PUBLICATION pub SET TABLES IN SCHEMA s EXCEPT (s.t1, s.t2); --- doc/src/sgml/ref/alter_publication.sgml | 40 +++++- src/backend/catalog/pg_publication.c | 2 +- src/backend/commands/publicationcmds.c | 156 ++++++++++++++++++++-- src/bin/psql/tab-complete.in.c | 26 ++++ src/test/regress/expected/publication.out | 23 ++++ src/test/regress/sql/publication.sql | 12 ++ src/test/subscription/t/037_except.pl | 90 +++++++++++++ 7 files changed, 328 insertions(+), 21 deletions(-) diff --git a/doc/src/sgml/ref/alter_publication.sgml b/doc/src/sgml/ref/alter_publication.sgml index e901163a89b..c59bf293a59 100644 --- a/doc/src/sgml/ref/alter_publication.sgml +++ b/doc/src/sgml/ref/alter_publication.sgml @@ -97,7 +97,11 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r used with a publication defined with <literal>FOR TABLE</literal> or <literal>FOR TABLES IN SCHEMA</literal>, replaces the list of tables/schemas in the publication with the specified list; the existing tables or schemas - that were present in the publication will be removed. + that were present in the publication will be removed. When + <literal>SET TABLES IN SCHEMA</literal> is used with an + <literal>EXCEPT</literal> clause, the excluded tables for each schema are + replaced with the specified list; if <literal>EXCEPT</literal> is omitted + for a schema, any existing exclusions for that schema are cleared. </para> <para> @@ -116,10 +120,15 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <para> The <literal>EXCEPT</literal> clause can be used with - <literal>ADD TABLES IN SCHEMA</literal> to exclude specific tables from a + <literal>ADD TABLES IN SCHEMA</literal> or + <literal>SET TABLES IN SCHEMA</literal> to exclude specific tables from a schema-level publication. Each excluded table must belong to the schema named in the same <literal>TABLES IN SCHEMA</literal> clause and must be - schema-qualified. <literal>EXCEPT</literal> is not supported with + schema-qualified. With <literal>ADD</literal>, the listed tables are added + to the exclusion list for that schema. With <literal>SET</literal>, the + exclusion list for each named schema is replaced by the specified tables; + omitting <literal>EXCEPT</literal> for a schema clears its exclusion list + entirely. <literal>EXCEPT</literal> is not supported with <literal>DROP TABLES IN SCHEMA</literal>; instead, dropping a schema from the publication automatically removes all of its associated <literal>EXCEPT</literal> entries. @@ -218,10 +227,16 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <listitem> <para> Specifies tables to be excluded from a schema-level publication entry. - This clause may be used with <literal>ADD TABLES IN SCHEMA</literal> - and not with <literal>DROP TABLES IN SCHEMA</literal>. Each named - table must belong to the schema specified in the same <literal>TABLES IN SCHEMA</literal> - clause and must be schema-qualified. See <xref linkend="sql-createpublication"/> + This clause may be used with <literal>ADD TABLES IN SCHEMA</literal> or + <literal>SET TABLES IN SCHEMA</literal>, but not with + <literal>DROP TABLES IN SCHEMA</literal>. Each named table must belong + to the schema specified in the same <literal>TABLES IN SCHEMA</literal> + clause and must be schema-qualified. When used with + <literal>ADD</literal>, the tables are appended to the existing exclusion + list for that schema. When used with <literal>SET</literal>, the + exclusion list for that schema is replaced; omitting + <literal>EXCEPT</literal> clears the exclusion list for that schema. + See <xref linkend="sql-createpublication"/> for further details on the semantics of <literal>EXCEPT</literal>. </para> </listitem> @@ -327,6 +342,17 @@ ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA sales EXCEPT (sales.int </programlisting> </para> + <para> + Replace the schema list of <structname>sales_publication</structname> with + <structname>sales</structname>, excluding only + <structname>sales.drafts</structname> (any previously excluded tables for + that schema are replaced, and schemas previously in the publication are + removed): +<programlisting> +ALTER PUBLICATION sales_publication SET TABLES IN SCHEMA sales EXCEPT (sales.drafts); +</programlisting> + </para> + <para> Add tables <structname>users</structname>, <structname>departments</structname> and schema diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index 85c2528873f..e63f221f1af 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -1002,7 +1002,7 @@ GetIncludedPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) List * GetExcludedPublicationTables(Oid pubid, PublicationPartOpt pub_partopt) { - Assert(GetPublication(pubid)->alltables); + Assert(GetPublication(pubid)->alltables || is_schema_publication(pubid)); return get_publication_relations(pubid, pub_partopt, true); } diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index b26706b5d1d..de20233062b 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -1598,9 +1598,11 @@ AlterPublicationExceptTables(AlterPublicationStmt *stmt, Oid pubid = pubform->oid; /* - * Nothing to do if no EXCEPT entries. + * Nothing to do if no EXCEPT entries, except in SET: for that it is quite + * possible that the user has removed all exceptions, in which case we + * need to drop any existing ones. */ - if (!exceptrelations) + if (!exceptrelations && stmt->action != AP_SetObjects) return; /* @@ -1622,17 +1624,6 @@ AlterPublicationExceptTables(AlterPublicationStmt *stmt, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); - /* - * EXCEPT with SET is not supported: SET replaces the schema list but does - * not have a well-defined semantics for merging or replacing existing - * except entries. Users should DROP and re-ADD the schema with the - * desired EXCEPT list instead. - */ - if (stmt->action == AP_SetObjects) - ereport(ERROR, - (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"))); - if (stmt->action == AP_AddObjects) { List *rels; @@ -1676,6 +1667,106 @@ AlterPublicationExceptTables(AlterPublicationStmt *stmt, PublicationAddTables(pubid, rels, false, stmt); + CloseTableList(rels); + } + else /* AP_SetObjects */ + { + List *oldexceptrelids = NIL; + List *newexceptrelids = NIL; + List *delrelids = NIL; + List *rels; + List *explicitrelids; + List *pubschemaidlist; + ListCell *lc; + + rels = OpenTableList(exceptrelations); + + /* Collect OIDs of the desired new except list. */ + foreach(lc, rels) + { + PublicationRelInfo *pri = (PublicationRelInfo *) lfirst(lc); + + newexceptrelids = lappend_oid(newexceptrelids, + RelationGetRelid(pri->relation)); + } + + /* + * Build the effective schema list: schemas already in the publication + * plus any being set in this same command. The latter may not yet be + * visible via a catalog scan, so we include them explicitly. + */ + pubschemaidlist = GetPublicationSchemas(pubid); + pubschemaidlist = list_concat_unique_oid(pubschemaidlist, schemaidlist); + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + foreach(lc, rels) + { + PublicationRelInfo *pri = (PublicationRelInfo *) lfirst(lc); + Oid relid = RelationGetRelid(pri->relation); + Oid relns = RelationGetNamespace(pri->relation); + + if (!list_member_oid(pubschemaidlist, relns)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s.%s\" in EXCEPT clause does not belong to any schema listed in the publication", + get_namespace_name(relns), + RelationGetRelationName(pri->relation))); + + if (list_member_oid(explicitrelids, relid)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s.%s\" cannot appear in both the table list and the EXCEPT clause", + get_namespace_name(relns), + RelationGetRelationName(pri->relation))); + } + + /* + * Get the current set of except entries. Only FOR ALL TABLES and + * schema-level publications can have except entries; for any other + * publication type oldexceptrelids stays NIL. + * + * Note: we check is_schema_publication() against the current catalog + * state (before AlterPublicationSchemas has run), so if the caller is + * doing SET TABLE t1 to convert a schema publication into a plain + * table publication, is_schema_publication() still returns true here. + * That is intentional: it lets us discover and clean up any stale + * except entries that belong to the old schema definition. + */ + if (GetPublication(pubid)->alltables || is_schema_publication(pubid)) + oldexceptrelids = GetExcludedPublicationTables(pubid, + PUBLICATION_PART_ROOT); + + /* Build a list of old except entries not present in the new list. */ + foreach(lc, oldexceptrelids) + { + Oid oldrelid = lfirst_oid(lc); + + if (!list_member_oid(newexceptrelids, oldrelid)) + delrelids = lappend_oid(delrelids, oldrelid); + } + + /* Drop old except entries not present in the new list. */ + foreach(lc, delrelids) + { + Oid relid = lfirst_oid(lc); + Oid proid; + ObjectAddress obj; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (!OidIsValid(proid)) + continue; /* already gone */ + + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + + /* Add new except entries, skipping any already present. */ + PublicationAddTables(pubid, rels, true, stmt); + CloseTableList(rels); } } @@ -2330,6 +2421,8 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) foreach(lc, schemas) { Oid schemaid = lfirst_oid(lc); + List *exceptoids; + ListCell *elc; psid = GetSysCacheOid2(PUBLICATIONNAMESPACEMAP, Anum_pg_publication_namespace_oid, @@ -2346,8 +2439,45 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) get_namespace_name(schemaid)))); } + /* + * Collect prexcept rows for tables belonging to this schema before + * removing the schema entry. GetExcludedPublicationTables relies on + * is_schema_publication(), which scans pg_publication_namespace; if + * this is the last schema in the publication, performDeletion() below + * would remove that row and make is_schema_publication() return + * false, tripping the assertion. + */ + exceptoids = GetExcludedPublicationTables(pubid, PUBLICATION_PART_ROOT); + ObjectAddressSet(obj, PublicationNamespaceRelationId, psid); performDeletion(&obj, DROP_CASCADE, 0); + + /* + * Drop any prexcept rows for tables belonging to this schema. These + * rows have no pg_depend entry pointing at the + * pg_publication_namespace row, so they are not cascaded by the + * performDeletion() call above and must be cleaned up explicitly. + */ + foreach(elc, exceptoids) + { + Oid relid = lfirst_oid(elc); + Oid proid; + + if (get_rel_namespace(relid) != schemaid) + continue; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (!OidIsValid(proid)) + continue; /* already gone */ + + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + + list_free(exceptoids); } } diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index 15b7551dcdc..a41e1d4a4a5 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2389,6 +2389,32 @@ match_previous_words(int pattern_id, } else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", MatchAnyN) && !ends_with(prev_wd, ',')) COMPLETE_WITH(")"); + /* After a single schema name in SET context, offer EXCEPT ( */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ("); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("("); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + { + if (strchr(prev3_wd, ',') == NULL) + { + set_completion_reference(prev3_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", MatchAnyN) && ends_with(prev_wd, ',')) + { + char *schema_word = previous_words[previous_words_count - 8]; + + if (strchr(schema_word, ',') == NULL) + { + set_completion_reference(schema_word); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index e563553e8eb..9526459f65a 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -517,6 +517,29 @@ Tables from schemas: Except tables: "pub_test.testpub_tbl_s1" +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s2" + +-- error: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (pub_test.testpub_tbl_s2); +ERROR: EXCEPT clause is not supported with DROP in ALTER PUBLICATION +-- error: except table must be schema-qualified +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (testpub_tbl_s1); +ERROR: table "testpub_tbl_s1" in EXCEPT clause must be schema-qualified +LINE 1: ...lter_except SET TABLES IN SCHEMA pub_test EXCEPT (testpub_tb... + ^ +-- error: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to any schema listed in the publication RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_alter_except; diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 3436b832eca..6de78800aa5 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -249,6 +249,18 @@ CREATE PUBLICATION testpub_alter_except; ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (pub_test.testpub_tbl_s1); \dRp+ testpub_alter_except +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + +-- error: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (pub_test.testpub_tbl_s2); + +-- error: except table must be schema-qualified +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (testpub_tbl_s1); +-- error: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (public.testpub_tbl1); + RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_alter_except; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 9675db18bef..e622bfb3d7f 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -378,6 +378,66 @@ $result = is($result, qq(0), 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); +# SET: replace the except list; tab_exc is now included and tab_pub is excluded. +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1 EXCEPT (sch1.tab_pub)" +); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_pub VALUES (7); + INSERT INTO sch1.tab_exc VALUES (7); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_exc"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: newly included table is replicated' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_pub"); +is($result, qq(6), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: now-excluded table is not replicated' +); + +# SET without EXCEPT: clears the except list; both tables are now published. +# tab_pub will be re-synced because REFRESH removed its entry when it was +# excluded. Truncate the subscriber copy beforehand so the re-sync produces +# a predictable count: publisher has 7 rows (6 original + INSERT(7)), so the +# subscriber ends up with 7 after re-sync, then 8 after INSERT(8). +$node_subscriber->safe_psql('postgres', 'TRUNCATE sch1.tab_pub'); +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1"); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_pub VALUES (8); + INSERT INTO sch1.tab_exc VALUES (8); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_pub"); +is($result, qq(8), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_pub replicated after except list cleared' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_exc"); +is($result, qq(2), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_exc replicated after except list cleared' +); + $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); @@ -445,6 +505,36 @@ $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); +# OK when a table is excluded by a TABLES IN SCHEMA EXCEPT publication, +# but is included by another publication. +$node_publisher->safe_psql('postgres', 'TRUNCATE tab1'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE tab1'); + +$node_publisher->safe_psql( + 'postgres', qq( + CREATE PUBLICATION tap_pub1 FOR TABLES IN SCHEMA public EXCEPT (public.tab1); + CREATE PUBLICATION tap_pub2 FOR TABLE tab1; + INSERT INTO tab1 VALUES(1); +)); +$node_subscriber->psql('postgres', + "CREATE SUBSCRIPTION tap_sub CONNECTION '$publisher_connstr' PUBLICATION tap_pub1, tap_pub2" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'tap_sub'); + +$node_publisher->safe_psql('postgres', qq(INSERT INTO tab1 VALUES(2))); +$node_publisher->wait_for_catchup('tap_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT * FROM tab1 ORDER BY a"); +is( $result, qq(1 +2), + "TABLES IN SCHEMA EXCEPT: table excluded in schema pub but included by another pub is replicated" +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); + $node_publisher->stop('fast'); done_testing(); -- 2.50.1 (Apple Git-155)
^ permalink raw reply [nested|flat] 196+ messages in thread

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-04-15 14:17  Nisha Moond <nisha.moond412@gmail.com>
  parent: vignesh C <vignesh21@gmail.com>
  0 siblings, 0 replies; 196+ messages in thread

From: Nisha Moond @ 2026-04-15 14:17 UTC (permalink / raw)
  To: vignesh C <vignesh21@gmail.com>; +Cc: PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Wed, Apr 15, 2026 at 11:18 AM vignesh C <vignesh21@gmail.com> wrote:
>
> On Tue, 14 Apr 2026 at 12:00, Nisha Moond <nisha.moond412@gmail.com> wrote:
> >
>
> Few comments for the second patch:

Thanks for the review.

> 1) This patch adds support only for:
>   ALTER PUBLICATION pub ADD TABLES IN SCHEMA s EXCEPT (s.t1, s.t2);
>
> But documentation mentions for both add and set:
> @@ -31,7 +31,7 @@ ALTER PUBLICATION <replaceable
> class="parameter">name</replaceable> RENAME TO <r
>  <phrase>where <replaceable
> class="parameter">publication_object</replaceable> is one of:</phrase>
>
>      TABLE <replaceable
> class="parameter">table_and_columns</replaceable> [, ... ]
> -    TABLES IN SCHEMA { <replaceable
> class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ...
> ]
> +    TABLES IN SCHEMA { <replaceable
> class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [
> EXCEPT ( <replaceable
> class="parameter">except_table_object</replaceable> [, ... ] ) ] [,
> ... ]
>

Fixed the doc descriptions where SET was mentioned in patch-002.
But for the synopsis, I feel it will be unnecessary to first separate
the ADD and SET publication objects like "publication_add_object" and
"publication_set_object" in patch-002 and then remove them in
patch-003. Please let me know if you think otherwise.

> 2) Tab completion missing for:
> alter publication pub1 add TABLES IN SCHEMA sch1
>

Done.

> 3) Currently Set tables in schema sch1 also works partially with the
> second patch without adding the except tables:
> postgres=# alter publication pub1 set tables in schema sch1 except (sch1.t1);
> ALTER PUBLICATION
> postgres=# \dRp+ pub1
>                                                       Publication pub1
>   Owner  | All tables | All sequences | Inserts | Updates | Deletes |
> Truncates | Generated columns | Via root | Description
> ---------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+-------------
>  vignesh | f          | f             | t       | t       | t       |
> t         | none              | f        |
> Tables from schemas:
>     "sch1"
>
> Should there be a check here to throw an error:
> +static void
> +AlterPublicationExceptTables(AlterPublicationStmt *stmt,
> +                                                        HeapTuple
> tup, List *exceptrelations,
> +                                                        List *schemaidlist)
> +{
> +       Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup);
> +       Oid                     pubid = pubform->oid;
> +
> +       /*
> +        * Nothing to do if no EXCEPT entries.
> +        */
> +       if (!exceptrelations)
> +               return;
> +
>

Fixed

> 4) Can this check be done at parser itself, it can be done in
> preprocess_pubobj_list parser function to detect the error early:
> +               foreach(lc, exceptrelations)
> +               {
> +                       PublicationTable *t = (PublicationTable *) lfirst(lc);
> +
> +                       if (t->relation->schemaname == NULL)
> +                               ereport(ERROR,
> +
> errcode(ERRCODE_INVALID_PARAMETER_VALUE),
> +                                               errmsg("table \"%s\"
> in EXCEPT clause must be schema-qualified",
> +
> t->relation->relname));
> +               }
>

Fixed.

All above comments are addressed in v2 attached above.

[1]
--
Thanks,
Nisha





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-04-16 00:13  Peter Smith <smithpb2250@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: Peter Smith @ 2026-04-16 00:13 UTC (permalink / raw)
  To: shveta malik <shveta.malik@gmail.com>; +Cc: Nisha Moond <nisha.moond412@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Wed, Apr 15, 2026 at 8:15 PM shveta malik <shveta.malik@gmail.com> wrote:
>
> On Wed, Apr 15, 2026 at 2:22 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
> >
> > On Tue, Apr 14, 2026 at 3:22 PM shveta malik <shveta.malik@gmail.com> wrote:
> > >
> > > On Tue, Apr 14, 2026 at 3:15 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
> > > >
> > > > On Tue, Apr 14, 2026 at 1:03 PM Peter Smith <smithpb2250@gmail.com> wrote:
> > > > >
> > > > > On Tue, Apr 14, 2026 at 4:30 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
> > > > > >
> > > > > > Hi hackers,
> > > > > >
> > > > > > Following earlier work to support EXCEPT for FOR ALL TABLES [1]
> > > > > > publications, starting this thread to extend the same capability to
> > > > > > schema-level publications (TABLES IN SCHEMA).
> > > > >
> > > > > Hi Nisha.
> > > > >
> > > > > +1 for adding this new kind of exclusion clause to CREATE PUBLICATION command.
> > > > >
> > > > > >
> > > > > > Currently, TABLES IN SCHEMA publishes all tables in a schema with no
> > > > > > way to exclude a subset. Users who want to skip a few tables must
> > > > > > switch to an explicit FOR TABLE list, which loses the convenience of
> > > > > > schema-level publishing and requires ongoing maintenance as tables are
> > > > > > added.
> > > > > >
> > > > > > Proposed syntax:
> > > > > > ------------------------
> > > > > > CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1 EXCEPT (s1.t1, s1.t2);
> > > > > > ALTER PUBLICATION pub ADD TABLES IN SCHEMA s1 EXCEPT (s1.t1);
> > > > > > ALTER PUBLICATION pub SET TABLES IN SCHEMA s1 EXCEPT (s1.t1);
> > > > > >
> > > > > > Note: Tables in the EXCEPT clause must be schema-qualified to avoid
> > > > > > ambiguity and must belong to the published schema; otherwise, an error
> > > > > > is raised.
> > > > > >
> > > > >
> > > > > The proposed syntax is almost, but not quite, what I was anticipating.
> > > > > IMO the syntax shouldn't just be similar to the FOR ALL TABLES EXCEPT;
> > > > > It can be *identical* to it. e.g., your examples are missing the
> > > > > 'TABLE' keyword necessary to achieve the same command flexibility.
> > > > >
> > > >
> > > > I intentionally didn’t use the TABLE keyword inside EXCEPT.
> > > > IIUC, for FOR ALL TABLES EXCEPT, there may be a future need to
> > > > distinguish object types (e.g., tables vs schemas), which is why
> > > > specifying TABLE makes sense there.
> > > >
> > > > However, for TABLES IN SCHEMA, only tables can be specified, so
> > > > omitting TABLE keeps the syntax simpler and more intuitive.
> > > >
> > > > Let's hear others’ opinions too on this and I'll adjust if there’s a
> > > > preference for including it.
> > > >
> > >
> > > Nisha, please see pt 1 in [1]. If we plan to support that, then we
> > > need TABLE keyword, otherwise we are fine.
> > >
> > > [1]: https://www.postgresql.org/message-id/CAJpy0uB%3DJxTYXOB7VmrhVLR%2B1PG0%3DTtHuGekaqibOPpo2UBLiQ%40ma...
> > >
> >
> > Thank you Shveta for pointing to the discussion.
> > So, if we were to extend CREATE PUBLICATION to support something like:
> >  "CREATE PUBLICATION pub FOR TABLES, SEQUENCES IN SCHEMA sch1 EXCEPT
> > (TABLE t1,  SEQUENCE s1);"
> > then, introducing TABLE inside EXCEPT could make sense, but at this
> > stage we’re not sure how the syntax for supporting SEQUENCES IN SCHEMA
> > will evolve. The overall grammar may require broader changes rather
> > than a simple extension. So, we can always introduce keywords like
> > TABLE or SEQUENCE later, if and when they are actually needed. Just my
> > thoughts.
> >
>
> It works for me Nisha. I also agree that the 'TABLE' keyword seems
> redundant in the case you proposed:
> CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1 EXCEPT (s1.t1, s1.t2);
>
> But I am just worried this might confuse users, as one command
> requires specifying the TABLE with EXCEPT, while another requires
> omitting it. But we can first focus on implementation and come back to
> it later when more people join and share their thoughts.
>

I agree with Shveta that inconsistency will confuse.

We already have FOR ALL TABLES EXCEPT (TABLE ...) [1]
And another place is currently introducing FOR ALL SEQUENCES EXCEPT
(SEQUENCE ...) [2]
IMO, this schema thread should match [1].

I think syntax *consistency* should take priority here. While some
keywords may end up being unnecessary in certain cases, having
different rules for each EXCEPT variation seems harder to maintain and
reason about.

I also agree with you that we are not sure how the command syntax
might evolve in future. That is another reason why requiring these
keywords (like 'TABLE' and 'SEQUENCE') is the best/safest first
approach, IMO, because it will be backward-compatible. For example, if
it turns out we can make (some of) these keywords optional in future,
then user code will still be fine, but if they are absent now, then we
cannot make them mandatory in future PostgreSQL versions without
breaking user code.

======
[1] https://www.postgresql.org/docs/devel/sql-createpublication.html
[2] https://www.postgresql.org/message-id/CANhcyEVSXyQkvmrsOWPdQqnm2J3GMyQQrKhyCJiBQzqs6AvSow%40mail.gma...

Kind Regards,
Peter Smith.
Fujitsu Australia





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-04-16 10:30  Nisha Moond <nisha.moond412@gmail.com>
  parent: Peter Smith <smithpb2250@gmail.com>
  0 siblings, 0 replies; 196+ messages in thread

From: Nisha Moond @ 2026-04-16 10:30 UTC (permalink / raw)
  To: Peter Smith <smithpb2250@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Thu, Apr 16, 2026 at 5:44 AM Peter Smith <smithpb2250@gmail.com> wrote:
>
> On Wed, Apr 15, 2026 at 8:15 PM shveta malik <shveta.malik@gmail.com> wrote:
> >
> > On Wed, Apr 15, 2026 at 2:22 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
> > >
> > > On Tue, Apr 14, 2026 at 3:22 PM shveta malik <shveta.malik@gmail.com> wrote:
> > > >
> > > > On Tue, Apr 14, 2026 at 3:15 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
> > > > >
> > > > > On Tue, Apr 14, 2026 at 1:03 PM Peter Smith <smithpb2250@gmail.com> wrote:
> > > > > >
> > > > > > On Tue, Apr 14, 2026 at 4:30 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
> > > > > > >
> > > > > > > Hi hackers,
> > > > > > >
> > > > > > > Following earlier work to support EXCEPT for FOR ALL TABLES [1]
> > > > > > > publications, starting this thread to extend the same capability to
> > > > > > > schema-level publications (TABLES IN SCHEMA).
> > > > > >
> > > > > > Hi Nisha.
> > > > > >
> > > > > > +1 for adding this new kind of exclusion clause to CREATE PUBLICATION command.
> > > > > >
> > > > > > >
> > > > > > > Currently, TABLES IN SCHEMA publishes all tables in a schema with no
> > > > > > > way to exclude a subset. Users who want to skip a few tables must
> > > > > > > switch to an explicit FOR TABLE list, which loses the convenience of
> > > > > > > schema-level publishing and requires ongoing maintenance as tables are
> > > > > > > added.
> > > > > > >
> > > > > > > Proposed syntax:
> > > > > > > ------------------------
> > > > > > > CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1 EXCEPT (s1.t1, s1.t2);
> > > > > > > ALTER PUBLICATION pub ADD TABLES IN SCHEMA s1 EXCEPT (s1.t1);
> > > > > > > ALTER PUBLICATION pub SET TABLES IN SCHEMA s1 EXCEPT (s1.t1);
> > > > > > >
> > > > > > > Note: Tables in the EXCEPT clause must be schema-qualified to avoid
> > > > > > > ambiguity and must belong to the published schema; otherwise, an error
> > > > > > > is raised.
> > > > > > >
> > > > > >
> > > > > > The proposed syntax is almost, but not quite, what I was anticipating.
> > > > > > IMO the syntax shouldn't just be similar to the FOR ALL TABLES EXCEPT;
> > > > > > It can be *identical* to it. e.g., your examples are missing the
> > > > > > 'TABLE' keyword necessary to achieve the same command flexibility.
> > > > > >
> > > > >
> > > > > I intentionally didn’t use the TABLE keyword inside EXCEPT.
> > > > > IIUC, for FOR ALL TABLES EXCEPT, there may be a future need to
> > > > > distinguish object types (e.g., tables vs schemas), which is why
> > > > > specifying TABLE makes sense there.
> > > > >
> > > > > However, for TABLES IN SCHEMA, only tables can be specified, so
> > > > > omitting TABLE keeps the syntax simpler and more intuitive.
> > > > >
> > > > > Let's hear others’ opinions too on this and I'll adjust if there’s a
> > > > > preference for including it.
> > > > >
> > > >
> > > > Nisha, please see pt 1 in [1]. If we plan to support that, then we
> > > > need TABLE keyword, otherwise we are fine.
> > > >
> > > > [1]: https://www.postgresql.org/message-id/CAJpy0uB%3DJxTYXOB7VmrhVLR%2B1PG0%3DTtHuGekaqibOPpo2UBLiQ%40ma...
> > > >
> > >
> > > Thank you Shveta for pointing to the discussion.
> > > So, if we were to extend CREATE PUBLICATION to support something like:
> > >  "CREATE PUBLICATION pub FOR TABLES, SEQUENCES IN SCHEMA sch1 EXCEPT
> > > (TABLE t1,  SEQUENCE s1);"
> > > then, introducing TABLE inside EXCEPT could make sense, but at this
> > > stage we’re not sure how the syntax for supporting SEQUENCES IN SCHEMA
> > > will evolve. The overall grammar may require broader changes rather
> > > than a simple extension. So, we can always introduce keywords like
> > > TABLE or SEQUENCE later, if and when they are actually needed. Just my
> > > thoughts.
> > >
> >
> > It works for me Nisha. I also agree that the 'TABLE' keyword seems
> > redundant in the case you proposed:
> > CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1 EXCEPT (s1.t1, s1.t2);
> >
> > But I am just worried this might confuse users, as one command
> > requires specifying the TABLE with EXCEPT, while another requires
> > omitting it. But we can first focus on implementation and come back to
> > it later when more people join and share their thoughts.
> >
>
> I agree with Shveta that inconsistency will confuse.
>
> We already have FOR ALL TABLES EXCEPT (TABLE ...) [1]
> And another place is currently introducing FOR ALL SEQUENCES EXCEPT
> (SEQUENCE ...) [2]
> IMO, this schema thread should match [1].
>
> I think syntax *consistency* should take priority here. While some
> keywords may end up being unnecessary in certain cases, having
> different rules for each EXCEPT variation seems harder to maintain and
> reason about.
>
> I also agree with you that we are not sure how the command syntax
> might evolve in future. That is another reason why requiring these
> keywords (like 'TABLE' and 'SEQUENCE') is the best/safest first
> approach, IMO, because it will be backward-compatible. For example, if
> it turns out we can make (some of) these keywords optional in future,
> then user code will still be fine, but if they are absent now, then we
> cannot make them mandatory in future PostgreSQL versions without
> breaking user code.
>

Okay, to maintain consistency in the EXCEPT syntax across publication
commands and keeping future compatibility in mind, I’m fine updating
the syntax.
I’ll share an updated patch soon.

--
Thanks,
Nisha





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-04-16 10:54  Nisha Moond <nisha.moond412@gmail.com>
  parent: Peter Smith <smithpb2250@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: Nisha Moond @ 2026-04-16 10:54 UTC (permalink / raw)
  To: Peter Smith <smithpb2250@gmail.com>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; shveta malik <shveta.malik@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Wed, Apr 15, 2026 at 7:35 AM Peter Smith <smithpb2250@gmail.com> wrote:
>
> On Tue, Apr 14, 2026 at 7:37 PM Amit Kapila <amit.kapila16@gmail.com> wrote:
> >
> > On Tue, Apr 14, 2026 at 2:05 PM shveta malik <shveta.malik@gmail.com> wrote:
> > >
> > > On Tue, Apr 14, 2026 at 1:03 PM Peter Smith <smithpb2250@gmail.com> wrote:
> > > >
> > > > On Tue, Apr 14, 2026 at 4:30 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
> > > > >
> > > > > Hi hackers,
> > > > >
> > > > > Following earlier work to support EXCEPT for FOR ALL TABLES [1]
> > > > > publications, starting this thread to extend the same capability to
> > > > > schema-level publications (TABLES IN SCHEMA).
> > > >
> > > > Hi Nisha.
> > > >
> > > > +1 for adding this new kind of exclusion clause to CREATE PUBLICATION command.
> > > >
> > > > >
> > > > > Currently, TABLES IN SCHEMA publishes all tables in a schema with no
> > > > > way to exclude a subset. Users who want to skip a few tables must
> > > > > switch to an explicit FOR TABLE list, which loses the convenience of
> > > > > schema-level publishing and requires ongoing maintenance as tables are
> > > > > added.
> > > > >
> > > > > Proposed syntax:
> > > > > ------------------------
> > > > > CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1 EXCEPT (s1.t1, s1.t2);
> > > > > ALTER PUBLICATION pub ADD TABLES IN SCHEMA s1 EXCEPT (s1.t1);
> > > > > ALTER PUBLICATION pub SET TABLES IN SCHEMA s1 EXCEPT (s1.t1);
> > > > >
> > > > > Note: Tables in the EXCEPT clause must be schema-qualified to avoid
> > > > > ambiguity and must belong to the published schema; otherwise, an error
> > > > > is raised.
> > > > >
> > > >
> > > > The proposed syntax is almost, but not quite, what I was anticipating.
> > > > IMO the syntax shouldn't just be similar to the FOR ALL TABLES EXCEPT;
> > > > It can be *identical* to it. e.g., your examples are missing the
> > > > 'TABLE' keyword necessary to achieve the same command flexibility.
> > > > Furthermore, what is the ambiguity referred to? An excluded table is
> > > > clearly associated with the preceding schema. Can't the code infer the
> > > > schema internally even when it is not provided by the user? Of course,
> > > > the user *can* specify a schema-qualified name if they want to, but I
> > > > didn't see why we are forcing that rule upon them.
> > >
> > > +1. I also feel specifying only the table name is clear enough. Or are
> > > we referring to implementation complexity here?
> > >
> >
> > I think it will add complexity. Consider an example:
> > CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1, s2, s3 EXCEPT (t1, t2);
> >
> > So, which schema's exclusion list will these tables should be
> > considered for? Say, if table with name t1 is present in all schemas
> > then shall we exclude from all schemas or just consider it excluded
> > from the first one (s1)?
> >
>
> The exact pattern is already in common usage for row-filters and
> column-lists, yet nobody is confused.
>
> -- all these tables have the same column names
> -- (analogous to multiple schemas having same table names)
> CREATE TABLE t1(c1 int, c2 int);
> CREATE TABLE t2(c1 int, c2 int);
> CREATE TABLE t3(c1 int, c2 int);
>
> -- all tables have a column c1
> -- but this c1 means t3.c1 because the column-list is only for the adjacent t3.
> CREATE PUBLICATION pub1 FOR TABLE t1, t2, t3 (c1);
>
> -- all tables have a column c2
> -- but this c2 means t3.c2 because the row-filter is only for the adjacent t3.
> CREATE PUBLICATION pub2 FOR TABLE t1, t2, t3 WHERE (c2 > 99);
>
> \dRp+
>                                                        Publication pub1
>   Owner   | All tables | All sequences | Inserts | Updates | Deletes |
> Truncates | Generated columns | Via root | Description
> ----------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+-------------
>  postgres | f          | f             | t       | t       | t       |
> t         | none              | f        |
> Tables:
>     "public.t1"
>     "public.t2"
>     "public.t3" (c1)
>
>                                                        Publication pub2
>   Owner   | All tables | All sequences | Inserts | Updates | Deletes |
> Truncates | Generated columns | Via root | Description
> ----------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+-------------
>  postgres | f          | f             | t       | t       | t       |
> t         | none              | f        |
> Tables:
>     "public.t1"
>     "public.t2"
>     "public.t3" WHERE (c2 > 99)
>

My intention was to avoid potential ambiguity when tables are not
schema-qualified, as mentioned by Amit [1].

That said, PostgreSQL generally does not enforce schema qualification
and relies on search_path [2][3] for object resolution. Users are
typically familiar with this behavior.

Thanks for the example. I’ve updated the syntax to allow tables in the
EXCEPT list without schema qualification.
If a table is specified without a schema, it is resolved against the
immediately preceding schema clause.

Few examples:
CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1, s2 EXCEPT (TABLE t1);
-- table t1 is resolved in schema s2

CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1 EXCEPT (TABLE t1), s2
EXCEPT (TABLE t2);
-- if s1 does not contain t1, an error is raised: "s1.t1" does not exist

CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1, s2 EXCEPT (TABLE s1.t1, s2.t1);
-- it will create the publication with except list - (s1.t1, s2.t1)

Attached v3 patches with the following updates:
1) Updated syntax to include TABLE keyword as per discussion [1]
    CREATE/ALTER PUBLICATION ... FOR TABLES IN SCHEMA s1 EXCEPT (TABLE t1, ...);
2) Removed the requirement for schema-qualified table names in the EXCEPT list.

[1] https://www.postgresql.org/message-id/CAA4eK1KbCWBmEXH-rhQjKgNwq%3DonZp8vRR-QkRhPpbKwL-kQdw%40mail.g...
[2] https://www.postgresql.org/docs/current/ddl-schemas.html#DDL-SCHEMAS-PATH
[3] https://www.postgresql.org/docs/current/runtime-config-client.html#GUC-SEARCH-PATH

--
Thanks,
Nisha

Attachments: download all (3 files, .tar.gz)

v3-0001-Support-EXCEPT-clause-for-schema-level-publicatio.patch (application/octet-stream, 39.4K) download From 0b3b5c75aa3dd1ffd7c778d908d2e4ce5602bc89 Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Mon, 13 Apr 2026 17:49:44 +0530 Subject: [PATCH v3 1/3] Support EXCEPT clause for schema-level publications Extend table exclusion support in publications to allow specific tables to be excluded from schema-level publications using an EXCEPT clause in CREATE PUBLICATION. Supported syntax: CREATE PUBLICATION <pub> FOR TABLES IN SCHEMA s EXCEPT (TABLE t1,...); --- doc/src/sgml/logical-replication.sgml | 3 +- doc/src/sgml/ref/create_publication.sgml | 16 ++- src/backend/catalog/pg_publication.c | 107 ++++++++++++--- src/backend/commands/publicationcmds.c | 60 +++++++++ src/backend/parser/gram.y | 41 +++++- src/backend/replication/pgoutput/pgoutput.c | 34 ++++- src/bin/pg_dump/pg_dump.c | 30 ++++- src/bin/pg_dump/t/002_pg_dump.pl | 36 +++++ src/bin/psql/describe.c | 18 +++ src/bin/psql/tab-complete.in.c | 37 +++++- src/include/nodes/parsenodes.h | 1 + src/test/regress/expected/publication.out | 48 ++++++- src/test/regress/sql/publication.sql | 31 ++++- src/test/subscription/t/037_except.pl | 139 +++++++++++++++++++- 14 files changed, 564 insertions(+), 37 deletions(-) diff --git a/doc/src/sgml/logical-replication.sgml b/doc/src/sgml/logical-replication.sgml index 23b268273b9..66ae192222d 100644 --- a/doc/src/sgml/logical-replication.sgml +++ b/doc/src/sgml/logical-replication.sgml @@ -117,7 +117,8 @@ or <literal>FOR ALL SEQUENCES</literal>. Unlike tables, sequences can be synchronized at any time. For more information, see <xref linkend="logical-replication-sequences"/>. When a publication is - created with <literal>FOR ALL TABLES</literal>, a table or set of tables can + created with <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal>, a table or set of tables can be explicitly excluded from publication using the <link linkend="sql-createpublication-params-for-except-table"><literal>EXCEPT</literal></link> clause. diff --git a/doc/src/sgml/ref/create_publication.sgml b/doc/src/sgml/ref/create_publication.sgml index 0ac576d3f10..0060efb0b3a 100644 --- a/doc/src/sgml/ref/create_publication.sgml +++ b/doc/src/sgml/ref/create_publication.sgml @@ -28,7 +28,7 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -142,6 +142,8 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <para> Marks the publication as one that replicates changes for all tables in the specified list of schemas, including tables created in the future. + Tables listed in <literal>EXCEPT</literal> for a given schema are + excluded from the publication. </para> <para> @@ -198,7 +200,8 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <listitem> <para> This clause specifies a list of tables to be excluded from the - publication. + publication. It can be used with both <literal>FOR ALL TABLES</literal> + and <literal>FOR TABLES IN SCHEMA</literal>. </para> <para> For inherited tables, if <literal>ONLY</literal> is specified before the @@ -515,6 +518,15 @@ CREATE PUBLICATION production_publication FOR TABLE users, departments, TABLES I CREATE PUBLICATION sales_publication FOR TABLES IN SCHEMA marketing, sales; </programlisting></para> + <para> + Create a publication that publishes all changes for all the tables present in + the schema <structname>sales</structname>, except + <structname>sales.internal</structname> and <structname>sales.drafts</structname>: +<programlisting> +CREATE PUBLICATION sales_filtered FOR TABLES IN SCHEMA sales EXCEPT (TABLE sales.internal, sales.drafts); +</programlisting> + </para> + <para> Create a publication that publishes all changes for table <structname>users</structname>, but replicates only columns <structname>user_id</structname> and diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index a43d385c605..85c2528873f 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -529,6 +529,7 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, referenced; List *relids = NIL; int i; + HeapTuple existing; bool inval_except_table; rel = table_open(PublicationRelRelationId, RowExclusiveLock); @@ -538,18 +539,33 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, * duplicates, it's here just to provide nicer error message in common * case. The real protection is the unique key on the catalog. */ - if (SearchSysCacheExists2(PUBLICATIONRELMAP, ObjectIdGetDatum(relid), - ObjectIdGetDatum(pubid))) + existing = SearchSysCache2(PUBLICATIONRELMAP, ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + + if (HeapTupleIsValid(existing)) { + Form_pg_publication_rel existing_form = + (Form_pg_publication_rel) GETSTRUCT(existing); + bool is_except = existing_form->prexcept; + + ReleaseSysCache(existing); table_close(rel, RowExclusiveLock); if (if_not_exists) return InvalidObjectAddress; - ereport(ERROR, - (errcode(ERRCODE_DUPLICATE_OBJECT), - errmsg("relation \"%s\" is already member of publication \"%s\"", - RelationGetRelationName(targetrel), pub->name))); + if (is_except) + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("table \"%s.%s\" cannot be added because it is listed in EXCEPT clause of publication \"%s\"", + get_namespace_name(RelationGetNamespace(targetrel)), + RelationGetRelationName(targetrel), + pub->name))); + else + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("relation \"%s\" is already member of publication \"%s\"", + RelationGetRelationName(targetrel), pub->name))); } check_publication_add_relation(pri); @@ -620,19 +636,24 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, /* * Determine whether EXCEPT tables require explicit relcache invalidation. * - * For CREATE PUBLICATION with EXCEPT tables, invalidation is skipped - * here, as CreatePublication() function invalidates all relations as part - * of defining a FOR ALL TABLES publication. + * For CREATE PUBLICATION with EXCEPT tables, invalidation is skipped here + * because the excluded tables were never included in the publication, so + * no subscriber cache entry needs to be cleared. + * + * For ALTER PUBLICATION, invalidation is needed when adding an EXCEPT + * table to either: - a FOR ALL TABLES publication (pub->alltables is + * true), or - a FOR TABLES IN SCHEMA publication (is_schema_publication + * is true). * - * For ALTER PUBLICATION, invalidation is needed only when adding an - * EXCEPT table to a publication already marked as ALL TABLES. For - * publications that were originally empty or defined as ALL SEQUENCES and - * are being converted to ALL TABLES, invalidation is skipped here, as - * AlterPublicationAllFlags() function invalidates all relations while - * marking the publication as ALL TABLES publication. + * The exception: when a publication is being converted to FOR ALL TABLES + * (pub->alltables is still false at this point), + * AlterPublicationAllFlags() will perform a full invalidation, so we skip + * it here. */ - inval_except_table = (alter_stmt != NULL) && pub->alltables && - (alter_stmt->for_all_tables && pri->except); + inval_except_table = (alter_stmt != NULL) && pri->except && + (pub->alltables + ? alter_stmt->for_all_tables + : is_schema_publication(pubid)); if (!pri->except || inval_except_table) { @@ -975,7 +996,8 @@ GetIncludedPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) * Gets list of table oids that were specified in the EXCEPT clause for a * publication. * - * This should only be used FOR ALL TABLES publications. + * This is used for FOR ALL TABLES and FOR TABLES IN SCHEMA publications, + * both of which support EXCEPT TABLE. */ List * GetExcludedPublicationTables(Oid pubid, PublicationPartOpt pub_partopt) @@ -1225,22 +1247,67 @@ GetSchemaPublicationRelations(Oid schemaid, PublicationPartOpt pub_partopt) /* * Gets the list of all relations published by FOR TABLES IN SCHEMA - * publication. + * publication, excluding any tables listed in the EXCEPT clause. */ List * GetAllSchemaPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) { List *result = NIL; List *pubschemalist = GetPublicationSchemas(pubid); + List *exceptlist = NIL; ListCell *cell; + /* get the list of tables excluded via EXCEPT TABLE for this publication */ + if (pubschemalist != NIL) + exceptlist = get_publication_relations(pubid, pub_partopt, true); + foreach(cell, pubschemalist) { Oid schemaid = lfirst_oid(cell); List *schemaRels = NIL; schemaRels = GetSchemaPublicationRelations(schemaid, pub_partopt); - result = list_concat(result, schemaRels); + + if (exceptlist != NIL) + { + /* filter out any tables that appear in the EXCEPT list */ + ListCell *rlc; + + foreach(rlc, schemaRels) + { + Oid relid = lfirst_oid(rlc); + bool excluded = list_member_oid(exceptlist, relid); + + /* + * Also exclude any relation whose partition ancestor is in + * the EXCEPT list. This matters when pub_partopt is + * PUBLICATION_PART_ROOT: the except list holds only the root + * OID, but the schema scan may also return individual + * partition relations that live in the same schema. + */ + if (!excluded && get_rel_relispartition(relid)) + { + List *ancestors = get_partition_ancestors(relid); + ListCell *alc; + + foreach(alc, ancestors) + { + if (list_member_oid(exceptlist, lfirst_oid(alc))) + { + excluded = true; + break; + } + } + list_free(ancestors); + } + + if (!excluded) + result = lappend_oid(result, relid); + } + list_free(schemaRels); + } + else + result = list_concat(result, schemaRels); } return result; diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 440adb356ad..064e35accbb 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -959,6 +959,8 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) } else if (!stmt->for_all_sequences) { + List *explicitrelids = NIL; + /* FOR TABLES IN SCHEMA requires superuser */ if (schemaidlist != NIL && !superuser()) ereport(ERROR, @@ -968,6 +970,7 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) if (relations != NIL) { List *rels; + ListCell *lc; rels = OpenTableList(relations); TransformPubWhereClauses(rels, pstate->p_sourcetext, @@ -977,6 +980,23 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) schemaidlist != NIL, publish_via_partition_root); + /* + * Collect explicit table OIDs now, before we close the relation + * list, so that except-table validation below can check for + * contradictions without relying on a catalog scan that might not + * yet see the just-inserted rows. + */ + if (exceptrelations != NIL) + { + foreach(lc, rels) + { + PublicationRelInfo *pri = (PublicationRelInfo *) lfirst(lc); + + explicitrelids = lappend_oid(explicitrelids, + RelationGetRelid(pri->relation)); + } + } + PublicationAddTables(puboid, rels, true, NULL); CloseTableList(rels); } @@ -989,6 +1009,46 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) */ LockSchemaList(schemaidlist); PublicationAddSchemas(puboid, schemaidlist, true, NULL); + + if (exceptrelations != NIL) + { + List *rels; + ListCell *lc; + + rels = OpenTableList(exceptrelations); + + /* + * Validate that each excluded table belongs to one of the + * schemas listed in this publication, and is not also in the + * explicit table list (which would be contradictory). Use the + * in-memory explicitrelids collected above rather than + * re-reading the catalog, which may not yet see the + * just-inserted rows. + */ + foreach(lc, rels) + { + PublicationRelInfo *pri = (PublicationRelInfo *) lfirst(lc); + Oid relid = RelationGetRelid(pri->relation); + Oid relns = RelationGetNamespace(pri->relation); + + if (!list_member_oid(schemaidlist, relns)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s.%s\" in EXCEPT clause does not belong to any schema listed in the publication", + get_namespace_name(relns), + RelationGetRelationName(pri->relation))); + + if (list_member_oid(explicitrelids, relid)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s.%s\" cannot appear in both the table list and the EXCEPT clause", + get_namespace_name(relns), + RelationGetRelationName(pri->relation))); + } + + PublicationAddTables(puboid, rels, true, NULL); + CloseTableList(rels); + } } } diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y index 2d1b19d1f53..b87fe1ede84 100644 --- a/src/backend/parser/gram.y +++ b/src/backend/parser/gram.y @@ -11272,7 +11272,7 @@ AlterOwnerStmt: ALTER AGGREGATE aggregate_with_argtypes OWNER TO RoleSpec * pub_obj is one of: * * TABLE table [, ...] - * TABLES IN SCHEMA schema [, ...] + * TABLES IN SCHEMA schema [EXCEPT ( table [, ...] )] [, ...] * *****************************************************************************/ @@ -11332,23 +11332,26 @@ PublicationObjSpec: $$->pubtable->columns = $3; $$->pubtable->whereClause = $4; } - | TABLES IN_P SCHEMA ColId + | TABLES IN_P SCHEMA ColId opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_SCHEMA; $$->name = $4; + $$->except_tables = $5; $$->location = @4; } - | TABLES IN_P SCHEMA CURRENT_SCHEMA + | TABLES IN_P SCHEMA CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_CUR_SCHEMA; + $$->except_tables = $5; $$->location = @4; } - | ColId opt_column_list OptWhereClause + | ColId opt_column_list OptWhereClause opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $4; /* * If either a row filter or column list is specified, create * a PublicationTable object. @@ -11392,10 +11395,11 @@ PublicationObjSpec: $$->pubtable->columns = $2; $$->pubtable->whereClause = $3; } - | CURRENT_SCHEMA + | CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $2; $$->location = @1; } ; @@ -20784,11 +20788,14 @@ preprocess_pub_all_objtype_list(List *all_objects_list, List **pubobjects, /* * Process pubobjspec_list to check for errors in any of the objects and * convert PUBLICATIONOBJ_CONTINUATION into appropriate PublicationObjSpecType. + * Also flattens except_tables from TABLES IN SCHEMA nodes into the list so + * that ObjectsInPublicationToOids() sees them as top-level EXCEPT_TABLE entries. */ static void preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) { ListCell *cell; + ListCell *lc; PublicationObjSpec *pubobj; PublicationObjSpecType prevobjtype = PUBLICATIONOBJ_CONTINUATION; @@ -20812,6 +20819,13 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLE) { + /* EXCEPT is not valid for table objects */ + if (pubobj->except_tables != NIL) + ereport(ERROR, + errcode(ERRCODE_SYNTAX_ERROR), + errmsg("EXCEPT is not allowed for TABLE publication objects"), + parser_errposition(pubobj->location)); + /* relation name or pubtable must be set for this type of object */ if (!pubobj->name && !pubobj->pubtable) ereport(ERROR, @@ -20860,6 +20874,23 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) errcode(ERRCODE_SYNTAX_ERROR), errmsg("invalid schema name"), parser_errposition(pubobj->location)); + + /* Flatten EXCEPT entries into the top-level list */ + foreach(lc, pubobj->except_tables) + { + PublicationObjSpec *eobj = (PublicationObjSpec *) lfirst(lc); + + /* + * If the table name is unqualified, implicitly qualify it with + * the parent schema. This is unambiguous because each EXCEPT + * clause is syntactically bound to exactly one schema. + */ + if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLES_IN_SCHEMA && + eobj->pubtable->relation->schemaname == NULL) + eobj->pubtable->relation->schemaname = pubobj->name; + } + pubobjspec_list = list_concat(pubobjspec_list, pubobj->except_tables); + pubobj->except_tables = NIL; } prevobjtype = pubobj->pubobjtype; diff --git a/src/backend/replication/pgoutput/pgoutput.c b/src/backend/replication/pgoutput/pgoutput.c index 4ecfcbff7ab..942ddb51d3a 100644 --- a/src/backend/replication/pgoutput/pgoutput.c +++ b/src/backend/replication/pgoutput/pgoutput.c @@ -2097,6 +2097,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) * are absorbed while decoding WAL. */ List *schemaPubids = GetSchemaPublications(schemaId); + List *schemaExceptPubids; ListCell *lc; Oid publish_as_relid = relid; int publish_ancestor_level = 0; @@ -2104,6 +2105,25 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) char relkind = get_rel_relkind(relid); List *rel_publications = NIL; + /* + * For the schema EXCEPT check, we must look up the top-most ancestor + * rather than the relation itself. check_publication_add_relation() + * prevents individual partitions from appearing in the EXCEPT clause, + * so only a root (non-partition) table can have prexcept = true. + * Using the partition's own OID would always return NIL and miss the + * exclusion. + */ + if (am_partition) + { + List *pancestore = get_partition_ancestors(relid); + + schemaExceptPubids = + GetRelationExcludedPublications(llast_oid(pancestore)); + list_free(pancestore); + } + else + schemaExceptPubids = GetRelationExcludedPublications(relid); + /* Reload publications if needed before use. */ if (!publications_valid) { @@ -2269,7 +2289,15 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) ancestors, &level); - if (ancestor != InvalidOid) + /* + * The ancestor is only considered published if it is not + * in the EXCEPT clause of this schema publication. + * GetTopMostAncestorInPublication checks schema + * membership but does not account for the EXCEPT list, so + * we must filter that out here. + */ + if (ancestor != InvalidOid && + !list_member_oid(schemaExceptPubids, pub->oid)) { ancestor_published = true; if (pub->pubviaroot) @@ -2281,7 +2309,8 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) } if (list_member_oid(pubids, pub->oid) || - list_member_oid(schemaPubids, pub->oid) || + (list_member_oid(schemaPubids, pub->oid) && + !list_member_oid(schemaExceptPubids, pub->oid)) || ancestor_published) publish = true; } @@ -2360,6 +2389,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) list_free(pubids); list_free(schemaPubids); + list_free(schemaExceptPubids); list_free(rel_publications); entry->replicate_valid = true; diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c index 1ca03d6b278..a1ca6edd80d 100644 --- a/src/bin/pg_dump/pg_dump.c +++ b/src/bin/pg_dump/pg_dump.c @@ -5019,6 +5019,7 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) PublicationInfo *pubinfo = pubsinfo->publication; PQExpBuffer query; char *tag; + bool first_except = true; /* Do nothing if not dumping schema */ if (!dopt->dumpSchema) @@ -5029,7 +5030,34 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) query = createPQExpBuffer(); appendPQExpBuffer(query, "ALTER PUBLICATION %s ", fmtId(pubinfo->dobj.name)); - appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s;\n", fmtId(schemainfo->dobj.name)); + appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s", fmtId(schemainfo->dobj.name)); + + /* + * Append EXCEPT clause for any tables that belong to this schema + * and are excluded from the publication. + */ + for (SimplePtrListCell *cell = pubinfo->except_tables.head; cell; cell = cell->next) + { + TableInfo *tbinfo = (TableInfo *) cell->ptr; + + if (strcmp(tbinfo->dobj.namespace->dobj.name, schemainfo->dobj.name) == 0) + { + if (first_except) + { + appendPQExpBufferStr(query, " EXCEPT ("); + first_except = false; + } + else + appendPQExpBufferStr(query, ", "); + + appendPQExpBuffer(query, "ONLY %s", fmtQualifiedDumpable(tbinfo)); + } + } + + if (!first_except) + appendPQExpBufferStr(query, ")"); + + appendPQExpBufferStr(query, ";\n"); /* * There is no point in creating drop query as the drop is done by schema diff --git a/src/bin/pg_dump/t/002_pg_dump.pl b/src/bin/pg_dump/t/002_pg_dump.pl index 3bc8e51561d..3391058a4c2 100644 --- a/src/bin/pg_dump/t/002_pg_dump.pl +++ b/src/bin/pg_dump/t/002_pg_dump.pl @@ -3242,6 +3242,42 @@ my %tests = ( like => { %full_runs, section_post_data => 1, }, }, + 'CREATE PUBLICATION pub11' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub11 FOR TABLES IN SCHEMA dump_test EXCEPT (dump_test.test_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub11 WITH (publish = 'insert, update, delete, truncate');\E + /xm, + like => { %full_runs, section_post_data => 1, }, + }, + + 'ALTER PUBLICATION pub11 ADD TABLES IN SCHEMA dump_test EXCEPT (dump_test.test_table)' + => { + regexp => qr/^ + \QALTER PUBLICATION pub11 ADD TABLES IN SCHEMA dump_test EXCEPT (ONLY dump_test.test_table);\E + /xm, + like => { %full_runs, section_post_data => 1, }, + }, + + 'CREATE PUBLICATION pub12' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub12 FOR TABLES IN SCHEMA dump_test EXCEPT (dump_test.test_table, dump_test.test_second_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub12 WITH (publish = 'insert, update, delete, truncate');\E + /xm, + like => { %full_runs, section_post_data => 1, }, + }, + + 'ALTER PUBLICATION pub12 ADD TABLES IN SCHEMA dump_test EXCEPT (dump_test.test_table, dump_test.test_second_table)' + => { + regexp => qr/^ + \QALTER PUBLICATION pub12 ADD TABLES IN SCHEMA dump_test EXCEPT (ONLY dump_test.test_table, ONLY dump_test.test_second_table);\E + /xm, + like => { %full_runs, section_post_data => 1, }, + }, + 'CREATE SUBSCRIPTION sub1' => { create_order => 50, create_sql => 'CREATE SUBSCRIPTION sub1 diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c index dd1179ef927..b751206e5a4 100644 --- a/src/bin/psql/describe.c +++ b/src/bin/psql/describe.c @@ -7038,6 +7038,24 @@ describePublications(const char *pattern) if (!addFooterToPublicationDesc(&buf, _("Tables from schemas:"), true, &cont)) goto error_return; + + if (pset.sversion >= 190000) + { + /* + * Get tables in the EXCEPT clause for this schema + * publication. + */ + printfPQExpBuffer(&buf, + "SELECT concat(c.relnamespace::regnamespace, '.', c.relname)\n" + "FROM pg_catalog.pg_class c\n" + " JOIN pg_catalog.pg_publication_rel pr ON c.oid = pr.prrelid\n" + "WHERE pr.prpubid = '%s'\n" + " AND pr.prexcept\n" + "ORDER BY 1", pubid); + if (!addFooterToPublicationDesc(&buf, _("Except tables:"), + true, &cont)) + goto error_return; + } } } else diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index 9990f818942..216cb599082 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -1064,6 +1064,15 @@ static const SchemaQuery Query_for_trigger_of_table = { "SELECT nspname FROM pg_catalog.pg_namespace "\ " WHERE nspname LIKE '%s'" +#define Query_for_list_of_tables_in_schema \ +"SELECT n.nspname || '.' || c.relname "\ +" FROM pg_catalog.pg_class c "\ +" JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "\ +" WHERE c.relkind IN (" CppAsString2(RELKIND_RELATION) ", " \ + CppAsString2(RELKIND_PARTITIONED_TABLE) ") "\ +" AND (n.nspname || '.' || c.relname) LIKE '%s' "\ +" AND n.nspname = '%s'" + /* Use COMPLETE_WITH_QUERY_VERBATIM with these queries for GUC names: */ #define Query_for_list_of_alter_system_set_vars \ "SELECT pg_catalog.lower(name) FROM pg_catalog.pg_settings "\ @@ -3784,8 +3793,32 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); - else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && (!ends_with(prev_wd, ','))) - COMPLETE_WITH("WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE", "WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + if (strchr(previous_words[3], ',') == NULL) + { + set_completion_reference(previous_words[3]); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + } + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && ends_with(prev_wd, ',')) + { + char *schema_word = previous_words[previous_words_count - 8]; + + if (strchr(schema_word, ',') == NULL) + { + set_completion_reference(schema_word); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + } + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* Complete "CREATE PUBLICATION <name> [...] WITH" */ else if (Matches("CREATE", "PUBLICATION", MatchAnyN, "WITH", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h index 91377a6cde3..a9177de0d43 100644 --- a/src/include/nodes/parsenodes.h +++ b/src/include/nodes/parsenodes.h @@ -4493,6 +4493,7 @@ typedef struct PublicationObjSpec PublicationObjSpecType pubobjtype; /* type of this publication object */ char *name; PublicationTable *pubtable; + List *except_tables; /* tables to exclude (for TABLES IN SCHEMA) */ ParseLoc location; /* token location, or -1 if unknown */ } PublicationObjSpec; diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index d028e9be866..1b1a6a333b0 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -461,7 +461,53 @@ HINT: Change the publication's EXCEPT clause using ALTER PUBLICATION ... SET AL RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + Publication testpub_schema_except1 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- Exclude multiple tables using unqualified names (implicitly qualified with the schema) +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + Publication testpub_schema_except2 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_nopk" + "pub_test.testpub_tbl_s1" + +-- fail: EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2 EXCEPT (TABLE pub_test.testpub_nopk); +ERROR: EXCEPT is not allowed for TABLE publication objects +LINE 2: FOR TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2 EXCEPT... + ^ +-- fail: EXCEPT table belongs to a different schema than the one listed +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to any schema listed in the publication +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2; CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; -- FOR ALL SEQUENCES diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 642e32fa098..ca7226be186 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -218,7 +218,36 @@ RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); + +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + +-- Exclude multiple tables using unqualified names (implicitly qualified with the schema) +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + +-- fail: EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2 EXCEPT (TABLE pub_test.testpub_nopk); + +-- fail: EXCEPT table belongs to a different schema than the one listed +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2; + CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 8c58d282eee..d2b1fb8f9ff 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -24,14 +24,16 @@ my $result; sub test_except_root_partition { - my ($pubviaroot) = @_; + my ($pubviaroot, $pubsql) = @_; + $pubsql //= + "CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1) WITH (publish_via_partition_root = $pubviaroot)"; # If the root partitioned table is in the EXCEPT clause, all its # partitions are excluded from publication, regardless of the # publish_via_partition_root setting. $node_publisher->safe_psql( 'postgres', qq( - CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1) WITH (publish_via_partition_root = $pubviaroot); + $pubsql; INSERT INTO root1 VALUES (1), (101); )); $node_subscriber->safe_psql('postgres', @@ -223,6 +225,138 @@ $node_subscriber->safe_psql( test_except_root_partition('false'); test_except_root_partition('true'); +# Same validation using TABLES IN SCHEMA instead of FOR ALL TABLES. +my $schema_pub = + "CREATE PUBLICATION tap_pub_part FOR TABLES IN SCHEMA public EXCEPT (TABLE public.root1)"; +test_except_root_partition('false', + "$schema_pub WITH (publish_via_partition_root = false)"); +test_except_root_partition('true', + "$schema_pub WITH (publish_via_partition_root = true)"); + +# ============================================ +# EXCEPT test cases for TABLES IN SCHEMA +# ============================================ + +# Create a dedicated schema with two tables: one to be published and one to be +# excluded. Also create inherited tables to verify ONLY semantics. +$node_publisher->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_pub AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.tab_exc AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.par (a int); + CREATE TABLE sch1.chi (b int) INHERITS (sch1.par); +)); + +$node_subscriber->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_pub (a int); + CREATE TABLE sch1.tab_exc (a int); + CREATE TABLE sch1.par (a int); + CREATE TABLE sch1.chi (b int) INHERITS (sch1.par); +)); + +# Basic test: initial sync respects EXCEPT. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_exc)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_pub"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: initial sync copies included table'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_exc"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: initial sync skips excluded table'); + +# DML: only the included table should be replicated. +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_pub VALUES (6); + INSERT INTO sch1.tab_exc VALUES (6); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_pub"); +is($result, qq(6), + 'TABLES IN SCHEMA EXCEPT: DML on included table is replicated'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_exc"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: DML on excluded table is not replicated'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Inherited tables: excluding the parent (without ONLY) also excludes the child. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.par)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.chi VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.chi"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: excluding parent (without ONLY) also excludes child' +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Truncate chi on the publisher so the next test starts with a clean slate. +# (The previous test inserted rows into chi that would otherwise be copied by +# the initial table sync of the next subscription.) +$node_publisher->safe_psql('postgres', 'TRUNCATE sch1.chi'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE sch1.chi'); +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE ONLY sch1.par)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.chi VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.chi"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: ONLY parent in EXCEPT does not exclude child' +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); +$node_publisher->safe_psql('postgres', + 'TRUNCATE sch1.par, sch1.chi, sch1.tab_exc'); +$node_subscriber->safe_psql('postgres', + 'TRUNCATE sch1.par, sch1.chi, sch1.tab_pub, sch1.tab_exc'); + +# Cleanup schema tables before the multi-publication section. +$node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); +$node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); + # ============================================ # Test when a subscription is subscribing to multiple publications # ============================================ @@ -254,6 +388,7 @@ $node_publisher->safe_psql( DROP PUBLICATION tap_pub2; TRUNCATE tab1; )); +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_subscriber->safe_psql('postgres', qq(TRUNCATE tab1)); # OK when a table is excluded by pub1 EXCEPT clause, but it is included by pub2 -- 2.50.1 (Apple Git-155)
v3-0002-Add-EXCEPT-support-to-ALTER-PUBLICATION-ADD-TABLE.patch (application/octet-stream, 16.9K) download From c84aab9b9993d9fe945db5b7ec64388cfc463edb Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Thu, 16 Apr 2026 14:55:06 +0530 Subject: [PATCH v3 2/3] Add EXCEPT support to ALTER PUBLICATION ADD TABLES IN SCHEMA Extend the EXCEPT clause support to allow tables to be excluded when adding a schema to a publication via ALTER PUBLICATION ... ADD: Syntax: ALTER PUBLICATION pub ADD TABLES IN SCHEMA s EXCEPT (TABLE s.t1); --- doc/src/sgml/ref/alter_publication.sgml | 42 +++++++- src/backend/commands/publicationcmds.c | 125 +++++++++++++++++++++- src/bin/psql/tab-complete.in.c | 28 +++++ src/test/regress/expected/publication.out | 19 +++- src/test/regress/sql/publication.sql | 11 +- src/test/subscription/t/037_except.pl | 28 +++++ 6 files changed, 249 insertions(+), 4 deletions(-) diff --git a/doc/src/sgml/ref/alter_publication.sgml b/doc/src/sgml/ref/alter_publication.sgml index aa32bb169e9..8aedfd951a5 100644 --- a/doc/src/sgml/ref/alter_publication.sgml +++ b/doc/src/sgml/ref/alter_publication.sgml @@ -31,7 +31,7 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -54,6 +54,10 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <phrase>and <replaceable class="parameter">table_object</replaceable> is:</phrase> [ ONLY ] <replaceable class="parameter">table_name</replaceable> [ * ] + +<phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> + + [ ONLY ] <replaceable class="parameter">table_name</replaceable> [ * ] </synopsis> </refsynopsisdiv> @@ -110,6 +114,15 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <literal>ADD TABLE</literal>. </para> + <para> + The <literal>EXCEPT</literal> clause can be used with + <literal>ADD TABLES IN SCHEMA</literal> to exclude specific tables from a + schema-level publication. <literal>EXCEPT</literal> is not supported with + <literal>DROP TABLES IN SCHEMA</literal>; instead, dropping a schema from + the publication automatically removes all of its associated + <literal>EXCEPT</literal> entries. + </para> + <para> The fourth variant of this command listed in the synopsis can change all of the publication properties specified in @@ -198,6 +211,23 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r </listitem> </varlistentry> + <varlistentry> + <term><literal>EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] )</literal></term> + <listitem> + <para> + Specifies tables to be excluded from a schema-level publication entry. + This clause may be used with <literal>ADD TABLES IN SCHEMA</literal> + and not with <literal>DROP TABLES IN SCHEMA</literal>. Each named + table must belong to the schema specified in the same + <literal>TABLES IN SCHEMA</literal> clause. Table names may be + schema-qualified or unqualified; unqualified names are implicitly + qualified with the schema named in the same clause. See + <xref linkend="sql-createpublication"/> for further details on the + semantics of <literal>EXCEPT</literal>. + </para> + </listitem> + </varlistentry> + <varlistentry> <term><literal>SET ( <replaceable class="parameter">publication_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] )</literal></term> <listitem> @@ -288,6 +318,16 @@ ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA marketing, sales; </programlisting> </para> + <para> + Add schema <structname>sales</structname> to the publication + <structname>sales_publication</structname>, excluding the + <structname>sales.internal</structname> and + <structname>sales.drafts</structname> tables: +<programlisting> +ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA sales EXCEPT (TABLE sales.internal, sales.drafts); +</programlisting> + </para> + <para> Add tables <structname>users</structname>, <structname>departments</structname> and schema diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 064e35accbb..b26706b5d1d 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -70,6 +70,9 @@ static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok); static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); +static void AlterPublicationExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, List *exceptrelations, + List *schemaidlist); static char defGetGeneratedColsOption(DefElem *def); @@ -1536,6 +1539,13 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, } PublicationAddSchemas(pubform->oid, schemaidlist, false, stmt); + + /* + * Increment the command counter so that is_schema_publication() in + * GetExcludedPublicationTables() can see the just-inserted schema + * rows when AlterPublicationExceptTables runs next. + */ + CommandCounterIncrement(); } else if (stmt->action == AP_DropObjects) PublicationDropSchemas(pubform->oid, schemaidlist, false); @@ -1561,6 +1571,112 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, * skip existing ones when doing catalog update. */ PublicationAddSchemas(pubform->oid, schemaidlist, true, stmt); + + /* + * Increment the command counter so that is_schema_publication() in + * GetExcludedPublicationTables() can see the just-inserted schema + * rows when AlterPublicationExceptTables runs next. + */ + CommandCounterIncrement(); + } +} + +/* + * Alter the EXCEPT list of a publication. + * + * Adds, removes, or replaces except-table entries in pg_publication_rel + * (rows with prexcept = true). These entries suppress publication of the + * named tables that would otherwise be covered by a FOR TABLES IN SCHEMA + * or FOR ALL TABLES clause. + */ +static void +AlterPublicationExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, List *exceptrelations, + List *schemaidlist) +{ + Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); + Oid pubid = pubform->oid; + + /* + * Nothing to do if no EXCEPT entries. + */ + if (!exceptrelations) + return; + + /* + * This function handles EXCEPT entries for schema-level publications + * only. For FOR ALL TABLES publications, EXCEPT entries are already + * processed by AlterPublicationTables(). + */ + if (schemaidlist == NIL && !is_schema_publication(pubid)) + return; + + /* + * EXCEPT is not meaningful with DROP: dropping a schema from a + * publication already removes all its except entries via cascade, and + * there is no sensible interpretation of "drop only the except entry but + * keep the schema". + */ + if (stmt->action == AP_DropObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); + + /* + * EXCEPT with SET is not supported: SET replaces the schema list but does + * not have a well-defined semantics for merging or replacing existing + * except entries. Users should DROP and re-ADD the schema with the + * desired EXCEPT list instead. + */ + if (stmt->action == AP_SetObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"))); + + if (stmt->action == AP_AddObjects) + { + List *rels; + List *explicitrelids; + List *pubschemaidlist; + ListCell *lc; + + rels = OpenTableList(exceptrelations); + + /* + * Build the effective schema list: schemas already in the publication + * plus any being added in this same command. The latter may not yet + * be visible via a catalog scan if CommandCounterIncrement has not + * been issued, so we include them explicitly. + */ + pubschemaidlist = GetPublicationSchemas(pubid); + pubschemaidlist = list_concat_unique_oid(pubschemaidlist, schemaidlist); + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + foreach(lc, rels) + { + PublicationRelInfo *pri = (PublicationRelInfo *) lfirst(lc); + Oid relid = RelationGetRelid(pri->relation); + Oid relns = RelationGetNamespace(pri->relation); + + if (!list_member_oid(pubschemaidlist, relns)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s.%s\" in EXCEPT clause does not belong to any schema listed in the publication", + get_namespace_name(relns), + RelationGetRelationName(pri->relation))); + + if (list_member_oid(explicitrelids, relid)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s.%s\" cannot appear in both the table list and the EXCEPT clause", + get_namespace_name(relns), + RelationGetRelationName(pri->relation))); + } + + PublicationAddTables(pubid, rels, false, stmt); + + CloseTableList(rels); } } @@ -1771,10 +1887,17 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) errmsg("publication \"%s\" does not exist", stmt->pubname)); - relations = list_concat(relations, exceptrelations); + /* + * For FOR ALL TABLES, EXCEPT entries are processed by + * AlterPublicationTables(), so merge them in. For TABLES IN SCHEMA, + * they are handled separately by AlterPublicationExceptTables(). + */ + if (stmt->for_all_tables) + relations = list_concat(relations, exceptrelations); AlterPublicationTables(stmt, tup, relations, pstate->p_sourcetext, schemaidlist != NIL); AlterPublicationSchemas(stmt, tup, schemaidlist); + AlterPublicationExceptTables(stmt, tup, exceptrelations, schemaidlist); AlterPublicationAllFlags(stmt, rel, tup); } diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index 216cb599082..4b6b48a31ce 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2363,6 +2363,34 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); + /* After a single schema name in ADD context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + if (strchr(previous_words[3], ',') == NULL) + { + set_completion_reference(previous_words[3]); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && ends_with(prev_wd, ',')) + { + char *schema_word = previous_words[previous_words_count - 8]; + + if (strchr(schema_word, ',') == NULL) + { + set_completion_reference(schema_word); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 1b1a6a333b0..700fdbfb292 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -505,9 +505,26 @@ LINE 2: FOR TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2 EXCEPT... CREATE PUBLICATION testpub_except_wrongschema FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to any schema listed in the publication + +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; +-- ADD: add a schema with an excepted table +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_alter_except; CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; -- FOR ALL SEQUENCES diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index ca7226be186..b509ba3b2f4 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -244,9 +244,18 @@ CREATE PUBLICATION testpub_except_err CREATE PUBLICATION testpub_except_wrongschema FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; + +-- ADD: add a schema with an excepted table +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_alter_except + RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_alter_except; CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index d2b1fb8f9ff..64f0e2173b2 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -353,6 +353,34 @@ $node_publisher->safe_psql('postgres', $node_subscriber->safe_psql('postgres', 'TRUNCATE sch1.par, sch1.chi, sch1.tab_pub, sch1.tab_exc'); +# ============================================ +# ALTER PUBLICATION EXCEPT for TABLES IN SCHEMA +# ============================================ + +# ADD: add a schema with an excepted table; verify the except entry takes effect. +$node_publisher->safe_psql('postgres', "CREATE PUBLICATION sch_pub"); +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub ADD TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_exc)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_pub"); +is($result, qq(6), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: included table synced'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_exc"); +is($result, qq(0), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + # Cleanup schema tables before the multi-publication section. $node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); $node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); -- 2.50.1 (Apple Git-155)
v3-0003-Add-EXCEPT-support-to-ALTER-PUBLICATION-SET-TABLE.patch (application/octet-stream, 21.6K) download From 4d62a7cc780bb4ae1600425eb2a0b8f5673f5342 Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Thu, 16 Apr 2026 15:44:10 +0530 Subject: [PATCH v3 3/3] Add EXCEPT support to ALTER PUBLICATION SET TABLES IN SCHEMA Extend AlterPublicationExceptTables() with the AP_SetObjects case, which redefine the publication and replaces the entire EXCEPT list. Syntax: ALTER PUBLICATION pub SET TABLES IN SCHEMA s EXCEPT (TABLE s.t1); --- doc/src/sgml/ref/alter_publication.sgml | 36 +++-- src/backend/catalog/pg_publication.c | 2 +- src/backend/commands/publicationcmds.c | 156 ++++++++++++++++++++-- src/bin/psql/tab-complete.in.c | 28 ++++ src/test/regress/expected/publication.out | 19 ++- src/test/regress/sql/publication.sql | 10 ++ src/test/subscription/t/037_except.pl | 90 +++++++++++++ 7 files changed, 314 insertions(+), 27 deletions(-) diff --git a/doc/src/sgml/ref/alter_publication.sgml b/doc/src/sgml/ref/alter_publication.sgml index 8aedfd951a5..1b73b34e43a 100644 --- a/doc/src/sgml/ref/alter_publication.sgml +++ b/doc/src/sgml/ref/alter_publication.sgml @@ -54,10 +54,6 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <phrase>and <replaceable class="parameter">table_object</replaceable> is:</phrase> [ ONLY ] <replaceable class="parameter">table_name</replaceable> [ * ] - -<phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> - - [ ONLY ] <replaceable class="parameter">table_name</replaceable> [ * ] </synopsis> </refsynopsisdiv> @@ -97,7 +93,11 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r used with a publication defined with <literal>FOR TABLE</literal> or <literal>FOR TABLES IN SCHEMA</literal>, replaces the list of tables/schemas in the publication with the specified list; the existing tables or schemas - that were present in the publication will be removed. + that were present in the publication will be removed. When + <literal>SET TABLES IN SCHEMA</literal> is used with an + <literal>EXCEPT</literal> clause, the excluded tables for each schema are + replaced with the specified list; if <literal>EXCEPT</literal> is omitted + for a schema, any existing exclusions for that schema are cleared. </para> <para> @@ -116,7 +116,8 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <para> The <literal>EXCEPT</literal> clause can be used with - <literal>ADD TABLES IN SCHEMA</literal> to exclude specific tables from a + <literal>ADD TABLES IN SCHEMA</literal> and + <literal>SET TABLES IN SCHEMA</literal> to exclude specific tables from a schema-level publication. <literal>EXCEPT</literal> is not supported with <literal>DROP TABLES IN SCHEMA</literal>; instead, dropping a schema from the publication automatically removes all of its associated @@ -217,12 +218,12 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <para> Specifies tables to be excluded from a schema-level publication entry. This clause may be used with <literal>ADD TABLES IN SCHEMA</literal> - and not with <literal>DROP TABLES IN SCHEMA</literal>. Each named - table must belong to the schema specified in the same - <literal>TABLES IN SCHEMA</literal> clause. Table names may be - schema-qualified or unqualified; unqualified names are implicitly - qualified with the schema named in the same clause. See - <xref linkend="sql-createpublication"/> for further details on the + and <literal>SET TABLES IN SCHEMA</literal>, and not with + <literal>DROP TABLES IN SCHEMA</literal>. Each named table must belong + to the schema specified in the same <literal>TABLES IN SCHEMA</literal> + clause. Table names may be schema-qualified or unqualified; unqualified + names are implicitly qualified with the schema named in the same clause. + See <xref linkend="sql-createpublication"/> for further details on the semantics of <literal>EXCEPT</literal>. </para> </listitem> @@ -328,6 +329,17 @@ ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA sales EXCEPT (TABLE sal </programlisting> </para> + <para> + Replace the schema list of <structname>sales_publication</structname> with + <structname>sales</structname>, excluding only + <structname>sales.drafts</structname> (any previously excluded tables for + that schema are replaced, and schemas previously in the publication are + removed): +<programlisting> +ALTER PUBLICATION sales_publication SET TABLES IN SCHEMA sales EXCEPT (TABLE sales.drafts); +</programlisting> + </para> + <para> Add tables <structname>users</structname>, <structname>departments</structname> and schema diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index 85c2528873f..e63f221f1af 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -1002,7 +1002,7 @@ GetIncludedPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) List * GetExcludedPublicationTables(Oid pubid, PublicationPartOpt pub_partopt) { - Assert(GetPublication(pubid)->alltables); + Assert(GetPublication(pubid)->alltables || is_schema_publication(pubid)); return get_publication_relations(pubid, pub_partopt, true); } diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index b26706b5d1d..de20233062b 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -1598,9 +1598,11 @@ AlterPublicationExceptTables(AlterPublicationStmt *stmt, Oid pubid = pubform->oid; /* - * Nothing to do if no EXCEPT entries. + * Nothing to do if no EXCEPT entries, except in SET: for that it is quite + * possible that the user has removed all exceptions, in which case we + * need to drop any existing ones. */ - if (!exceptrelations) + if (!exceptrelations && stmt->action != AP_SetObjects) return; /* @@ -1622,17 +1624,6 @@ AlterPublicationExceptTables(AlterPublicationStmt *stmt, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); - /* - * EXCEPT with SET is not supported: SET replaces the schema list but does - * not have a well-defined semantics for merging or replacing existing - * except entries. Users should DROP and re-ADD the schema with the - * desired EXCEPT list instead. - */ - if (stmt->action == AP_SetObjects) - ereport(ERROR, - (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"))); - if (stmt->action == AP_AddObjects) { List *rels; @@ -1676,6 +1667,106 @@ AlterPublicationExceptTables(AlterPublicationStmt *stmt, PublicationAddTables(pubid, rels, false, stmt); + CloseTableList(rels); + } + else /* AP_SetObjects */ + { + List *oldexceptrelids = NIL; + List *newexceptrelids = NIL; + List *delrelids = NIL; + List *rels; + List *explicitrelids; + List *pubschemaidlist; + ListCell *lc; + + rels = OpenTableList(exceptrelations); + + /* Collect OIDs of the desired new except list. */ + foreach(lc, rels) + { + PublicationRelInfo *pri = (PublicationRelInfo *) lfirst(lc); + + newexceptrelids = lappend_oid(newexceptrelids, + RelationGetRelid(pri->relation)); + } + + /* + * Build the effective schema list: schemas already in the publication + * plus any being set in this same command. The latter may not yet be + * visible via a catalog scan, so we include them explicitly. + */ + pubschemaidlist = GetPublicationSchemas(pubid); + pubschemaidlist = list_concat_unique_oid(pubschemaidlist, schemaidlist); + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + foreach(lc, rels) + { + PublicationRelInfo *pri = (PublicationRelInfo *) lfirst(lc); + Oid relid = RelationGetRelid(pri->relation); + Oid relns = RelationGetNamespace(pri->relation); + + if (!list_member_oid(pubschemaidlist, relns)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s.%s\" in EXCEPT clause does not belong to any schema listed in the publication", + get_namespace_name(relns), + RelationGetRelationName(pri->relation))); + + if (list_member_oid(explicitrelids, relid)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s.%s\" cannot appear in both the table list and the EXCEPT clause", + get_namespace_name(relns), + RelationGetRelationName(pri->relation))); + } + + /* + * Get the current set of except entries. Only FOR ALL TABLES and + * schema-level publications can have except entries; for any other + * publication type oldexceptrelids stays NIL. + * + * Note: we check is_schema_publication() against the current catalog + * state (before AlterPublicationSchemas has run), so if the caller is + * doing SET TABLE t1 to convert a schema publication into a plain + * table publication, is_schema_publication() still returns true here. + * That is intentional: it lets us discover and clean up any stale + * except entries that belong to the old schema definition. + */ + if (GetPublication(pubid)->alltables || is_schema_publication(pubid)) + oldexceptrelids = GetExcludedPublicationTables(pubid, + PUBLICATION_PART_ROOT); + + /* Build a list of old except entries not present in the new list. */ + foreach(lc, oldexceptrelids) + { + Oid oldrelid = lfirst_oid(lc); + + if (!list_member_oid(newexceptrelids, oldrelid)) + delrelids = lappend_oid(delrelids, oldrelid); + } + + /* Drop old except entries not present in the new list. */ + foreach(lc, delrelids) + { + Oid relid = lfirst_oid(lc); + Oid proid; + ObjectAddress obj; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (!OidIsValid(proid)) + continue; /* already gone */ + + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + + /* Add new except entries, skipping any already present. */ + PublicationAddTables(pubid, rels, true, stmt); + CloseTableList(rels); } } @@ -2330,6 +2421,8 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) foreach(lc, schemas) { Oid schemaid = lfirst_oid(lc); + List *exceptoids; + ListCell *elc; psid = GetSysCacheOid2(PUBLICATIONNAMESPACEMAP, Anum_pg_publication_namespace_oid, @@ -2346,8 +2439,45 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) get_namespace_name(schemaid)))); } + /* + * Collect prexcept rows for tables belonging to this schema before + * removing the schema entry. GetExcludedPublicationTables relies on + * is_schema_publication(), which scans pg_publication_namespace; if + * this is the last schema in the publication, performDeletion() below + * would remove that row and make is_schema_publication() return + * false, tripping the assertion. + */ + exceptoids = GetExcludedPublicationTables(pubid, PUBLICATION_PART_ROOT); + ObjectAddressSet(obj, PublicationNamespaceRelationId, psid); performDeletion(&obj, DROP_CASCADE, 0); + + /* + * Drop any prexcept rows for tables belonging to this schema. These + * rows have no pg_depend entry pointing at the + * pg_publication_namespace row, so they are not cascaded by the + * performDeletion() call above and must be cleaned up explicitly. + */ + foreach(elc, exceptoids) + { + Oid relid = lfirst_oid(elc); + Oid proid; + + if (get_rel_namespace(relid) != schemaid) + continue; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (!OidIsValid(proid)) + continue; /* already gone */ + + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + + list_free(exceptoids); } } diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index 4b6b48a31ce..ae092f761dd 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2391,6 +2391,34 @@ match_previous_words(int pattern_id, } else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) COMPLETE_WITH(")"); + /* After a single schema name in SET context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + if (strchr(previous_words[3], ',') == NULL) + { + set_completion_reference(previous_words[3]); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && ends_with(prev_wd, ',')) + { + char *schema_word = previous_words[previous_words_count - 8]; + + if (strchr(schema_word, ',') == NULL) + { + set_completion_reference(schema_word); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 700fdbfb292..cb51072cb72 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -505,7 +505,6 @@ LINE 2: FOR TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2 EXCEPT... CREATE PUBLICATION testpub_except_wrongschema FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to any schema listed in the publication - --------------------------------------------- -- EXCEPT tests for ALTER PUBLICATION --------------------------------------------- @@ -522,6 +521,24 @@ Tables from schemas: Except tables: "pub_test.testpub_tbl_s1" +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s2" + +-- error: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +ERROR: EXCEPT clause is not supported with DROP in ALTER PUBLICATION +-- error: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to any schema listed in the publication RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_alter_except; diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index b509ba3b2f4..5f23905da15 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -253,6 +253,16 @@ CREATE PUBLICATION testpub_alter_except; ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); \dRp+ testpub_alter_except +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + +-- error: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); + +-- error: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_alter_except; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 64f0e2173b2..580acd74bca 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -378,6 +378,66 @@ $result = is($result, qq(0), 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); +# SET: replace the except list; tab_exc is now included and tab_pub is excluded. +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_pub)" +); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_pub VALUES (7); + INSERT INTO sch1.tab_exc VALUES (7); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_exc"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: newly included table is replicated' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_pub"); +is($result, qq(6), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: now-excluded table is not replicated' +); + +# SET without EXCEPT: clears the except list; both tables are now published. +# tab_pub will be re-synced because REFRESH removed its entry when it was +# excluded. Truncate the subscriber copy beforehand so the re-sync produces +# a predictable count: publisher has 7 rows (6 original + INSERT(7)), so the +# subscriber ends up with 7 after re-sync, then 8 after INSERT(8). +$node_subscriber->safe_psql('postgres', 'TRUNCATE sch1.tab_pub'); +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1"); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_pub VALUES (8); + INSERT INTO sch1.tab_exc VALUES (8); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_pub"); +is($result, qq(8), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_pub replicated after except list cleared' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_exc"); +is($result, qq(2), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_exc replicated after except list cleared' +); + $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); @@ -445,6 +505,36 @@ $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); +# OK when a table is excluded by a TABLES IN SCHEMA EXCEPT publication, +# but is included by another publication. +$node_publisher->safe_psql('postgres', 'TRUNCATE tab1'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE tab1'); + +$node_publisher->safe_psql( + 'postgres', qq( + CREATE PUBLICATION tap_pub1 FOR TABLES IN SCHEMA public EXCEPT (TABLE public.tab1); + CREATE PUBLICATION tap_pub2 FOR TABLE tab1; + INSERT INTO tab1 VALUES(1); +)); +$node_subscriber->psql('postgres', + "CREATE SUBSCRIPTION tap_sub CONNECTION '$publisher_connstr' PUBLICATION tap_pub1, tap_pub2" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'tap_sub'); + +$node_publisher->safe_psql('postgres', qq(INSERT INTO tab1 VALUES(2))); +$node_publisher->wait_for_catchup('tap_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT * FROM tab1 ORDER BY a"); +is( $result, qq(1 +2), + "TABLES IN SCHEMA EXCEPT: table excluded in schema pub but included by another pub is replicated" +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); + $node_publisher->stop('fast'); done_testing(); -- 2.50.1 (Apple Git-155)
^ permalink raw reply [nested|flat] 196+ messages in thread

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-04-24 04:46  shveta malik <shveta.malik@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: shveta malik @ 2026-04-24 04:46 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>; shveta malik <shveta.malik@gmail.com>

On Thu, Apr 16, 2026 at 4:24 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
>
> On Wed, Apr 15, 2026 at 7:35 AM Peter Smith <smithpb2250@gmail.com> wrote:
> >
> > On Tue, Apr 14, 2026 at 7:37 PM Amit Kapila <amit.kapila16@gmail.com> wrote:
> > >
> > > On Tue, Apr 14, 2026 at 2:05 PM shveta malik <shveta.malik@gmail.com> wrote:
> > > >
> > > > On Tue, Apr 14, 2026 at 1:03 PM Peter Smith <smithpb2250@gmail.com> wrote:
> > > > >
> > > > > On Tue, Apr 14, 2026 at 4:30 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
> > > > > >
> > > > > > Hi hackers,
> > > > > >
> > > > > > Following earlier work to support EXCEPT for FOR ALL TABLES [1]
> > > > > > publications, starting this thread to extend the same capability to
> > > > > > schema-level publications (TABLES IN SCHEMA).
> > > > >
> > > > > Hi Nisha.
> > > > >
> > > > > +1 for adding this new kind of exclusion clause to CREATE PUBLICATION command.
> > > > >
> > > > > >
> > > > > > Currently, TABLES IN SCHEMA publishes all tables in a schema with no
> > > > > > way to exclude a subset. Users who want to skip a few tables must
> > > > > > switch to an explicit FOR TABLE list, which loses the convenience of
> > > > > > schema-level publishing and requires ongoing maintenance as tables are
> > > > > > added.
> > > > > >
> > > > > > Proposed syntax:
> > > > > > ------------------------
> > > > > > CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1 EXCEPT (s1.t1, s1.t2);
> > > > > > ALTER PUBLICATION pub ADD TABLES IN SCHEMA s1 EXCEPT (s1.t1);
> > > > > > ALTER PUBLICATION pub SET TABLES IN SCHEMA s1 EXCEPT (s1.t1);
> > > > > >
> > > > > > Note: Tables in the EXCEPT clause must be schema-qualified to avoid
> > > > > > ambiguity and must belong to the published schema; otherwise, an error
> > > > > > is raised.
> > > > > >
> > > > >
> > > > > The proposed syntax is almost, but not quite, what I was anticipating.
> > > > > IMO the syntax shouldn't just be similar to the FOR ALL TABLES EXCEPT;
> > > > > It can be *identical* to it. e.g., your examples are missing the
> > > > > 'TABLE' keyword necessary to achieve the same command flexibility.
> > > > > Furthermore, what is the ambiguity referred to? An excluded table is
> > > > > clearly associated with the preceding schema. Can't the code infer the
> > > > > schema internally even when it is not provided by the user? Of course,
> > > > > the user *can* specify a schema-qualified name if they want to, but I
> > > > > didn't see why we are forcing that rule upon them.
> > > >
> > > > +1. I also feel specifying only the table name is clear enough. Or are
> > > > we referring to implementation complexity here?
> > > >
> > >
> > > I think it will add complexity. Consider an example:
> > > CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1, s2, s3 EXCEPT (t1, t2);
> > >
> > > So, which schema's exclusion list will these tables should be
> > > considered for? Say, if table with name t1 is present in all schemas
> > > then shall we exclude from all schemas or just consider it excluded
> > > from the first one (s1)?
> > >
> >
> > The exact pattern is already in common usage for row-filters and
> > column-lists, yet nobody is confused.
> >
> > -- all these tables have the same column names
> > -- (analogous to multiple schemas having same table names)
> > CREATE TABLE t1(c1 int, c2 int);
> > CREATE TABLE t2(c1 int, c2 int);
> > CREATE TABLE t3(c1 int, c2 int);
> >
> > -- all tables have a column c1
> > -- but this c1 means t3.c1 because the column-list is only for the adjacent t3.
> > CREATE PUBLICATION pub1 FOR TABLE t1, t2, t3 (c1);
> >
> > -- all tables have a column c2
> > -- but this c2 means t3.c2 because the row-filter is only for the adjacent t3.
> > CREATE PUBLICATION pub2 FOR TABLE t1, t2, t3 WHERE (c2 > 99);
> >
> > \dRp+
> >                                                        Publication pub1
> >   Owner   | All tables | All sequences | Inserts | Updates | Deletes |
> > Truncates | Generated columns | Via root | Description
> > ----------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+-------------
> >  postgres | f          | f             | t       | t       | t       |
> > t         | none              | f        |
> > Tables:
> >     "public.t1"
> >     "public.t2"
> >     "public.t3" (c1)
> >
> >                                                        Publication pub2
> >   Owner   | All tables | All sequences | Inserts | Updates | Deletes |
> > Truncates | Generated columns | Via root | Description
> > ----------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+-------------
> >  postgres | f          | f             | t       | t       | t       |
> > t         | none              | f        |
> > Tables:
> >     "public.t1"
> >     "public.t2"
> >     "public.t3" WHERE (c2 > 99)
> >
>
> My intention was to avoid potential ambiguity when tables are not
> schema-qualified, as mentioned by Amit [1].
>
> That said, PostgreSQL generally does not enforce schema qualification
> and relies on search_path [2][3] for object resolution. Users are
> typically familiar with this behavior.
>
> Thanks for the example. I’ve updated the syntax to allow tables in the
> EXCEPT list without schema qualification.
> If a table is specified without a schema, it is resolved against the
> immediately preceding schema clause.
>
> Few examples:
> CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1, s2 EXCEPT (TABLE t1);
> -- table t1 is resolved in schema s2

Okay, looks good.

> CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1 EXCEPT (TABLE t1), s2
> EXCEPT (TABLE t2);
> -- if s1 does not contain t1, an error is raised: "s1.t1" does not exist

Okay, looks good.

>
> CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1, s2 EXCEPT (TABLE s1.t1, s2.t1);
> -- it will create the publication with except list - (s1.t1, s2.t1)

Okay, I thought we will not be supporting EXCEPT at the end and mixed
schemas inside. What will happen if I give:

CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1, s2 EXCEPT (TABLE t1, t2);

and t1, t2 are present in both the schemas?

I feel just like we associate column lists and row filters directly
with each table, rather than using a mixed style at the end; we should
also allow EXCEPT to be specified alongside each schema. This would
avoid added complexity and reduce potential confusion. Thoughts?

thanks
Shveta





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-04-24 05:59  shveta malik <shveta.malik@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: shveta malik @ 2026-04-24 05:59 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>; shveta malik <shveta.malik@gmail.com>

On Fri, Apr 24, 2026 at 10:16 AM shveta malik <shveta.malik@gmail.com> wrote:
>
> On Thu, Apr 16, 2026 at 4:24 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
> >
> > On Wed, Apr 15, 2026 at 7:35 AM Peter Smith <smithpb2250@gmail.com> wrote:
> > >
> > > On Tue, Apr 14, 2026 at 7:37 PM Amit Kapila <amit.kapila16@gmail.com> wrote:
> > > >
> > > > On Tue, Apr 14, 2026 at 2:05 PM shveta malik <shveta.malik@gmail.com> wrote:
> > > > >
> > > > > On Tue, Apr 14, 2026 at 1:03 PM Peter Smith <smithpb2250@gmail.com> wrote:
> > > > > >
> > > > > > On Tue, Apr 14, 2026 at 4:30 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
> > > > > > >
> > > > > > > Hi hackers,
> > > > > > >
> > > > > > > Following earlier work to support EXCEPT for FOR ALL TABLES [1]
> > > > > > > publications, starting this thread to extend the same capability to
> > > > > > > schema-level publications (TABLES IN SCHEMA).
> > > > > >
> > > > > > Hi Nisha.
> > > > > >
> > > > > > +1 for adding this new kind of exclusion clause to CREATE PUBLICATION command.
> > > > > >
> > > > > > >
> > > > > > > Currently, TABLES IN SCHEMA publishes all tables in a schema with no
> > > > > > > way to exclude a subset. Users who want to skip a few tables must
> > > > > > > switch to an explicit FOR TABLE list, which loses the convenience of
> > > > > > > schema-level publishing and requires ongoing maintenance as tables are
> > > > > > > added.
> > > > > > >
> > > > > > > Proposed syntax:
> > > > > > > ------------------------
> > > > > > > CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1 EXCEPT (s1.t1, s1.t2);
> > > > > > > ALTER PUBLICATION pub ADD TABLES IN SCHEMA s1 EXCEPT (s1.t1);
> > > > > > > ALTER PUBLICATION pub SET TABLES IN SCHEMA s1 EXCEPT (s1.t1);
> > > > > > >
> > > > > > > Note: Tables in the EXCEPT clause must be schema-qualified to avoid
> > > > > > > ambiguity and must belong to the published schema; otherwise, an error
> > > > > > > is raised.
> > > > > > >
> > > > > >
> > > > > > The proposed syntax is almost, but not quite, what I was anticipating.
> > > > > > IMO the syntax shouldn't just be similar to the FOR ALL TABLES EXCEPT;
> > > > > > It can be *identical* to it. e.g., your examples are missing the
> > > > > > 'TABLE' keyword necessary to achieve the same command flexibility.
> > > > > > Furthermore, what is the ambiguity referred to? An excluded table is
> > > > > > clearly associated with the preceding schema. Can't the code infer the
> > > > > > schema internally even when it is not provided by the user? Of course,
> > > > > > the user *can* specify a schema-qualified name if they want to, but I
> > > > > > didn't see why we are forcing that rule upon them.
> > > > >
> > > > > +1. I also feel specifying only the table name is clear enough. Or are
> > > > > we referring to implementation complexity here?
> > > > >
> > > >
> > > > I think it will add complexity. Consider an example:
> > > > CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1, s2, s3 EXCEPT (t1, t2);
> > > >
> > > > So, which schema's exclusion list will these tables should be
> > > > considered for? Say, if table with name t1 is present in all schemas
> > > > then shall we exclude from all schemas or just consider it excluded
> > > > from the first one (s1)?
> > > >
> > >
> > > The exact pattern is already in common usage for row-filters and
> > > column-lists, yet nobody is confused.
> > >
> > > -- all these tables have the same column names
> > > -- (analogous to multiple schemas having same table names)
> > > CREATE TABLE t1(c1 int, c2 int);
> > > CREATE TABLE t2(c1 int, c2 int);
> > > CREATE TABLE t3(c1 int, c2 int);
> > >
> > > -- all tables have a column c1
> > > -- but this c1 means t3.c1 because the column-list is only for the adjacent t3.
> > > CREATE PUBLICATION pub1 FOR TABLE t1, t2, t3 (c1);
> > >
> > > -- all tables have a column c2
> > > -- but this c2 means t3.c2 because the row-filter is only for the adjacent t3.
> > > CREATE PUBLICATION pub2 FOR TABLE t1, t2, t3 WHERE (c2 > 99);
> > >
> > > \dRp+
> > >                                                        Publication pub1
> > >   Owner   | All tables | All sequences | Inserts | Updates | Deletes |
> > > Truncates | Generated columns | Via root | Description
> > > ----------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+-------------
> > >  postgres | f          | f             | t       | t       | t       |
> > > t         | none              | f        |
> > > Tables:
> > >     "public.t1"
> > >     "public.t2"
> > >     "public.t3" (c1)
> > >
> > >                                                        Publication pub2
> > >   Owner   | All tables | All sequences | Inserts | Updates | Deletes |
> > > Truncates | Generated columns | Via root | Description
> > > ----------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+-------------
> > >  postgres | f          | f             | t       | t       | t       |
> > > t         | none              | f        |
> > > Tables:
> > >     "public.t1"
> > >     "public.t2"
> > >     "public.t3" WHERE (c2 > 99)
> > >
> >
> > My intention was to avoid potential ambiguity when tables are not
> > schema-qualified, as mentioned by Amit [1].
> >
> > That said, PostgreSQL generally does not enforce schema qualification
> > and relies on search_path [2][3] for object resolution. Users are
> > typically familiar with this behavior.
> >
> > Thanks for the example. I’ve updated the syntax to allow tables in the
> > EXCEPT list without schema qualification.
> > If a table is specified without a schema, it is resolved against the
> > immediately preceding schema clause.
> >
> > Few examples:
> > CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1, s2 EXCEPT (TABLE t1);
> > -- table t1 is resolved in schema s2
>
> Okay, looks good.
>
> > CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1 EXCEPT (TABLE t1), s2
> > EXCEPT (TABLE t2);
> > -- if s1 does not contain t1, an error is raised: "s1.t1" does not exist
>
> Okay, looks good.
>
> >
> > CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1, s2 EXCEPT (TABLE s1.t1, s2.t1);
> > -- it will create the publication with except list - (s1.t1, s2.t1)
>
> Okay, I thought we will not be supporting EXCEPT at the end and mixed
> schemas inside. What will happen if I give:
>
> CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1, s2 EXCEPT (TABLE t1, t2);
>
> and t1, t2 are present in both the schemas?
>
> I feel just like we associate column lists and row filters directly
> with each table, rather than using a mixed style at the end; we should
> also allow EXCEPT to be specified alongside each schema. This would
> avoid added complexity and reduce potential confusion. Thoughts?

One correction: I meant, we should "only"  allow EXCEPT to be
specified alongside each schema.

thanks
Shveta





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-04-27 03:32  Nisha Moond <nisha.moond412@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: Nisha Moond @ 2026-04-27 03:32 UTC (permalink / raw)
  To: shveta malik <shveta.malik@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Fri, Apr 24, 2026 at 11:29 AM shveta malik <shveta.malik@gmail.com> wrote:
>
> On Fri, Apr 24, 2026 at 10:16 AM shveta malik <shveta.malik@gmail.com> wrote:
> >
> > On Thu, Apr 16, 2026 at 4:24 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
> > >
> > > On Wed, Apr 15, 2026 at 7:35 AM Peter Smith <smithpb2250@gmail.com> wrote:
> > > >
> > > > On Tue, Apr 14, 2026 at 7:37 PM Amit Kapila <amit.kapila16@gmail.com> wrote:
> > > > >
> > > > > On Tue, Apr 14, 2026 at 2:05 PM shveta malik <shveta.malik@gmail.com> wrote:
> > > > > >
> > > > > > On Tue, Apr 14, 2026 at 1:03 PM Peter Smith <smithpb2250@gmail.com> wrote:
> > > > > > >
> > > > > > > On Tue, Apr 14, 2026 at 4:30 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
> > > > > > > >
> > > > > > > > Hi hackers,
> > > > > > > >
> > > > > > > > Following earlier work to support EXCEPT for FOR ALL TABLES [1]
> > > > > > > > publications, starting this thread to extend the same capability to
> > > > > > > > schema-level publications (TABLES IN SCHEMA).
> > > > > > >
> > > > > > > Hi Nisha.
> > > > > > >
> > > > > > > +1 for adding this new kind of exclusion clause to CREATE PUBLICATION command.
> > > > > > >
> > > > > > > >
> > > > > > > > Currently, TABLES IN SCHEMA publishes all tables in a schema with no
> > > > > > > > way to exclude a subset. Users who want to skip a few tables must
> > > > > > > > switch to an explicit FOR TABLE list, which loses the convenience of
> > > > > > > > schema-level publishing and requires ongoing maintenance as tables are
> > > > > > > > added.
> > > > > > > >
> > > > > > > > Proposed syntax:
> > > > > > > > ------------------------
> > > > > > > > CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1 EXCEPT (s1.t1, s1.t2);
> > > > > > > > ALTER PUBLICATION pub ADD TABLES IN SCHEMA s1 EXCEPT (s1.t1);
> > > > > > > > ALTER PUBLICATION pub SET TABLES IN SCHEMA s1 EXCEPT (s1.t1);
> > > > > > > >
> > > > > > > > Note: Tables in the EXCEPT clause must be schema-qualified to avoid
> > > > > > > > ambiguity and must belong to the published schema; otherwise, an error
> > > > > > > > is raised.
> > > > > > > >
> > > > > > >
> > > > > > > The proposed syntax is almost, but not quite, what I was anticipating.
> > > > > > > IMO the syntax shouldn't just be similar to the FOR ALL TABLES EXCEPT;
> > > > > > > It can be *identical* to it. e.g., your examples are missing the
> > > > > > > 'TABLE' keyword necessary to achieve the same command flexibility.
> > > > > > > Furthermore, what is the ambiguity referred to? An excluded table is
> > > > > > > clearly associated with the preceding schema. Can't the code infer the
> > > > > > > schema internally even when it is not provided by the user? Of course,
> > > > > > > the user *can* specify a schema-qualified name if they want to, but I
> > > > > > > didn't see why we are forcing that rule upon them.
> > > > > >
> > > > > > +1. I also feel specifying only the table name is clear enough. Or are
> > > > > > we referring to implementation complexity here?
> > > > > >
> > > > >
> > > > > I think it will add complexity. Consider an example:
> > > > > CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1, s2, s3 EXCEPT (t1, t2);
> > > > >
> > > > > So, which schema's exclusion list will these tables should be
> > > > > considered for? Say, if table with name t1 is present in all schemas
> > > > > then shall we exclude from all schemas or just consider it excluded
> > > > > from the first one (s1)?
> > > > >
> > > >
> > > > The exact pattern is already in common usage for row-filters and
> > > > column-lists, yet nobody is confused.
> > > >
> > > > -- all these tables have the same column names
> > > > -- (analogous to multiple schemas having same table names)
> > > > CREATE TABLE t1(c1 int, c2 int);
> > > > CREATE TABLE t2(c1 int, c2 int);
> > > > CREATE TABLE t3(c1 int, c2 int);
> > > >
> > > > -- all tables have a column c1
> > > > -- but this c1 means t3.c1 because the column-list is only for the adjacent t3.
> > > > CREATE PUBLICATION pub1 FOR TABLE t1, t2, t3 (c1);
> > > >
> > > > -- all tables have a column c2
> > > > -- but this c2 means t3.c2 because the row-filter is only for the adjacent t3.
> > > > CREATE PUBLICATION pub2 FOR TABLE t1, t2, t3 WHERE (c2 > 99);
> > > >
> > > > \dRp+
> > > >                                                        Publication pub1
> > > >   Owner   | All tables | All sequences | Inserts | Updates | Deletes |
> > > > Truncates | Generated columns | Via root | Description
> > > > ----------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+-------------
> > > >  postgres | f          | f             | t       | t       | t       |
> > > > t         | none              | f        |
> > > > Tables:
> > > >     "public.t1"
> > > >     "public.t2"
> > > >     "public.t3" (c1)
> > > >
> > > >                                                        Publication pub2
> > > >   Owner   | All tables | All sequences | Inserts | Updates | Deletes |
> > > > Truncates | Generated columns | Via root | Description
> > > > ----------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+-------------
> > > >  postgres | f          | f             | t       | t       | t       |
> > > > t         | none              | f        |
> > > > Tables:
> > > >     "public.t1"
> > > >     "public.t2"
> > > >     "public.t3" WHERE (c2 > 99)
> > > >
> > >
> > > My intention was to avoid potential ambiguity when tables are not
> > > schema-qualified, as mentioned by Amit [1].
> > >
> > > That said, PostgreSQL generally does not enforce schema qualification
> > > and relies on search_path [2][3] for object resolution. Users are
> > > typically familiar with this behavior.
> > >
> > > Thanks for the example. I’ve updated the syntax to allow tables in the
> > > EXCEPT list without schema qualification.
> > > If a table is specified without a schema, it is resolved against the
> > > immediately preceding schema clause.
> > >
> > > Few examples:
> > > CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1, s2 EXCEPT (TABLE t1);
> > > -- table t1 is resolved in schema s2
> >
> > Okay, looks good.
> >
> > > CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1 EXCEPT (TABLE t1), s2
> > > EXCEPT (TABLE t2);
> > > -- if s1 does not contain t1, an error is raised: "s1.t1" does not exist
> >
> > Okay, looks good.
> >
> > >
> > > CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1, s2 EXCEPT (TABLE s1.t1, s2.t1);
> > > -- it will create the publication with except list - (s1.t1, s2.t1)
> >
> > Okay, I thought we will not be supporting EXCEPT at the end and mixed
> > schemas inside. What will happen if I give:
> >
> > CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1, s2 EXCEPT (TABLE t1, t2);
> >
> > and t1, t2 are present in both the schemas?
> >

If no schema is specified, tables are resolved against the immediate
schema. In this case, s2.t1 and s2.t2 will be used in the EXCEPT list,
even if they exist in both s1 and s2.

> > I feel just like we associate column lists and row filters directly
> > with each table, rather than using a mixed style at the end; we should
> > also allow EXCEPT to be specified alongside each schema. This would
> > avoid added complexity and reduce potential confusion. Thoughts?
>
> One correction: I meant, we should "only"  allow EXCEPT to be
> specified alongside each schema.
>

I kept this for user convenience to specify the EXCEPT list in one go.
But as you mentioned, supporting mixed style adds complexity, as
currently, it checks tables against all schemas in the publication
(not just those in the command).

In further testing, I also noticed below confusing behavior due to
allowed mixed style -

CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1;
ALTER PUBLICATION pub ADD TABLES IN SCHEMA s2 EXCEPT (TABLE s1.t1);
 -- here, s1.t1 is allowed in EXCEPT because s1 is already part of the
publication, even though it’s not in the current command.

Let me make the changes to restrict the mixed style. Will share the
updated patch soon.

--
Thanks,
Nisha





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-04-27 03:36  shveta malik <shveta.malik@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: shveta malik @ 2026-04-27 03:36 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>; shveta malik <shveta.malik@gmail.com>

On Mon, Apr 27, 2026 at 9:02 AM Nisha Moond <nisha.moond412@gmail.com> wrote:
>
> On Fri, Apr 24, 2026 at 11:29 AM shveta malik <shveta.malik@gmail.com> wrote:
> >
> > On Fri, Apr 24, 2026 at 10:16 AM shveta malik <shveta.malik@gmail.com> wrote:
> > >
> > > On Thu, Apr 16, 2026 at 4:24 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
> > > >
> > > > On Wed, Apr 15, 2026 at 7:35 AM Peter Smith <smithpb2250@gmail.com> wrote:
> > > > >
> > > > > On Tue, Apr 14, 2026 at 7:37 PM Amit Kapila <amit.kapila16@gmail.com> wrote:
> > > > > >
> > > > > > On Tue, Apr 14, 2026 at 2:05 PM shveta malik <shveta.malik@gmail.com> wrote:
> > > > > > >
> > > > > > > On Tue, Apr 14, 2026 at 1:03 PM Peter Smith <smithpb2250@gmail.com> wrote:
> > > > > > > >
> > > > > > > > On Tue, Apr 14, 2026 at 4:30 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
> > > > > > > > >
> > > > > > > > > Hi hackers,
> > > > > > > > >
> > > > > > > > > Following earlier work to support EXCEPT for FOR ALL TABLES [1]
> > > > > > > > > publications, starting this thread to extend the same capability to
> > > > > > > > > schema-level publications (TABLES IN SCHEMA).
> > > > > > > >
> > > > > > > > Hi Nisha.
> > > > > > > >
> > > > > > > > +1 for adding this new kind of exclusion clause to CREATE PUBLICATION command.
> > > > > > > >
> > > > > > > > >
> > > > > > > > > Currently, TABLES IN SCHEMA publishes all tables in a schema with no
> > > > > > > > > way to exclude a subset. Users who want to skip a few tables must
> > > > > > > > > switch to an explicit FOR TABLE list, which loses the convenience of
> > > > > > > > > schema-level publishing and requires ongoing maintenance as tables are
> > > > > > > > > added.
> > > > > > > > >
> > > > > > > > > Proposed syntax:
> > > > > > > > > ------------------------
> > > > > > > > > CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1 EXCEPT (s1.t1, s1.t2);
> > > > > > > > > ALTER PUBLICATION pub ADD TABLES IN SCHEMA s1 EXCEPT (s1.t1);
> > > > > > > > > ALTER PUBLICATION pub SET TABLES IN SCHEMA s1 EXCEPT (s1.t1);
> > > > > > > > >
> > > > > > > > > Note: Tables in the EXCEPT clause must be schema-qualified to avoid
> > > > > > > > > ambiguity and must belong to the published schema; otherwise, an error
> > > > > > > > > is raised.
> > > > > > > > >
> > > > > > > >
> > > > > > > > The proposed syntax is almost, but not quite, what I was anticipating.
> > > > > > > > IMO the syntax shouldn't just be similar to the FOR ALL TABLES EXCEPT;
> > > > > > > > It can be *identical* to it. e.g., your examples are missing the
> > > > > > > > 'TABLE' keyword necessary to achieve the same command flexibility.
> > > > > > > > Furthermore, what is the ambiguity referred to? An excluded table is
> > > > > > > > clearly associated with the preceding schema. Can't the code infer the
> > > > > > > > schema internally even when it is not provided by the user? Of course,
> > > > > > > > the user *can* specify a schema-qualified name if they want to, but I
> > > > > > > > didn't see why we are forcing that rule upon them.
> > > > > > >
> > > > > > > +1. I also feel specifying only the table name is clear enough. Or are
> > > > > > > we referring to implementation complexity here?
> > > > > > >
> > > > > >
> > > > > > I think it will add complexity. Consider an example:
> > > > > > CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1, s2, s3 EXCEPT (t1, t2);
> > > > > >
> > > > > > So, which schema's exclusion list will these tables should be
> > > > > > considered for? Say, if table with name t1 is present in all schemas
> > > > > > then shall we exclude from all schemas or just consider it excluded
> > > > > > from the first one (s1)?
> > > > > >
> > > > >
> > > > > The exact pattern is already in common usage for row-filters and
> > > > > column-lists, yet nobody is confused.
> > > > >
> > > > > -- all these tables have the same column names
> > > > > -- (analogous to multiple schemas having same table names)
> > > > > CREATE TABLE t1(c1 int, c2 int);
> > > > > CREATE TABLE t2(c1 int, c2 int);
> > > > > CREATE TABLE t3(c1 int, c2 int);
> > > > >
> > > > > -- all tables have a column c1
> > > > > -- but this c1 means t3.c1 because the column-list is only for the adjacent t3.
> > > > > CREATE PUBLICATION pub1 FOR TABLE t1, t2, t3 (c1);
> > > > >
> > > > > -- all tables have a column c2
> > > > > -- but this c2 means t3.c2 because the row-filter is only for the adjacent t3.
> > > > > CREATE PUBLICATION pub2 FOR TABLE t1, t2, t3 WHERE (c2 > 99);
> > > > >
> > > > > \dRp+
> > > > >                                                        Publication pub1
> > > > >   Owner   | All tables | All sequences | Inserts | Updates | Deletes |
> > > > > Truncates | Generated columns | Via root | Description
> > > > > ----------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+-------------
> > > > >  postgres | f          | f             | t       | t       | t       |
> > > > > t         | none              | f        |
> > > > > Tables:
> > > > >     "public.t1"
> > > > >     "public.t2"
> > > > >     "public.t3" (c1)
> > > > >
> > > > >                                                        Publication pub2
> > > > >   Owner   | All tables | All sequences | Inserts | Updates | Deletes |
> > > > > Truncates | Generated columns | Via root | Description
> > > > > ----------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+-------------
> > > > >  postgres | f          | f             | t       | t       | t       |
> > > > > t         | none              | f        |
> > > > > Tables:
> > > > >     "public.t1"
> > > > >     "public.t2"
> > > > >     "public.t3" WHERE (c2 > 99)
> > > > >
> > > >
> > > > My intention was to avoid potential ambiguity when tables are not
> > > > schema-qualified, as mentioned by Amit [1].
> > > >
> > > > That said, PostgreSQL generally does not enforce schema qualification
> > > > and relies on search_path [2][3] for object resolution. Users are
> > > > typically familiar with this behavior.
> > > >
> > > > Thanks for the example. I’ve updated the syntax to allow tables in the
> > > > EXCEPT list without schema qualification.
> > > > If a table is specified without a schema, it is resolved against the
> > > > immediately preceding schema clause.
> > > >
> > > > Few examples:
> > > > CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1, s2 EXCEPT (TABLE t1);
> > > > -- table t1 is resolved in schema s2
> > >
> > > Okay, looks good.
> > >
> > > > CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1 EXCEPT (TABLE t1), s2
> > > > EXCEPT (TABLE t2);
> > > > -- if s1 does not contain t1, an error is raised: "s1.t1" does not exist
> > >
> > > Okay, looks good.
> > >
> > > >
> > > > CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1, s2 EXCEPT (TABLE s1.t1, s2.t1);
> > > > -- it will create the publication with except list - (s1.t1, s2.t1)
> > >
> > > Okay, I thought we will not be supporting EXCEPT at the end and mixed
> > > schemas inside. What will happen if I give:
> > >
> > > CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1, s2 EXCEPT (TABLE t1, t2);
> > >
> > > and t1, t2 are present in both the schemas?
> > >
>
> If no schema is specified, tables are resolved against the immediate
> schema. In this case, s2.t1 and s2.t2 will be used in the EXCEPT list,
> even if they exist in both s1 and s2.
>
> > > I feel just like we associate column lists and row filters directly
> > > with each table, rather than using a mixed style at the end; we should
> > > also allow EXCEPT to be specified alongside each schema. This would
> > > avoid added complexity and reduce potential confusion. Thoughts?
> >
> > One correction: I meant, we should "only"  allow EXCEPT to be
> > specified alongside each schema.
> >
>
> I kept this for user convenience to specify the EXCEPT list in one go.
> But as you mentioned, supporting mixed style adds complexity, as
> currently, it checks tables against all schemas in the publication
> (not just those in the command).
>
> In further testing, I also noticed below confusing behavior due to
> allowed mixed style -
>
> CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1;
> ALTER PUBLICATION pub ADD TABLES IN SCHEMA s2 EXCEPT (TABLE s1.t1);
>  -- here, s1.t1 is allowed in EXCEPT because s1 is already part of the
> publication, even though it’s not in the current command.

This case seems further confusing.

>
> Let me make the changes to restrict the mixed style. Will share the
> updated patch soon.
>

Yes, that will be better approach.

thanks
Shveta





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-04-27 09:02  Nisha Moond <nisha.moond412@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  0 siblings, 2 replies; 196+ messages in thread

From: Nisha Moond @ 2026-04-27 09:02 UTC (permalink / raw)
  To: shveta malik <shveta.malik@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Mon, Apr 27, 2026 at 9:06 AM shveta malik <shveta.malik@gmail.com> wrote:
>
> On Mon, Apr 27, 2026 at 9:02 AM Nisha Moond <nisha.moond412@gmail.com> wrote:
> >
> > On Fri, Apr 24, 2026 at 11:29 AM shveta malik <shveta.malik@gmail.com> wrote:
> > >
> > > > I feel just like we associate column lists and row filters directly
> > > > with each table, rather than using a mixed style at the end; we should
> > > > also allow EXCEPT to be specified alongside each schema. This would
> > > > avoid added complexity and reduce potential confusion. Thoughts?
> > >
> > > One correction: I meant, we should "only"  allow EXCEPT to be
> > > specified alongside each schema.
> > >
> >
> > I kept this for user convenience to specify the EXCEPT list in one go.
> > But as you mentioned, supporting mixed style adds complexity, as
> > currently, it checks tables against all schemas in the publication
> > (not just those in the command).
> >
> > In further testing, I also noticed below confusing behavior due to
> > allowed mixed style -
> >
> > CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1;
> > ALTER PUBLICATION pub ADD TABLES IN SCHEMA s2 EXCEPT (TABLE s1.t1);
> >  -- here, s1.t1 is allowed in EXCEPT because s1 is already part of the
> > publication, even though it’s not in the current command.
>
> This case seems further confusing.
>
> >
> > Let me make the changes to restrict the mixed style. Will share the
> > updated patch soon.
> >
>
> Yes, that will be better approach.
>

Please find the attached patches incorporating the above suggestion.
The EXCEPT clause now accepts tables only of its adjacent schema and
mixed style is not allowed.

Few examples :
CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1 EXCEPT (TABLE t1), s2
EXCEPT (TABLE t1);
 -- both s1.t1 and s2.t1 will be added in except list
CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1, s2 EXCEPT (TABLE s1.t1, s2.t1);
-- ERROR:  table "s1.t1" in EXCEPT clause does not belong to schema "s2"

--
Thanks,
Nisha

Attachments: download all (3 files, .tar.gz)

v4-0001-Support-EXCEPT-clause-for-schema-level-publicatio.patch (application/octet-stream, 40.3K) download From 2a37919a70af62e9b983abb2036623f0130c47cd Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Mon, 13 Apr 2026 17:49:44 +0530 Subject: [PATCH v4 1/3] Support EXCEPT clause for schema-level publications Extend table exclusion support in publications to allow specific tables to be excluded from schema-level publications using an EXCEPT clause in CREATE PUBLICATION. Supported syntax: CREATE PUBLICATION <pub> FOR TABLES IN SCHEMA s EXCEPT (TABLE t1,...); --- doc/src/sgml/logical-replication.sgml | 3 +- doc/src/sgml/ref/create_publication.sgml | 16 ++- src/backend/catalog/pg_publication.c | 107 ++++++++++++--- src/backend/commands/publicationcmds.c | 52 ++++++++ src/backend/parser/gram.y | 53 +++++++- src/backend/replication/pgoutput/pgoutput.c | 34 ++++- src/bin/pg_dump/pg_dump.c | 30 ++++- src/bin/pg_dump/t/002_pg_dump.pl | 36 +++++ src/bin/psql/describe.c | 18 +++ src/bin/psql/tab-complete.in.c | 37 +++++- src/include/nodes/parsenodes.h | 1 + src/test/regress/expected/publication.out | 56 +++++++- src/test/regress/sql/publication.sql | 35 ++++- src/test/subscription/t/037_except.pl | 139 +++++++++++++++++++- 14 files changed, 580 insertions(+), 37 deletions(-) diff --git a/doc/src/sgml/logical-replication.sgml b/doc/src/sgml/logical-replication.sgml index 9e7868487de..1433d2660fe 100644 --- a/doc/src/sgml/logical-replication.sgml +++ b/doc/src/sgml/logical-replication.sgml @@ -117,7 +117,8 @@ or <literal>FOR ALL SEQUENCES</literal>. Unlike tables, sequences can be synchronized at any time. For more information, see <xref linkend="logical-replication-sequences"/>. When a publication is - created with <literal>FOR ALL TABLES</literal>, a table or set of tables can + created with <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal>, a table or set of tables can be explicitly excluded from publication using the <link linkend="sql-createpublication-params-for-except-table"><literal>EXCEPT</literal></link> clause. diff --git a/doc/src/sgml/ref/create_publication.sgml b/doc/src/sgml/ref/create_publication.sgml index f82d640e6ca..b545a3ca21f 100644 --- a/doc/src/sgml/ref/create_publication.sgml +++ b/doc/src/sgml/ref/create_publication.sgml @@ -28,7 +28,7 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -142,6 +142,8 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <para> Marks the publication as one that replicates changes for all tables in the specified list of schemas, including tables created in the future. + Tables listed in <literal>EXCEPT</literal> for a given schema are + excluded from the publication. </para> <para> @@ -198,7 +200,8 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <listitem> <para> This clause specifies a list of tables to be excluded from the - publication. + publication. It can be used with both <literal>FOR ALL TABLES</literal> + and <literal>FOR TABLES IN SCHEMA</literal>. </para> <para> For inherited tables, if <literal>ONLY</literal> is specified before the @@ -515,6 +518,15 @@ CREATE PUBLICATION production_publication FOR TABLE users, departments, TABLES I CREATE PUBLICATION sales_publication FOR TABLES IN SCHEMA marketing, sales; </programlisting></para> + <para> + Create a publication that publishes all changes for all the tables present in + the schema <structname>sales</structname>, except + <structname>sales.internal</structname> and <structname>sales.drafts</structname>: +<programlisting> +CREATE PUBLICATION sales_filtered FOR TABLES IN SCHEMA sales EXCEPT (TABLE sales.internal, sales.drafts); +</programlisting> + </para> + <para> Create a publication that publishes all changes for table <structname>users</structname>, but replicates only columns <structname>user_id</structname> and diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index a43d385c605..85c2528873f 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -529,6 +529,7 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, referenced; List *relids = NIL; int i; + HeapTuple existing; bool inval_except_table; rel = table_open(PublicationRelRelationId, RowExclusiveLock); @@ -538,18 +539,33 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, * duplicates, it's here just to provide nicer error message in common * case. The real protection is the unique key on the catalog. */ - if (SearchSysCacheExists2(PUBLICATIONRELMAP, ObjectIdGetDatum(relid), - ObjectIdGetDatum(pubid))) + existing = SearchSysCache2(PUBLICATIONRELMAP, ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + + if (HeapTupleIsValid(existing)) { + Form_pg_publication_rel existing_form = + (Form_pg_publication_rel) GETSTRUCT(existing); + bool is_except = existing_form->prexcept; + + ReleaseSysCache(existing); table_close(rel, RowExclusiveLock); if (if_not_exists) return InvalidObjectAddress; - ereport(ERROR, - (errcode(ERRCODE_DUPLICATE_OBJECT), - errmsg("relation \"%s\" is already member of publication \"%s\"", - RelationGetRelationName(targetrel), pub->name))); + if (is_except) + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("table \"%s.%s\" cannot be added because it is listed in EXCEPT clause of publication \"%s\"", + get_namespace_name(RelationGetNamespace(targetrel)), + RelationGetRelationName(targetrel), + pub->name))); + else + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("relation \"%s\" is already member of publication \"%s\"", + RelationGetRelationName(targetrel), pub->name))); } check_publication_add_relation(pri); @@ -620,19 +636,24 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, /* * Determine whether EXCEPT tables require explicit relcache invalidation. * - * For CREATE PUBLICATION with EXCEPT tables, invalidation is skipped - * here, as CreatePublication() function invalidates all relations as part - * of defining a FOR ALL TABLES publication. + * For CREATE PUBLICATION with EXCEPT tables, invalidation is skipped here + * because the excluded tables were never included in the publication, so + * no subscriber cache entry needs to be cleared. + * + * For ALTER PUBLICATION, invalidation is needed when adding an EXCEPT + * table to either: - a FOR ALL TABLES publication (pub->alltables is + * true), or - a FOR TABLES IN SCHEMA publication (is_schema_publication + * is true). * - * For ALTER PUBLICATION, invalidation is needed only when adding an - * EXCEPT table to a publication already marked as ALL TABLES. For - * publications that were originally empty or defined as ALL SEQUENCES and - * are being converted to ALL TABLES, invalidation is skipped here, as - * AlterPublicationAllFlags() function invalidates all relations while - * marking the publication as ALL TABLES publication. + * The exception: when a publication is being converted to FOR ALL TABLES + * (pub->alltables is still false at this point), + * AlterPublicationAllFlags() will perform a full invalidation, so we skip + * it here. */ - inval_except_table = (alter_stmt != NULL) && pub->alltables && - (alter_stmt->for_all_tables && pri->except); + inval_except_table = (alter_stmt != NULL) && pri->except && + (pub->alltables + ? alter_stmt->for_all_tables + : is_schema_publication(pubid)); if (!pri->except || inval_except_table) { @@ -975,7 +996,8 @@ GetIncludedPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) * Gets list of table oids that were specified in the EXCEPT clause for a * publication. * - * This should only be used FOR ALL TABLES publications. + * This is used for FOR ALL TABLES and FOR TABLES IN SCHEMA publications, + * both of which support EXCEPT TABLE. */ List * GetExcludedPublicationTables(Oid pubid, PublicationPartOpt pub_partopt) @@ -1225,22 +1247,67 @@ GetSchemaPublicationRelations(Oid schemaid, PublicationPartOpt pub_partopt) /* * Gets the list of all relations published by FOR TABLES IN SCHEMA - * publication. + * publication, excluding any tables listed in the EXCEPT clause. */ List * GetAllSchemaPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) { List *result = NIL; List *pubschemalist = GetPublicationSchemas(pubid); + List *exceptlist = NIL; ListCell *cell; + /* get the list of tables excluded via EXCEPT TABLE for this publication */ + if (pubschemalist != NIL) + exceptlist = get_publication_relations(pubid, pub_partopt, true); + foreach(cell, pubschemalist) { Oid schemaid = lfirst_oid(cell); List *schemaRels = NIL; schemaRels = GetSchemaPublicationRelations(schemaid, pub_partopt); - result = list_concat(result, schemaRels); + + if (exceptlist != NIL) + { + /* filter out any tables that appear in the EXCEPT list */ + ListCell *rlc; + + foreach(rlc, schemaRels) + { + Oid relid = lfirst_oid(rlc); + bool excluded = list_member_oid(exceptlist, relid); + + /* + * Also exclude any relation whose partition ancestor is in + * the EXCEPT list. This matters when pub_partopt is + * PUBLICATION_PART_ROOT: the except list holds only the root + * OID, but the schema scan may also return individual + * partition relations that live in the same schema. + */ + if (!excluded && get_rel_relispartition(relid)) + { + List *ancestors = get_partition_ancestors(relid); + ListCell *alc; + + foreach(alc, ancestors) + { + if (list_member_oid(exceptlist, lfirst_oid(alc))) + { + excluded = true; + break; + } + } + list_free(ancestors); + } + + if (!excluded) + result = lappend_oid(result, relid); + } + list_free(schemaRels); + } + else + result = list_concat(result, schemaRels); } return result; diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 440adb356ad..dfe3e1f9706 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -959,6 +959,8 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) } else if (!stmt->for_all_sequences) { + List *explicitrelids = NIL; + /* FOR TABLES IN SCHEMA requires superuser */ if (schemaidlist != NIL && !superuser()) ereport(ERROR, @@ -968,6 +970,7 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) if (relations != NIL) { List *rels; + ListCell *lc; rels = OpenTableList(relations); TransformPubWhereClauses(rels, pstate->p_sourcetext, @@ -977,6 +980,23 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) schemaidlist != NIL, publish_via_partition_root); + /* + * Collect explicit table OIDs now, before we close the relation + * list, so that except-table validation below can check for + * contradictions without relying on a catalog scan that might not + * yet see the just-inserted rows. + */ + if (exceptrelations != NIL) + { + foreach(lc, rels) + { + PublicationRelInfo *pri = (PublicationRelInfo *) lfirst(lc); + + explicitrelids = lappend_oid(explicitrelids, + RelationGetRelid(pri->relation)); + } + } + PublicationAddTables(puboid, rels, true, NULL); CloseTableList(rels); } @@ -989,6 +1009,38 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) */ LockSchemaList(schemaidlist); PublicationAddSchemas(puboid, schemaidlist, true, NULL); + + if (exceptrelations != NIL) + { + List *rels; + ListCell *lc; + + rels = OpenTableList(exceptrelations); + + /* + * Validate that each excluded table is not also in the + * explicit table list (which would be contradictory). Use + * the in-memory explicitrelids collected above rather than + * re-reading the catalog, which may not yet see the + * just-inserted rows. + */ + foreach(lc, rels) + { + PublicationRelInfo *pri = (PublicationRelInfo *) lfirst(lc); + Oid relid = RelationGetRelid(pri->relation); + Oid relns = RelationGetNamespace(pri->relation); + + if (list_member_oid(explicitrelids, relid)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s.%s\" cannot appear in both the table list and the EXCEPT clause", + get_namespace_name(relns), + RelationGetRelationName(pri->relation))); + } + + PublicationAddTables(puboid, rels, true, NULL); + CloseTableList(rels); + } } } diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y index ff4e1388c55..cd8d0453521 100644 --- a/src/backend/parser/gram.y +++ b/src/backend/parser/gram.y @@ -11272,7 +11272,7 @@ AlterOwnerStmt: ALTER AGGREGATE aggregate_with_argtypes OWNER TO RoleSpec * pub_obj is one of: * * TABLE table [, ...] - * TABLES IN SCHEMA schema [, ...] + * TABLES IN SCHEMA schema [EXCEPT ( table [, ...] )] [, ...] * *****************************************************************************/ @@ -11332,23 +11332,26 @@ PublicationObjSpec: $$->pubtable->columns = $3; $$->pubtable->whereClause = $4; } - | TABLES IN_P SCHEMA ColId + | TABLES IN_P SCHEMA ColId opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_SCHEMA; $$->name = $4; + $$->except_tables = $5; $$->location = @4; } - | TABLES IN_P SCHEMA CURRENT_SCHEMA + | TABLES IN_P SCHEMA CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_CUR_SCHEMA; + $$->except_tables = $5; $$->location = @4; } - | ColId opt_column_list OptWhereClause + | ColId opt_column_list OptWhereClause opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $4; /* * If either a row filter or column list is specified, create * a PublicationTable object. @@ -11392,10 +11395,11 @@ PublicationObjSpec: $$->pubtable->columns = $2; $$->pubtable->whereClause = $3; } - | CURRENT_SCHEMA + | CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $2; $$->location = @1; } ; @@ -20784,11 +20788,14 @@ preprocess_pub_all_objtype_list(List *all_objects_list, List **pubobjects, /* * Process pubobjspec_list to check for errors in any of the objects and * convert PUBLICATIONOBJ_CONTINUATION into appropriate PublicationObjSpecType. + * Also flattens except_tables from TABLES IN SCHEMA nodes into the list so + * that ObjectsInPublicationToOids() sees them as top-level EXCEPT_TABLE entries. */ static void preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) { ListCell *cell; + ListCell *lc; PublicationObjSpec *pubobj; PublicationObjSpecType prevobjtype = PUBLICATIONOBJ_CONTINUATION; @@ -20812,6 +20819,13 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLE) { + /* EXCEPT is not valid for table objects */ + if (pubobj->except_tables != NIL) + ereport(ERROR, + errcode(ERRCODE_SYNTAX_ERROR), + errmsg("EXCEPT is not allowed for TABLE publication objects"), + parser_errposition(pubobj->location)); + /* relation name or pubtable must be set for this type of object */ if (!pubobj->name && !pubobj->pubtable) ereport(ERROR, @@ -20860,6 +20874,35 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) errcode(ERRCODE_SYNTAX_ERROR), errmsg("invalid schema name"), parser_errposition(pubobj->location)); + + /* Flatten EXCEPT entries into the top-level list */ + foreach(lc, pubobj->except_tables) + { + PublicationObjSpec *eobj = (PublicationObjSpec *) lfirst(lc); + + /* + * Unqualified names are implicitly qualified with the parent + * schema. Qualified names must match the parent schema — + * each EXCEPT clause is bound to exactly one schema, so + * cross-schema entries are rejected at parse time. + */ + if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLES_IN_SCHEMA) + { + if (eobj->pubtable->relation->schemaname == NULL) + eobj->pubtable->relation->schemaname = pubobj->name; + else if (strcmp(eobj->pubtable->relation->schemaname, + pubobj->name) != 0) + ereport(ERROR, + errcode(ERRCODE_SYNTAX_ERROR), + errmsg("table \"%s.%s\" in EXCEPT clause does not belong to schema \"%s\"", + eobj->pubtable->relation->schemaname, + eobj->pubtable->relation->relname, + pubobj->name), + parser_errposition(eobj->location)); + } + } + pubobjspec_list = list_concat(pubobjspec_list, pubobj->except_tables); + pubobj->except_tables = NIL; } prevobjtype = pubobj->pubobjtype; diff --git a/src/backend/replication/pgoutput/pgoutput.c b/src/backend/replication/pgoutput/pgoutput.c index 4ecfcbff7ab..942ddb51d3a 100644 --- a/src/backend/replication/pgoutput/pgoutput.c +++ b/src/backend/replication/pgoutput/pgoutput.c @@ -2097,6 +2097,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) * are absorbed while decoding WAL. */ List *schemaPubids = GetSchemaPublications(schemaId); + List *schemaExceptPubids; ListCell *lc; Oid publish_as_relid = relid; int publish_ancestor_level = 0; @@ -2104,6 +2105,25 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) char relkind = get_rel_relkind(relid); List *rel_publications = NIL; + /* + * For the schema EXCEPT check, we must look up the top-most ancestor + * rather than the relation itself. check_publication_add_relation() + * prevents individual partitions from appearing in the EXCEPT clause, + * so only a root (non-partition) table can have prexcept = true. + * Using the partition's own OID would always return NIL and miss the + * exclusion. + */ + if (am_partition) + { + List *pancestore = get_partition_ancestors(relid); + + schemaExceptPubids = + GetRelationExcludedPublications(llast_oid(pancestore)); + list_free(pancestore); + } + else + schemaExceptPubids = GetRelationExcludedPublications(relid); + /* Reload publications if needed before use. */ if (!publications_valid) { @@ -2269,7 +2289,15 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) ancestors, &level); - if (ancestor != InvalidOid) + /* + * The ancestor is only considered published if it is not + * in the EXCEPT clause of this schema publication. + * GetTopMostAncestorInPublication checks schema + * membership but does not account for the EXCEPT list, so + * we must filter that out here. + */ + if (ancestor != InvalidOid && + !list_member_oid(schemaExceptPubids, pub->oid)) { ancestor_published = true; if (pub->pubviaroot) @@ -2281,7 +2309,8 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) } if (list_member_oid(pubids, pub->oid) || - list_member_oid(schemaPubids, pub->oid) || + (list_member_oid(schemaPubids, pub->oid) && + !list_member_oid(schemaExceptPubids, pub->oid)) || ancestor_published) publish = true; } @@ -2360,6 +2389,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) list_free(pubids); list_free(schemaPubids); + list_free(schemaExceptPubids); list_free(rel_publications); entry->replicate_valid = true; diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c index d56dcc701ce..f63e950a136 100644 --- a/src/bin/pg_dump/pg_dump.c +++ b/src/bin/pg_dump/pg_dump.c @@ -5019,6 +5019,7 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) PublicationInfo *pubinfo = pubsinfo->publication; PQExpBuffer query; char *tag; + bool first_except = true; /* Do nothing if not dumping schema */ if (!dopt->dumpSchema) @@ -5029,7 +5030,34 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) query = createPQExpBuffer(); appendPQExpBuffer(query, "ALTER PUBLICATION %s ", fmtId(pubinfo->dobj.name)); - appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s;\n", fmtId(schemainfo->dobj.name)); + appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s", fmtId(schemainfo->dobj.name)); + + /* + * Append EXCEPT clause for any tables that belong to this schema + * and are excluded from the publication. + */ + for (SimplePtrListCell *cell = pubinfo->except_tables.head; cell; cell = cell->next) + { + TableInfo *tbinfo = (TableInfo *) cell->ptr; + + if (strcmp(tbinfo->dobj.namespace->dobj.name, schemainfo->dobj.name) == 0) + { + if (first_except) + { + appendPQExpBufferStr(query, " EXCEPT ("); + first_except = false; + } + else + appendPQExpBufferStr(query, ", "); + + appendPQExpBuffer(query, "ONLY %s", fmtQualifiedDumpable(tbinfo)); + } + } + + if (!first_except) + appendPQExpBufferStr(query, ")"); + + appendPQExpBufferStr(query, ";\n"); /* * There is no point in creating drop query as the drop is done by schema diff --git a/src/bin/pg_dump/t/002_pg_dump.pl b/src/bin/pg_dump/t/002_pg_dump.pl index 3bc8e51561d..3391058a4c2 100644 --- a/src/bin/pg_dump/t/002_pg_dump.pl +++ b/src/bin/pg_dump/t/002_pg_dump.pl @@ -3242,6 +3242,42 @@ my %tests = ( like => { %full_runs, section_post_data => 1, }, }, + 'CREATE PUBLICATION pub11' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub11 FOR TABLES IN SCHEMA dump_test EXCEPT (dump_test.test_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub11 WITH (publish = 'insert, update, delete, truncate');\E + /xm, + like => { %full_runs, section_post_data => 1, }, + }, + + 'ALTER PUBLICATION pub11 ADD TABLES IN SCHEMA dump_test EXCEPT (dump_test.test_table)' + => { + regexp => qr/^ + \QALTER PUBLICATION pub11 ADD TABLES IN SCHEMA dump_test EXCEPT (ONLY dump_test.test_table);\E + /xm, + like => { %full_runs, section_post_data => 1, }, + }, + + 'CREATE PUBLICATION pub12' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub12 FOR TABLES IN SCHEMA dump_test EXCEPT (dump_test.test_table, dump_test.test_second_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub12 WITH (publish = 'insert, update, delete, truncate');\E + /xm, + like => { %full_runs, section_post_data => 1, }, + }, + + 'ALTER PUBLICATION pub12 ADD TABLES IN SCHEMA dump_test EXCEPT (dump_test.test_table, dump_test.test_second_table)' + => { + regexp => qr/^ + \QALTER PUBLICATION pub12 ADD TABLES IN SCHEMA dump_test EXCEPT (ONLY dump_test.test_table, ONLY dump_test.test_second_table);\E + /xm, + like => { %full_runs, section_post_data => 1, }, + }, + 'CREATE SUBSCRIPTION sub1' => { create_order => 50, create_sql => 'CREATE SUBSCRIPTION sub1 diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c index e1449654f96..e5b1a70e05e 100644 --- a/src/bin/psql/describe.c +++ b/src/bin/psql/describe.c @@ -7038,6 +7038,24 @@ describePublications(const char *pattern) if (!addFooterToPublicationDesc(&buf, _("Tables from schemas:"), true, &cont)) goto error_return; + + if (pset.sversion >= 190000) + { + /* + * Get tables in the EXCEPT clause for this schema + * publication. + */ + printfPQExpBuffer(&buf, + "SELECT concat(c.relnamespace::regnamespace, '.', c.relname)\n" + "FROM pg_catalog.pg_class c\n" + " JOIN pg_catalog.pg_publication_rel pr ON c.oid = pr.prrelid\n" + "WHERE pr.prpubid = '%s'\n" + " AND pr.prexcept\n" + "ORDER BY 1", pubid); + if (!addFooterToPublicationDesc(&buf, _("Except tables:"), + true, &cont)) + goto error_return; + } } } else diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index db65d130fcb..6c9c7552627 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -1064,6 +1064,15 @@ static const SchemaQuery Query_for_trigger_of_table = { "SELECT nspname FROM pg_catalog.pg_namespace "\ " WHERE nspname LIKE '%s'" +#define Query_for_list_of_tables_in_schema \ +"SELECT n.nspname || '.' || c.relname "\ +" FROM pg_catalog.pg_class c "\ +" JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "\ +" WHERE c.relkind IN (" CppAsString2(RELKIND_RELATION) ", " \ + CppAsString2(RELKIND_PARTITIONED_TABLE) ") "\ +" AND (n.nspname || '.' || c.relname) LIKE '%s' "\ +" AND n.nspname = '%s'" + /* Use COMPLETE_WITH_QUERY_VERBATIM with these queries for GUC names: */ #define Query_for_list_of_alter_system_set_vars \ "SELECT pg_catalog.lower(name) FROM pg_catalog.pg_settings "\ @@ -3784,8 +3793,32 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); - else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && (!ends_with(prev_wd, ','))) - COMPLETE_WITH("WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE", "WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + if (strchr(previous_words[3], ',') == NULL) + { + set_completion_reference(previous_words[3]); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + } + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && ends_with(prev_wd, ',')) + { + char *schema_word = previous_words[previous_words_count - 8]; + + if (strchr(schema_word, ',') == NULL) + { + set_completion_reference(schema_word); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + } + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* Complete "CREATE PUBLICATION <name> [...] WITH" */ else if (Matches("CREATE", "PUBLICATION", MatchAnyN, "WITH", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h index 91377a6cde3..a9177de0d43 100644 --- a/src/include/nodes/parsenodes.h +++ b/src/include/nodes/parsenodes.h @@ -4493,6 +4493,7 @@ typedef struct PublicationObjSpec PublicationObjSpecType pubobjtype; /* type of this publication object */ char *name; PublicationTable *pubtable; + List *except_tables; /* tables to exclude (for TABLES IN SCHEMA) */ ParseLoc location; /* token location, or -1 if unknown */ } PublicationObjSpec; diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 0345f6c5e47..e78192edd01 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -470,7 +470,61 @@ HINT: Change the publication's EXCEPT clause using ALTER PUBLICATION ... SET AL RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + Publication testpub_schema_except1 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- Exclude multiple tables using unqualified names (implicitly qualified with the schema) +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + Publication testpub_schema_except2 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_nopk" + "pub_test.testpub_tbl_s1" + +-- fail: EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2 EXCEPT (TABLE pub_test.testpub_nopk); +ERROR: EXCEPT is not allowed for TABLE publication objects +LINE 2: FOR TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2 EXCEPT... + ^ +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testp... + ^ +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); +ERROR: table "pub_test.testpub_tbl_s1" in EXCEPT clause does not belong to schema "public" +LINE 2: ...R TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.t... + ^ +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2; CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; -- FOR ALL SEQUENCES diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 041e14a4de6..9120902dfac 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -220,7 +220,40 @@ RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); + +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + +-- Exclude multiple tables using unqualified names (implicitly qualified with the schema) +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + +-- fail: EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2 EXCEPT (TABLE pub_test.testpub_nopk); + +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); + +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2; + CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 8c58d282eee..d2b1fb8f9ff 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -24,14 +24,16 @@ my $result; sub test_except_root_partition { - my ($pubviaroot) = @_; + my ($pubviaroot, $pubsql) = @_; + $pubsql //= + "CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1) WITH (publish_via_partition_root = $pubviaroot)"; # If the root partitioned table is in the EXCEPT clause, all its # partitions are excluded from publication, regardless of the # publish_via_partition_root setting. $node_publisher->safe_psql( 'postgres', qq( - CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1) WITH (publish_via_partition_root = $pubviaroot); + $pubsql; INSERT INTO root1 VALUES (1), (101); )); $node_subscriber->safe_psql('postgres', @@ -223,6 +225,138 @@ $node_subscriber->safe_psql( test_except_root_partition('false'); test_except_root_partition('true'); +# Same validation using TABLES IN SCHEMA instead of FOR ALL TABLES. +my $schema_pub = + "CREATE PUBLICATION tap_pub_part FOR TABLES IN SCHEMA public EXCEPT (TABLE public.root1)"; +test_except_root_partition('false', + "$schema_pub WITH (publish_via_partition_root = false)"); +test_except_root_partition('true', + "$schema_pub WITH (publish_via_partition_root = true)"); + +# ============================================ +# EXCEPT test cases for TABLES IN SCHEMA +# ============================================ + +# Create a dedicated schema with two tables: one to be published and one to be +# excluded. Also create inherited tables to verify ONLY semantics. +$node_publisher->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_pub AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.tab_exc AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.par (a int); + CREATE TABLE sch1.chi (b int) INHERITS (sch1.par); +)); + +$node_subscriber->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_pub (a int); + CREATE TABLE sch1.tab_exc (a int); + CREATE TABLE sch1.par (a int); + CREATE TABLE sch1.chi (b int) INHERITS (sch1.par); +)); + +# Basic test: initial sync respects EXCEPT. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_exc)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_pub"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: initial sync copies included table'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_exc"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: initial sync skips excluded table'); + +# DML: only the included table should be replicated. +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_pub VALUES (6); + INSERT INTO sch1.tab_exc VALUES (6); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_pub"); +is($result, qq(6), + 'TABLES IN SCHEMA EXCEPT: DML on included table is replicated'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_exc"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: DML on excluded table is not replicated'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Inherited tables: excluding the parent (without ONLY) also excludes the child. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.par)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.chi VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.chi"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: excluding parent (without ONLY) also excludes child' +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Truncate chi on the publisher so the next test starts with a clean slate. +# (The previous test inserted rows into chi that would otherwise be copied by +# the initial table sync of the next subscription.) +$node_publisher->safe_psql('postgres', 'TRUNCATE sch1.chi'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE sch1.chi'); +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE ONLY sch1.par)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.chi VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.chi"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: ONLY parent in EXCEPT does not exclude child' +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); +$node_publisher->safe_psql('postgres', + 'TRUNCATE sch1.par, sch1.chi, sch1.tab_exc'); +$node_subscriber->safe_psql('postgres', + 'TRUNCATE sch1.par, sch1.chi, sch1.tab_pub, sch1.tab_exc'); + +# Cleanup schema tables before the multi-publication section. +$node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); +$node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); + # ============================================ # Test when a subscription is subscribing to multiple publications # ============================================ @@ -254,6 +388,7 @@ $node_publisher->safe_psql( DROP PUBLICATION tap_pub2; TRUNCATE tab1; )); +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_subscriber->safe_psql('postgres', qq(TRUNCATE tab1)); # OK when a table is excluded by pub1 EXCEPT clause, but it is included by pub2 -- 2.50.1 (Apple Git-155)
v4-0002-Add-EXCEPT-support-to-ALTER-PUBLICATION-ADD-TABLE.patch (application/octet-stream, 16.3K) download From 13dbb4b792c77e6be155d17b307fa0abbc8b6f8b Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Mon, 27 Apr 2026 13:03:29 +0530 Subject: [PATCH v4 2/3] Add EXCEPT support to ALTER PUBLICATION ADD TABLES IN SCHEMA Extend the EXCEPT clause support to allow tables to be excluded when adding a schema to a publication via ALTER PUBLICATION ... ADD: Syntax: ALTER PUBLICATION pub ADD TABLES IN SCHEMA s EXCEPT (TABLE s.t1); --- doc/src/sgml/ref/alter_publication.sgml | 42 +++++++- src/backend/commands/publicationcmds.c | 113 +++++++++++++++++++++- src/bin/psql/tab-complete.in.c | 28 ++++++ src/test/regress/expected/publication.out | 18 +++- src/test/regress/sql/publication.sql | 11 ++- src/test/subscription/t/037_except.pl | 28 ++++++ 6 files changed, 236 insertions(+), 4 deletions(-) diff --git a/doc/src/sgml/ref/alter_publication.sgml b/doc/src/sgml/ref/alter_publication.sgml index aa32bb169e9..8aedfd951a5 100644 --- a/doc/src/sgml/ref/alter_publication.sgml +++ b/doc/src/sgml/ref/alter_publication.sgml @@ -31,7 +31,7 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -54,6 +54,10 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <phrase>and <replaceable class="parameter">table_object</replaceable> is:</phrase> [ ONLY ] <replaceable class="parameter">table_name</replaceable> [ * ] + +<phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> + + [ ONLY ] <replaceable class="parameter">table_name</replaceable> [ * ] </synopsis> </refsynopsisdiv> @@ -110,6 +114,15 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <literal>ADD TABLE</literal>. </para> + <para> + The <literal>EXCEPT</literal> clause can be used with + <literal>ADD TABLES IN SCHEMA</literal> to exclude specific tables from a + schema-level publication. <literal>EXCEPT</literal> is not supported with + <literal>DROP TABLES IN SCHEMA</literal>; instead, dropping a schema from + the publication automatically removes all of its associated + <literal>EXCEPT</literal> entries. + </para> + <para> The fourth variant of this command listed in the synopsis can change all of the publication properties specified in @@ -198,6 +211,23 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r </listitem> </varlistentry> + <varlistentry> + <term><literal>EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] )</literal></term> + <listitem> + <para> + Specifies tables to be excluded from a schema-level publication entry. + This clause may be used with <literal>ADD TABLES IN SCHEMA</literal> + and not with <literal>DROP TABLES IN SCHEMA</literal>. Each named + table must belong to the schema specified in the same + <literal>TABLES IN SCHEMA</literal> clause. Table names may be + schema-qualified or unqualified; unqualified names are implicitly + qualified with the schema named in the same clause. See + <xref linkend="sql-createpublication"/> for further details on the + semantics of <literal>EXCEPT</literal>. + </para> + </listitem> + </varlistentry> + <varlistentry> <term><literal>SET ( <replaceable class="parameter">publication_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] )</literal></term> <listitem> @@ -288,6 +318,16 @@ ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA marketing, sales; </programlisting> </para> + <para> + Add schema <structname>sales</structname> to the publication + <structname>sales_publication</structname>, excluding the + <structname>sales.internal</structname> and + <structname>sales.drafts</structname> tables: +<programlisting> +ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA sales EXCEPT (TABLE sales.internal, sales.drafts); +</programlisting> + </para> + <para> Add tables <structname>users</structname>, <structname>departments</structname> and schema diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index dfe3e1f9706..858c0d0944d 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -70,6 +70,9 @@ static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok); static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); +static void AlterPublicationExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, List *exceptrelations, + List *schemaidlist); static char defGetGeneratedColsOption(DefElem *def); @@ -1528,6 +1531,13 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, } PublicationAddSchemas(pubform->oid, schemaidlist, false, stmt); + + /* + * Increment the command counter so that is_schema_publication() in + * GetExcludedPublicationTables() can see the just-inserted schema + * rows when AlterPublicationExceptTables runs next. + */ + CommandCounterIncrement(); } else if (stmt->action == AP_DropObjects) PublicationDropSchemas(pubform->oid, schemaidlist, false); @@ -1553,6 +1563,100 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, * skip existing ones when doing catalog update. */ PublicationAddSchemas(pubform->oid, schemaidlist, true, stmt); + + /* + * Increment the command counter so that is_schema_publication() in + * GetExcludedPublicationTables() can see the just-inserted schema + * rows when AlterPublicationExceptTables runs next. + */ + CommandCounterIncrement(); + } +} + +/* + * Alter the EXCEPT list of a publication. + * + * Adds, removes, or replaces except-table entries in pg_publication_rel + * (rows with prexcept = true). These entries suppress publication of the + * named tables that would otherwise be covered by a FOR TABLES IN SCHEMA + * or FOR ALL TABLES clause. + */ +static void +AlterPublicationExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, List *exceptrelations, + List *schemaidlist) +{ + Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); + Oid pubid = pubform->oid; + + /* + * Nothing to do if no EXCEPT entries. + */ + if (!exceptrelations) + return; + + /* + * This function handles EXCEPT entries for schema-level publications + * only. For FOR ALL TABLES publications, EXCEPT entries are already + * processed by AlterPublicationTables(). + */ + if (schemaidlist == NIL && !is_schema_publication(pubid)) + return; + + /* + * EXCEPT is not meaningful with DROP: dropping a schema from a + * publication already removes all its except entries via cascade, and + * there is no sensible interpretation of "drop only the except entry but + * keep the schema". + */ + if (stmt->action == AP_DropObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); + + /* + * EXCEPT with SET is not supported: SET replaces the schema list but does + * not have a well-defined semantics for merging or replacing existing + * except entries. Users should DROP and re-ADD the schema with the + * desired EXCEPT list instead. + */ + if (stmt->action == AP_SetObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"))); + + if (stmt->action == AP_AddObjects) + { + List *rels; + List *explicitrelids; + ListCell *lc; + + rels = OpenTableList(exceptrelations); + + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + /* + * Validate that each excluded table is not also in the explicit table + * list (which would be contradictory). + */ + foreach(lc, rels) + { + PublicationRelInfo *pri = (PublicationRelInfo *) lfirst(lc); + Oid relid = RelationGetRelid(pri->relation); + Oid relns = RelationGetNamespace(pri->relation); + + if (list_member_oid(explicitrelids, relid)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s.%s\" cannot appear in both the table list and the EXCEPT clause", + get_namespace_name(relns), + RelationGetRelationName(pri->relation))); + } + + PublicationAddTables(pubid, rels, false, stmt); + + CloseTableList(rels); } } @@ -1763,10 +1867,17 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) errmsg("publication \"%s\" does not exist", stmt->pubname)); - relations = list_concat(relations, exceptrelations); + /* + * For FOR ALL TABLES, EXCEPT entries are processed by + * AlterPublicationTables(), so merge them in. For TABLES IN SCHEMA, + * they are handled separately by AlterPublicationExceptTables(). + */ + if (stmt->for_all_tables) + relations = list_concat(relations, exceptrelations); AlterPublicationTables(stmt, tup, relations, pstate->p_sourcetext, schemaidlist != NIL); AlterPublicationSchemas(stmt, tup, schemaidlist); + AlterPublicationExceptTables(stmt, tup, exceptrelations, schemaidlist); AlterPublicationAllFlags(stmt, rel, tup); } diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index 6c9c7552627..c930c6c672e 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2363,6 +2363,34 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); + /* After a single schema name in ADD context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + if (strchr(previous_words[3], ',') == NULL) + { + set_completion_reference(previous_words[3]); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && ends_with(prev_wd, ',')) + { + char *schema_word = previous_words[previous_words_count - 8]; + + if (strchr(schema_word, ',') == NULL) + { + set_completion_reference(schema_word); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index e78192edd01..ca163b2bb01 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -522,9 +522,25 @@ CREATE PUBLICATION testpub_except_crossschema ERROR: table "pub_test.testpub_tbl_s1" in EXCEPT clause does not belong to schema "public" LINE 2: ...R TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.t... ^ +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; +-- ADD: add a schema with an excepted table +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_alter_except; CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; -- FOR ALL SEQUENCES diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 9120902dfac..3a9a9e403f8 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -250,9 +250,18 @@ CREATE PUBLICATION testpub_except_wrongschema CREATE PUBLICATION testpub_except_crossschema FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; + +-- ADD: add a schema with an excepted table +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_alter_except + RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_alter_except; CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index d2b1fb8f9ff..64f0e2173b2 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -353,6 +353,34 @@ $node_publisher->safe_psql('postgres', $node_subscriber->safe_psql('postgres', 'TRUNCATE sch1.par, sch1.chi, sch1.tab_pub, sch1.tab_exc'); +# ============================================ +# ALTER PUBLICATION EXCEPT for TABLES IN SCHEMA +# ============================================ + +# ADD: add a schema with an excepted table; verify the except entry takes effect. +$node_publisher->safe_psql('postgres', "CREATE PUBLICATION sch_pub"); +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub ADD TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_exc)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_pub"); +is($result, qq(6), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: included table synced'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_exc"); +is($result, qq(0), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + # Cleanup schema tables before the multi-publication section. $node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); $node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); -- 2.50.1 (Apple Git-155)
v4-0003-Add-EXCEPT-support-to-ALTER-PUBLICATION-SET-TABLE.patch (application/octet-stream, 20.7K) download From 344321031a67496ffb949cc927e68d22878fdd41 Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Mon, 27 Apr 2026 13:22:38 +0530 Subject: [PATCH v4 3/3] Add EXCEPT support to ALTER PUBLICATION SET TABLES IN SCHEMA Extend AlterPublicationExceptTables() with the AP_SetObjects case, which redefine the publication and replaces the entire EXCEPT list. Syntax: ALTER PUBLICATION pub SET TABLES IN SCHEMA s EXCEPT (TABLE s.t1); --- doc/src/sgml/ref/alter_publication.sgml | 36 ++++-- src/backend/catalog/pg_publication.c | 2 +- src/backend/commands/publicationcmds.c | 145 ++++++++++++++++++++-- src/bin/psql/tab-complete.in.c | 28 +++++ src/test/regress/expected/publication.out | 20 +++ src/test/regress/sql/publication.sql | 10 ++ src/test/subscription/t/037_except.pl | 90 ++++++++++++++ 7 files changed, 305 insertions(+), 26 deletions(-) diff --git a/doc/src/sgml/ref/alter_publication.sgml b/doc/src/sgml/ref/alter_publication.sgml index 8aedfd951a5..1b73b34e43a 100644 --- a/doc/src/sgml/ref/alter_publication.sgml +++ b/doc/src/sgml/ref/alter_publication.sgml @@ -54,10 +54,6 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <phrase>and <replaceable class="parameter">table_object</replaceable> is:</phrase> [ ONLY ] <replaceable class="parameter">table_name</replaceable> [ * ] - -<phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> - - [ ONLY ] <replaceable class="parameter">table_name</replaceable> [ * ] </synopsis> </refsynopsisdiv> @@ -97,7 +93,11 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r used with a publication defined with <literal>FOR TABLE</literal> or <literal>FOR TABLES IN SCHEMA</literal>, replaces the list of tables/schemas in the publication with the specified list; the existing tables or schemas - that were present in the publication will be removed. + that were present in the publication will be removed. When + <literal>SET TABLES IN SCHEMA</literal> is used with an + <literal>EXCEPT</literal> clause, the excluded tables for each schema are + replaced with the specified list; if <literal>EXCEPT</literal> is omitted + for a schema, any existing exclusions for that schema are cleared. </para> <para> @@ -116,7 +116,8 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <para> The <literal>EXCEPT</literal> clause can be used with - <literal>ADD TABLES IN SCHEMA</literal> to exclude specific tables from a + <literal>ADD TABLES IN SCHEMA</literal> and + <literal>SET TABLES IN SCHEMA</literal> to exclude specific tables from a schema-level publication. <literal>EXCEPT</literal> is not supported with <literal>DROP TABLES IN SCHEMA</literal>; instead, dropping a schema from the publication automatically removes all of its associated @@ -217,12 +218,12 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <para> Specifies tables to be excluded from a schema-level publication entry. This clause may be used with <literal>ADD TABLES IN SCHEMA</literal> - and not with <literal>DROP TABLES IN SCHEMA</literal>. Each named - table must belong to the schema specified in the same - <literal>TABLES IN SCHEMA</literal> clause. Table names may be - schema-qualified or unqualified; unqualified names are implicitly - qualified with the schema named in the same clause. See - <xref linkend="sql-createpublication"/> for further details on the + and <literal>SET TABLES IN SCHEMA</literal>, and not with + <literal>DROP TABLES IN SCHEMA</literal>. Each named table must belong + to the schema specified in the same <literal>TABLES IN SCHEMA</literal> + clause. Table names may be schema-qualified or unqualified; unqualified + names are implicitly qualified with the schema named in the same clause. + See <xref linkend="sql-createpublication"/> for further details on the semantics of <literal>EXCEPT</literal>. </para> </listitem> @@ -328,6 +329,17 @@ ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA sales EXCEPT (TABLE sal </programlisting> </para> + <para> + Replace the schema list of <structname>sales_publication</structname> with + <structname>sales</structname>, excluding only + <structname>sales.drafts</structname> (any previously excluded tables for + that schema are replaced, and schemas previously in the publication are + removed): +<programlisting> +ALTER PUBLICATION sales_publication SET TABLES IN SCHEMA sales EXCEPT (TABLE sales.drafts); +</programlisting> + </para> + <para> Add tables <structname>users</structname>, <structname>departments</structname> and schema diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index 85c2528873f..e63f221f1af 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -1002,7 +1002,7 @@ GetIncludedPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) List * GetExcludedPublicationTables(Oid pubid, PublicationPartOpt pub_partopt) { - Assert(GetPublication(pubid)->alltables); + Assert(GetPublication(pubid)->alltables || is_schema_publication(pubid)); return get_publication_relations(pubid, pub_partopt, true); } diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 858c0d0944d..96f653c5e95 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -1590,9 +1590,11 @@ AlterPublicationExceptTables(AlterPublicationStmt *stmt, Oid pubid = pubform->oid; /* - * Nothing to do if no EXCEPT entries. + * Nothing to do if no EXCEPT entries, except in SET: for that it is quite + * possible that the user has removed all exceptions, in which case we + * need to drop any existing ones. */ - if (!exceptrelations) + if (!exceptrelations && stmt->action != AP_SetObjects) return; /* @@ -1614,17 +1616,6 @@ AlterPublicationExceptTables(AlterPublicationStmt *stmt, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); - /* - * EXCEPT with SET is not supported: SET replaces the schema list but does - * not have a well-defined semantics for merging or replacing existing - * except entries. Users should DROP and re-ADD the schema with the - * desired EXCEPT list instead. - */ - if (stmt->action == AP_SetObjects) - ereport(ERROR, - (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"))); - if (stmt->action == AP_AddObjects) { List *rels; @@ -1656,6 +1647,95 @@ AlterPublicationExceptTables(AlterPublicationStmt *stmt, PublicationAddTables(pubid, rels, false, stmt); + CloseTableList(rels); + } + else /* AP_SetObjects */ + { + List *oldexceptrelids = NIL; + List *newexceptrelids = NIL; + List *delrelids = NIL; + List *rels; + List *explicitrelids; + ListCell *lc; + + rels = OpenTableList(exceptrelations); + + /* Collect OIDs of the desired new except list. */ + foreach(lc, rels) + { + PublicationRelInfo *pri = (PublicationRelInfo *) lfirst(lc); + + newexceptrelids = lappend_oid(newexceptrelids, + RelationGetRelid(pri->relation)); + } + + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + /* + * Validate that each excluded table is not also in the explicit table + * list (which would be contradictory). + */ + foreach(lc, rels) + { + PublicationRelInfo *pri = (PublicationRelInfo *) lfirst(lc); + Oid relid = RelationGetRelid(pri->relation); + Oid relns = RelationGetNamespace(pri->relation); + + if (list_member_oid(explicitrelids, relid)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s.%s\" cannot appear in both the table list and the EXCEPT clause", + get_namespace_name(relns), + RelationGetRelationName(pri->relation))); + } + + /* + * Get the current set of except entries. Only FOR ALL TABLES and + * schema-level publications can have except entries; for any other + * publication type oldexceptrelids stays NIL. + * + * Note: we check is_schema_publication() against the current catalog + * state (before AlterPublicationSchemas has run), so if the caller is + * doing SET TABLE t1 to convert a schema publication into a plain + * table publication, is_schema_publication() still returns true here. + * That is intentional: it lets us discover and clean up any stale + * except entries that belong to the old schema definition. + */ + if (GetPublication(pubid)->alltables || is_schema_publication(pubid)) + oldexceptrelids = GetExcludedPublicationTables(pubid, + PUBLICATION_PART_ROOT); + + /* Build a list of old except entries not present in the new list. */ + foreach(lc, oldexceptrelids) + { + Oid oldrelid = lfirst_oid(lc); + + if (!list_member_oid(newexceptrelids, oldrelid)) + delrelids = lappend_oid(delrelids, oldrelid); + } + + /* Drop old except entries not present in the new list. */ + foreach(lc, delrelids) + { + Oid relid = lfirst_oid(lc); + Oid proid; + ObjectAddress obj; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (!OidIsValid(proid)) + continue; /* already gone */ + + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + + /* Add new except entries, skipping any already present. */ + PublicationAddTables(pubid, rels, true, stmt); + CloseTableList(rels); } } @@ -2310,6 +2390,8 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) foreach(lc, schemas) { Oid schemaid = lfirst_oid(lc); + List *exceptoids; + ListCell *elc; psid = GetSysCacheOid2(PUBLICATIONNAMESPACEMAP, Anum_pg_publication_namespace_oid, @@ -2326,8 +2408,45 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) get_namespace_name(schemaid)))); } + /* + * Collect prexcept rows for tables belonging to this schema before + * removing the schema entry. GetExcludedPublicationTables relies on + * is_schema_publication(), which scans pg_publication_namespace; if + * this is the last schema in the publication, performDeletion() below + * would remove that row and make is_schema_publication() return + * false, tripping the assertion. + */ + exceptoids = GetExcludedPublicationTables(pubid, PUBLICATION_PART_ROOT); + ObjectAddressSet(obj, PublicationNamespaceRelationId, psid); performDeletion(&obj, DROP_CASCADE, 0); + + /* + * Drop any prexcept rows for tables belonging to this schema. These + * rows have no pg_depend entry pointing at the + * pg_publication_namespace row, so they are not cascaded by the + * performDeletion() call above and must be cleaned up explicitly. + */ + foreach(elc, exceptoids) + { + Oid relid = lfirst_oid(elc); + Oid proid; + + if (get_rel_namespace(relid) != schemaid) + continue; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (!OidIsValid(proid)) + continue; /* already gone */ + + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + + list_free(exceptoids); } } diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index c930c6c672e..5afcce87f72 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2391,6 +2391,34 @@ match_previous_words(int pattern_id, } else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) COMPLETE_WITH(")"); + /* After a single schema name in SET context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + if (strchr(previous_words[3], ',') == NULL) + { + set_completion_reference(previous_words[3]); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && ends_with(prev_wd, ',')) + { + char *schema_word = previous_words[previous_words_count - 8]; + + if (strchr(schema_word, ',') == NULL) + { + set_completion_reference(schema_word); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index ca163b2bb01..5b6bf3bbddd 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -538,6 +538,26 @@ Tables from schemas: Except tables: "pub_test.testpub_tbl_s1" +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s2" + +-- error: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +ERROR: EXCEPT clause is not supported with DROP in ALTER PUBLICATION +-- error: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 1: ...xcept SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.tes... + ^ RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_alter_except; diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 3a9a9e403f8..fdc6940c87d 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -259,6 +259,16 @@ CREATE PUBLICATION testpub_alter_except; ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); \dRp+ testpub_alter_except +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + +-- error: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); + +-- error: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_alter_except; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 64f0e2173b2..580acd74bca 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -378,6 +378,66 @@ $result = is($result, qq(0), 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); +# SET: replace the except list; tab_exc is now included and tab_pub is excluded. +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_pub)" +); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_pub VALUES (7); + INSERT INTO sch1.tab_exc VALUES (7); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_exc"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: newly included table is replicated' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_pub"); +is($result, qq(6), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: now-excluded table is not replicated' +); + +# SET without EXCEPT: clears the except list; both tables are now published. +# tab_pub will be re-synced because REFRESH removed its entry when it was +# excluded. Truncate the subscriber copy beforehand so the re-sync produces +# a predictable count: publisher has 7 rows (6 original + INSERT(7)), so the +# subscriber ends up with 7 after re-sync, then 8 after INSERT(8). +$node_subscriber->safe_psql('postgres', 'TRUNCATE sch1.tab_pub'); +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1"); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_pub VALUES (8); + INSERT INTO sch1.tab_exc VALUES (8); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_pub"); +is($result, qq(8), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_pub replicated after except list cleared' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_exc"); +is($result, qq(2), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_exc replicated after except list cleared' +); + $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); @@ -445,6 +505,36 @@ $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); +# OK when a table is excluded by a TABLES IN SCHEMA EXCEPT publication, +# but is included by another publication. +$node_publisher->safe_psql('postgres', 'TRUNCATE tab1'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE tab1'); + +$node_publisher->safe_psql( + 'postgres', qq( + CREATE PUBLICATION tap_pub1 FOR TABLES IN SCHEMA public EXCEPT (TABLE public.tab1); + CREATE PUBLICATION tap_pub2 FOR TABLE tab1; + INSERT INTO tab1 VALUES(1); +)); +$node_subscriber->psql('postgres', + "CREATE SUBSCRIPTION tap_sub CONNECTION '$publisher_connstr' PUBLICATION tap_pub1, tap_pub2" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'tap_sub'); + +$node_publisher->safe_psql('postgres', qq(INSERT INTO tab1 VALUES(2))); +$node_publisher->wait_for_catchup('tap_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT * FROM tab1 ORDER BY a"); +is( $result, qq(1 +2), + "TABLES IN SCHEMA EXCEPT: table excluded in schema pub but included by another pub is replicated" +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); + $node_publisher->stop('fast'); done_testing(); -- 2.50.1 (Apple Git-155)
^ permalink raw reply [nested|flat] 196+ messages in thread

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-04-29 05:45  Peter Smith <smithpb2250@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  1 sibling, 1 reply; 196+ messages in thread

From: Peter Smith @ 2026-04-29 05:45 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Hi Nisha.

Some review comments for v4-0001 (docs only).

======
doc/src/sgml/ref/create_publication.sgml

1.
+    TABLES IN SCHEMA { <replaceable
class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [
EXCEPT ( <replaceable
class="parameter">except_table_object</replaceable> [, ... ] ) ] [,
... ]

It is ambiguous which part does that last ellipsis applies to?

Consider instead:

TABLES IN SCHEMA tables_in_schema [, ... ]

and tables_in_schema is:
{ schema_name | CURRENT_SCHEMA } [ EXCEPT ( except_table_object [, ... ] ) ]

~~~

2.
      <para>
       This clause specifies a list of tables to be excluded from the
-      publication.
+      publication. It can be used with both <literal>FOR ALL TABLES</literal>
+      and <literal>FOR TABLES IN SCHEMA</literal>.
      </para>

Saying "both" may imply they can coexist, but they cannot.

SUGGESTION
It can be used with <literal>FOR ALL TABLES</literal> or <literal>FOR
TABLES IN SCHEMA</literal>.

~~~

3.
+  <para>
+   Create a publication that publishes all changes for all the tables
present in
+   the schema <structname>sales</structname>, except
+   <structname>sales.internal</structname> and
<structname>sales.drafts</structname>:
+<programlisting>
+CREATE PUBLICATION sales_filtered FOR TABLES IN SCHEMA sales EXCEPT
(TABLE sales.internal, sales.drafts);
+</programlisting>
+  </para>
+

AFAIK, the tables in the EXCEPT clause do not need to be
schema-qualified, so they should not be written that way in the
programlisting part of this example, because it might give the user
the impression that schema-qualified names are required.

======
Kind Regards,
Peter Smith.
Fujitsu Australia





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-04-29 06:32  Peter Smith <smithpb2250@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  1 sibling, 1 reply; 196+ messages in thread

From: Peter Smith @ 2026-04-29 06:32 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Hi Nisha.

A couple of ad-hoc review comments for v4-0001...

======
src/bin/pg_dump/pg_dump.c

dumpPublicationNamespace:

1.
+ if (!first_except)
+ appendPQExpBufferStr(query, ")");

The logic seems ok, but the above seems a bit strange, checking
'first_except'. Maybe renaming to 'has_except' (and some small
refactoring) would read better?

~~~

2.
IIUC, the 'ALTER PUBLICATION' EXCEPT clause syntax change is not
introduced until your patch 0003. So, how does this dump code even
work when it relies on that ALTER PUBLICATION?

Furthermore, the patch 0003 commit message says 'ALTER PUBLICATION pub
SET TABLES', but this dump code is using 'ALTER PUBLICATION pub ADD
TABLES' (note ADD v SET). Something seems suspicious...

======
Kind Regards,
Peter Smith.
Fujitsu Australia





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-05-04 12:05  Nisha Moond <nisha.moond412@gmail.com>
  parent: Peter Smith <smithpb2250@gmail.com>
  0 siblings, 0 replies; 196+ messages in thread

From: Nisha Moond @ 2026-05-04 12:05 UTC (permalink / raw)
  To: Peter Smith <smithpb2250@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Wed, Apr 29, 2026 at 11:16 AM Peter Smith <smithpb2250@gmail.com> wrote:
>
> Hi Nisha.
>
> Some review comments for v4-0001 (docs only).
>

Thank you Peter for the review.

> ======
> doc/src/sgml/ref/create_publication.sgml
>
> 1.
> +    TABLES IN SCHEMA { <replaceable
> class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [
> EXCEPT ( <replaceable
> class="parameter">except_table_object</replaceable> [, ... ] ) ] [,
> ... ]
>
> It is ambiguous which part does that last ellipsis applies to?
>
> Consider instead:
>
> TABLES IN SCHEMA tables_in_schema [, ... ]
>
> and tables_in_schema is:
> { schema_name | CURRENT_SCHEMA } [ EXCEPT ( except_table_object [, ... ] ) ]
>
> ~~~

Fixed.

>
> 2.
>       <para>
>        This clause specifies a list of tables to be excluded from the
> -      publication.
> +      publication. It can be used with both <literal>FOR ALL TABLES</literal>
> +      and <literal>FOR TABLES IN SCHEMA</literal>.
>       </para>
>
> Saying "both" may imply they can coexist, but they cannot.
>
> SUGGESTION
> It can be used with <literal>FOR ALL TABLES</literal> or <literal>FOR
> TABLES IN SCHEMA</literal>.
>
> ~~~

Fixed.

>
> 3.
> +  <para>
> +   Create a publication that publishes all changes for all the tables
> present in
> +   the schema <structname>sales</structname>, except
> +   <structname>sales.internal</structname> and
> <structname>sales.drafts</structname>:
> +<programlisting>
> +CREATE PUBLICATION sales_filtered FOR TABLES IN SCHEMA sales EXCEPT
> (TABLE sales.internal, sales.drafts);
> +</programlisting>
> +  </para>
> +
>
> AFAIK, the tables in the EXCEPT clause do not need to be
> schema-qualified, so they should not be written that way in the
> programlisting part of this example, because it might give the user
> the impression that schema-qualified names are required.
>

Done, matched with nearby examples.

All of the above comments are addressed in v5-0001 patch.

--
Thanks,
Nisha





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-05-04 12:05  Nisha Moond <nisha.moond412@gmail.com>
  parent: Peter Smith <smithpb2250@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: Nisha Moond @ 2026-05-04 12:05 UTC (permalink / raw)
  To: Peter Smith <smithpb2250@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Wed, Apr 29, 2026 at 12:02 PM Peter Smith <smithpb2250@gmail.com> wrote:
>
> Hi Nisha.
>
> A couple of ad-hoc review comments for v4-0001...
>
> ======
> src/bin/pg_dump/pg_dump.c
>
> dumpPublicationNamespace:
>
> 1.
> + if (!first_except)
> + appendPQExpBufferStr(query, ")");
>
> The logic seems ok, but the above seems a bit strange, checking
> 'first_except'. Maybe renaming to 'has_except' (and some small
> refactoring) would read better?
>
> ~~~

Thanks for pointing that out. This also needed updating after the
syntax change to EXCEPT (TABLE ...).
I’ve used the name "has_except", defaulting it to false for better readability.

>
> 2.
> IIUC, the 'ALTER PUBLICATION' EXCEPT clause syntax change is not
> introduced until your patch 0003. So, how does this dump code even
> work when it relies on that ALTER PUBLICATION?
>
> Furthermore, the patch 0003 commit message says 'ALTER PUBLICATION pub
> SET TABLES', but this dump code is using 'ALTER PUBLICATION pub ADD
> TABLES' (note ADD v SET). Something seems suspicious...
>

I think there was a slight mix-up in reading the patch messages. The
ALTER PUBLICATION ... EXCEPT syntax is introduced in patch-002 for
ADD, not patch-003.

That said, you’re right. The pg_dump part doesn’t work with patch-001
alone. I missed moving it to patch-002 while splitting the patches.
Thanks for catching that; it’s now fixed.

Also, patch-003 is for SET (not ADD) and includes handling for cleanup
of EXCEPT entries when a schema is dropped. I’ve updated the patch
message for clarity.

Attached v5 patches with these updates.

--
Thanks,
Nisha

Attachments: download all (3 files, .tar.gz)

v5-0001-Support-EXCEPT-clause-for-schema-level-publicatio.patch (application/octet-stream, 37.5K) download From 906bb9a40f1d5e75dd5ff43409fda5e86dc03b01 Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Mon, 4 May 2026 12:49:27 +0530 Subject: [PATCH v5 1/3] Support EXCEPT clause for schema-level publications Extend table exclusion support in publications to allow specific tables to be excluded from schema-level publications using an EXCEPT clause in CREATE PUBLICATION. Supported syntax: CREATE PUBLICATION <pub> FOR TABLES IN SCHEMA s EXCEPT (TABLE t1,...); --- doc/src/sgml/logical-replication.sgml | 3 +- doc/src/sgml/ref/create_publication.sgml | 20 ++- src/backend/catalog/pg_publication.c | 107 ++++++++++++--- src/backend/commands/publicationcmds.c | 52 ++++++++ src/backend/parser/gram.y | 53 +++++++- src/backend/replication/pgoutput/pgoutput.c | 34 ++++- src/bin/psql/describe.c | 18 +++ src/bin/psql/tab-complete.in.c | 37 +++++- src/include/nodes/parsenodes.h | 1 + src/test/regress/expected/publication.out | 56 +++++++- src/test/regress/sql/publication.sql | 35 ++++- src/test/subscription/t/037_except.pl | 139 +++++++++++++++++++- 12 files changed, 519 insertions(+), 36 deletions(-) diff --git a/doc/src/sgml/logical-replication.sgml b/doc/src/sgml/logical-replication.sgml index 9e7868487de..1433d2660fe 100644 --- a/doc/src/sgml/logical-replication.sgml +++ b/doc/src/sgml/logical-replication.sgml @@ -117,7 +117,8 @@ or <literal>FOR ALL SEQUENCES</literal>. Unlike tables, sequences can be synchronized at any time. For more information, see <xref linkend="logical-replication-sequences"/>. When a publication is - created with <literal>FOR ALL TABLES</literal>, a table or set of tables can + created with <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal>, a table or set of tables can be explicitly excluded from publication using the <link linkend="sql-createpublication-params-for-except-table"><literal>EXCEPT</literal></link> clause. diff --git a/doc/src/sgml/ref/create_publication.sgml b/doc/src/sgml/ref/create_publication.sgml index f82d640e6ca..f9ee7a1a4cf 100644 --- a/doc/src/sgml/ref/create_publication.sgml +++ b/doc/src/sgml/ref/create_publication.sgml @@ -28,7 +28,7 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA <replaceable class="parameter">tables_in_schema</replaceable> [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -39,6 +39,10 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <replaceable class="parameter">table_object</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] [ WHERE ( <replaceable class="parameter">expression</replaceable> ) ] +<phrase>and <replaceable class="parameter">tables_in_schema</replaceable> is:</phrase> + + { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] + <phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> TABLE <replaceable class="parameter">table_object</replaceable> [, ... ] @@ -142,6 +146,8 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <para> Marks the publication as one that replicates changes for all tables in the specified list of schemas, including tables created in the future. + Tables listed in <literal>EXCEPT</literal> for a given schema are + excluded from the publication. </para> <para> @@ -198,7 +204,8 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <listitem> <para> This clause specifies a list of tables to be excluded from the - publication. + publication. It can be used with <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal>. </para> <para> For inherited tables, if <literal>ONLY</literal> is specified before the @@ -515,6 +522,15 @@ CREATE PUBLICATION production_publication FOR TABLE users, departments, TABLES I CREATE PUBLICATION sales_publication FOR TABLES IN SCHEMA marketing, sales; </programlisting></para> + <para> + Create a publication that publishes all changes for all the tables present in + the schema <structname>sales</structname>, except + <structname>internal</structname> and <structname>drafts</structname>: +<programlisting> +CREATE PUBLICATION sales_filtered FOR TABLES IN SCHEMA sales EXCEPT (TABLE internal, drafts); +</programlisting> + </para> + <para> Create a publication that publishes all changes for table <structname>users</structname>, but replicates only columns <structname>user_id</structname> and diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index a43d385c605..85c2528873f 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -529,6 +529,7 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, referenced; List *relids = NIL; int i; + HeapTuple existing; bool inval_except_table; rel = table_open(PublicationRelRelationId, RowExclusiveLock); @@ -538,18 +539,33 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, * duplicates, it's here just to provide nicer error message in common * case. The real protection is the unique key on the catalog. */ - if (SearchSysCacheExists2(PUBLICATIONRELMAP, ObjectIdGetDatum(relid), - ObjectIdGetDatum(pubid))) + existing = SearchSysCache2(PUBLICATIONRELMAP, ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + + if (HeapTupleIsValid(existing)) { + Form_pg_publication_rel existing_form = + (Form_pg_publication_rel) GETSTRUCT(existing); + bool is_except = existing_form->prexcept; + + ReleaseSysCache(existing); table_close(rel, RowExclusiveLock); if (if_not_exists) return InvalidObjectAddress; - ereport(ERROR, - (errcode(ERRCODE_DUPLICATE_OBJECT), - errmsg("relation \"%s\" is already member of publication \"%s\"", - RelationGetRelationName(targetrel), pub->name))); + if (is_except) + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("table \"%s.%s\" cannot be added because it is listed in EXCEPT clause of publication \"%s\"", + get_namespace_name(RelationGetNamespace(targetrel)), + RelationGetRelationName(targetrel), + pub->name))); + else + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("relation \"%s\" is already member of publication \"%s\"", + RelationGetRelationName(targetrel), pub->name))); } check_publication_add_relation(pri); @@ -620,19 +636,24 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, /* * Determine whether EXCEPT tables require explicit relcache invalidation. * - * For CREATE PUBLICATION with EXCEPT tables, invalidation is skipped - * here, as CreatePublication() function invalidates all relations as part - * of defining a FOR ALL TABLES publication. + * For CREATE PUBLICATION with EXCEPT tables, invalidation is skipped here + * because the excluded tables were never included in the publication, so + * no subscriber cache entry needs to be cleared. + * + * For ALTER PUBLICATION, invalidation is needed when adding an EXCEPT + * table to either: - a FOR ALL TABLES publication (pub->alltables is + * true), or - a FOR TABLES IN SCHEMA publication (is_schema_publication + * is true). * - * For ALTER PUBLICATION, invalidation is needed only when adding an - * EXCEPT table to a publication already marked as ALL TABLES. For - * publications that were originally empty or defined as ALL SEQUENCES and - * are being converted to ALL TABLES, invalidation is skipped here, as - * AlterPublicationAllFlags() function invalidates all relations while - * marking the publication as ALL TABLES publication. + * The exception: when a publication is being converted to FOR ALL TABLES + * (pub->alltables is still false at this point), + * AlterPublicationAllFlags() will perform a full invalidation, so we skip + * it here. */ - inval_except_table = (alter_stmt != NULL) && pub->alltables && - (alter_stmt->for_all_tables && pri->except); + inval_except_table = (alter_stmt != NULL) && pri->except && + (pub->alltables + ? alter_stmt->for_all_tables + : is_schema_publication(pubid)); if (!pri->except || inval_except_table) { @@ -975,7 +996,8 @@ GetIncludedPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) * Gets list of table oids that were specified in the EXCEPT clause for a * publication. * - * This should only be used FOR ALL TABLES publications. + * This is used for FOR ALL TABLES and FOR TABLES IN SCHEMA publications, + * both of which support EXCEPT TABLE. */ List * GetExcludedPublicationTables(Oid pubid, PublicationPartOpt pub_partopt) @@ -1225,22 +1247,67 @@ GetSchemaPublicationRelations(Oid schemaid, PublicationPartOpt pub_partopt) /* * Gets the list of all relations published by FOR TABLES IN SCHEMA - * publication. + * publication, excluding any tables listed in the EXCEPT clause. */ List * GetAllSchemaPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) { List *result = NIL; List *pubschemalist = GetPublicationSchemas(pubid); + List *exceptlist = NIL; ListCell *cell; + /* get the list of tables excluded via EXCEPT TABLE for this publication */ + if (pubschemalist != NIL) + exceptlist = get_publication_relations(pubid, pub_partopt, true); + foreach(cell, pubschemalist) { Oid schemaid = lfirst_oid(cell); List *schemaRels = NIL; schemaRels = GetSchemaPublicationRelations(schemaid, pub_partopt); - result = list_concat(result, schemaRels); + + if (exceptlist != NIL) + { + /* filter out any tables that appear in the EXCEPT list */ + ListCell *rlc; + + foreach(rlc, schemaRels) + { + Oid relid = lfirst_oid(rlc); + bool excluded = list_member_oid(exceptlist, relid); + + /* + * Also exclude any relation whose partition ancestor is in + * the EXCEPT list. This matters when pub_partopt is + * PUBLICATION_PART_ROOT: the except list holds only the root + * OID, but the schema scan may also return individual + * partition relations that live in the same schema. + */ + if (!excluded && get_rel_relispartition(relid)) + { + List *ancestors = get_partition_ancestors(relid); + ListCell *alc; + + foreach(alc, ancestors) + { + if (list_member_oid(exceptlist, lfirst_oid(alc))) + { + excluded = true; + break; + } + } + list_free(ancestors); + } + + if (!excluded) + result = lappend_oid(result, relid); + } + list_free(schemaRels); + } + else + result = list_concat(result, schemaRels); } return result; diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 440adb356ad..dfe3e1f9706 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -959,6 +959,8 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) } else if (!stmt->for_all_sequences) { + List *explicitrelids = NIL; + /* FOR TABLES IN SCHEMA requires superuser */ if (schemaidlist != NIL && !superuser()) ereport(ERROR, @@ -968,6 +970,7 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) if (relations != NIL) { List *rels; + ListCell *lc; rels = OpenTableList(relations); TransformPubWhereClauses(rels, pstate->p_sourcetext, @@ -977,6 +980,23 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) schemaidlist != NIL, publish_via_partition_root); + /* + * Collect explicit table OIDs now, before we close the relation + * list, so that except-table validation below can check for + * contradictions without relying on a catalog scan that might not + * yet see the just-inserted rows. + */ + if (exceptrelations != NIL) + { + foreach(lc, rels) + { + PublicationRelInfo *pri = (PublicationRelInfo *) lfirst(lc); + + explicitrelids = lappend_oid(explicitrelids, + RelationGetRelid(pri->relation)); + } + } + PublicationAddTables(puboid, rels, true, NULL); CloseTableList(rels); } @@ -989,6 +1009,38 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) */ LockSchemaList(schemaidlist); PublicationAddSchemas(puboid, schemaidlist, true, NULL); + + if (exceptrelations != NIL) + { + List *rels; + ListCell *lc; + + rels = OpenTableList(exceptrelations); + + /* + * Validate that each excluded table is not also in the + * explicit table list (which would be contradictory). Use + * the in-memory explicitrelids collected above rather than + * re-reading the catalog, which may not yet see the + * just-inserted rows. + */ + foreach(lc, rels) + { + PublicationRelInfo *pri = (PublicationRelInfo *) lfirst(lc); + Oid relid = RelationGetRelid(pri->relation); + Oid relns = RelationGetNamespace(pri->relation); + + if (list_member_oid(explicitrelids, relid)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s.%s\" cannot appear in both the table list and the EXCEPT clause", + get_namespace_name(relns), + RelationGetRelationName(pri->relation))); + } + + PublicationAddTables(puboid, rels, true, NULL); + CloseTableList(rels); + } } } diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y index ff4e1388c55..cd8d0453521 100644 --- a/src/backend/parser/gram.y +++ b/src/backend/parser/gram.y @@ -11272,7 +11272,7 @@ AlterOwnerStmt: ALTER AGGREGATE aggregate_with_argtypes OWNER TO RoleSpec * pub_obj is one of: * * TABLE table [, ...] - * TABLES IN SCHEMA schema [, ...] + * TABLES IN SCHEMA schema [EXCEPT ( table [, ...] )] [, ...] * *****************************************************************************/ @@ -11332,23 +11332,26 @@ PublicationObjSpec: $$->pubtable->columns = $3; $$->pubtable->whereClause = $4; } - | TABLES IN_P SCHEMA ColId + | TABLES IN_P SCHEMA ColId opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_SCHEMA; $$->name = $4; + $$->except_tables = $5; $$->location = @4; } - | TABLES IN_P SCHEMA CURRENT_SCHEMA + | TABLES IN_P SCHEMA CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_CUR_SCHEMA; + $$->except_tables = $5; $$->location = @4; } - | ColId opt_column_list OptWhereClause + | ColId opt_column_list OptWhereClause opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $4; /* * If either a row filter or column list is specified, create * a PublicationTable object. @@ -11392,10 +11395,11 @@ PublicationObjSpec: $$->pubtable->columns = $2; $$->pubtable->whereClause = $3; } - | CURRENT_SCHEMA + | CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $2; $$->location = @1; } ; @@ -20784,11 +20788,14 @@ preprocess_pub_all_objtype_list(List *all_objects_list, List **pubobjects, /* * Process pubobjspec_list to check for errors in any of the objects and * convert PUBLICATIONOBJ_CONTINUATION into appropriate PublicationObjSpecType. + * Also flattens except_tables from TABLES IN SCHEMA nodes into the list so + * that ObjectsInPublicationToOids() sees them as top-level EXCEPT_TABLE entries. */ static void preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) { ListCell *cell; + ListCell *lc; PublicationObjSpec *pubobj; PublicationObjSpecType prevobjtype = PUBLICATIONOBJ_CONTINUATION; @@ -20812,6 +20819,13 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLE) { + /* EXCEPT is not valid for table objects */ + if (pubobj->except_tables != NIL) + ereport(ERROR, + errcode(ERRCODE_SYNTAX_ERROR), + errmsg("EXCEPT is not allowed for TABLE publication objects"), + parser_errposition(pubobj->location)); + /* relation name or pubtable must be set for this type of object */ if (!pubobj->name && !pubobj->pubtable) ereport(ERROR, @@ -20860,6 +20874,35 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) errcode(ERRCODE_SYNTAX_ERROR), errmsg("invalid schema name"), parser_errposition(pubobj->location)); + + /* Flatten EXCEPT entries into the top-level list */ + foreach(lc, pubobj->except_tables) + { + PublicationObjSpec *eobj = (PublicationObjSpec *) lfirst(lc); + + /* + * Unqualified names are implicitly qualified with the parent + * schema. Qualified names must match the parent schema — + * each EXCEPT clause is bound to exactly one schema, so + * cross-schema entries are rejected at parse time. + */ + if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLES_IN_SCHEMA) + { + if (eobj->pubtable->relation->schemaname == NULL) + eobj->pubtable->relation->schemaname = pubobj->name; + else if (strcmp(eobj->pubtable->relation->schemaname, + pubobj->name) != 0) + ereport(ERROR, + errcode(ERRCODE_SYNTAX_ERROR), + errmsg("table \"%s.%s\" in EXCEPT clause does not belong to schema \"%s\"", + eobj->pubtable->relation->schemaname, + eobj->pubtable->relation->relname, + pubobj->name), + parser_errposition(eobj->location)); + } + } + pubobjspec_list = list_concat(pubobjspec_list, pubobj->except_tables); + pubobj->except_tables = NIL; } prevobjtype = pubobj->pubobjtype; diff --git a/src/backend/replication/pgoutput/pgoutput.c b/src/backend/replication/pgoutput/pgoutput.c index 4ecfcbff7ab..942ddb51d3a 100644 --- a/src/backend/replication/pgoutput/pgoutput.c +++ b/src/backend/replication/pgoutput/pgoutput.c @@ -2097,6 +2097,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) * are absorbed while decoding WAL. */ List *schemaPubids = GetSchemaPublications(schemaId); + List *schemaExceptPubids; ListCell *lc; Oid publish_as_relid = relid; int publish_ancestor_level = 0; @@ -2104,6 +2105,25 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) char relkind = get_rel_relkind(relid); List *rel_publications = NIL; + /* + * For the schema EXCEPT check, we must look up the top-most ancestor + * rather than the relation itself. check_publication_add_relation() + * prevents individual partitions from appearing in the EXCEPT clause, + * so only a root (non-partition) table can have prexcept = true. + * Using the partition's own OID would always return NIL and miss the + * exclusion. + */ + if (am_partition) + { + List *pancestore = get_partition_ancestors(relid); + + schemaExceptPubids = + GetRelationExcludedPublications(llast_oid(pancestore)); + list_free(pancestore); + } + else + schemaExceptPubids = GetRelationExcludedPublications(relid); + /* Reload publications if needed before use. */ if (!publications_valid) { @@ -2269,7 +2289,15 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) ancestors, &level); - if (ancestor != InvalidOid) + /* + * The ancestor is only considered published if it is not + * in the EXCEPT clause of this schema publication. + * GetTopMostAncestorInPublication checks schema + * membership but does not account for the EXCEPT list, so + * we must filter that out here. + */ + if (ancestor != InvalidOid && + !list_member_oid(schemaExceptPubids, pub->oid)) { ancestor_published = true; if (pub->pubviaroot) @@ -2281,7 +2309,8 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) } if (list_member_oid(pubids, pub->oid) || - list_member_oid(schemaPubids, pub->oid) || + (list_member_oid(schemaPubids, pub->oid) && + !list_member_oid(schemaExceptPubids, pub->oid)) || ancestor_published) publish = true; } @@ -2360,6 +2389,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) list_free(pubids); list_free(schemaPubids); + list_free(schemaExceptPubids); list_free(rel_publications); entry->replicate_valid = true; diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c index e1449654f96..e5b1a70e05e 100644 --- a/src/bin/psql/describe.c +++ b/src/bin/psql/describe.c @@ -7038,6 +7038,24 @@ describePublications(const char *pattern) if (!addFooterToPublicationDesc(&buf, _("Tables from schemas:"), true, &cont)) goto error_return; + + if (pset.sversion >= 190000) + { + /* + * Get tables in the EXCEPT clause for this schema + * publication. + */ + printfPQExpBuffer(&buf, + "SELECT concat(c.relnamespace::regnamespace, '.', c.relname)\n" + "FROM pg_catalog.pg_class c\n" + " JOIN pg_catalog.pg_publication_rel pr ON c.oid = pr.prrelid\n" + "WHERE pr.prpubid = '%s'\n" + " AND pr.prexcept\n" + "ORDER BY 1", pubid); + if (!addFooterToPublicationDesc(&buf, _("Except tables:"), + true, &cont)) + goto error_return; + } } } else diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index db65d130fcb..6c9c7552627 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -1064,6 +1064,15 @@ static const SchemaQuery Query_for_trigger_of_table = { "SELECT nspname FROM pg_catalog.pg_namespace "\ " WHERE nspname LIKE '%s'" +#define Query_for_list_of_tables_in_schema \ +"SELECT n.nspname || '.' || c.relname "\ +" FROM pg_catalog.pg_class c "\ +" JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "\ +" WHERE c.relkind IN (" CppAsString2(RELKIND_RELATION) ", " \ + CppAsString2(RELKIND_PARTITIONED_TABLE) ") "\ +" AND (n.nspname || '.' || c.relname) LIKE '%s' "\ +" AND n.nspname = '%s'" + /* Use COMPLETE_WITH_QUERY_VERBATIM with these queries for GUC names: */ #define Query_for_list_of_alter_system_set_vars \ "SELECT pg_catalog.lower(name) FROM pg_catalog.pg_settings "\ @@ -3784,8 +3793,32 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); - else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && (!ends_with(prev_wd, ','))) - COMPLETE_WITH("WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE", "WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + if (strchr(previous_words[3], ',') == NULL) + { + set_completion_reference(previous_words[3]); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + } + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && ends_with(prev_wd, ',')) + { + char *schema_word = previous_words[previous_words_count - 8]; + + if (strchr(schema_word, ',') == NULL) + { + set_completion_reference(schema_word); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + } + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* Complete "CREATE PUBLICATION <name> [...] WITH" */ else if (Matches("CREATE", "PUBLICATION", MatchAnyN, "WITH", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h index 91377a6cde3..a9177de0d43 100644 --- a/src/include/nodes/parsenodes.h +++ b/src/include/nodes/parsenodes.h @@ -4493,6 +4493,7 @@ typedef struct PublicationObjSpec PublicationObjSpecType pubobjtype; /* type of this publication object */ char *name; PublicationTable *pubtable; + List *except_tables; /* tables to exclude (for TABLES IN SCHEMA) */ ParseLoc location; /* token location, or -1 if unknown */ } PublicationObjSpec; diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 0345f6c5e47..e78192edd01 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -470,7 +470,61 @@ HINT: Change the publication's EXCEPT clause using ALTER PUBLICATION ... SET AL RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + Publication testpub_schema_except1 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- Exclude multiple tables using unqualified names (implicitly qualified with the schema) +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + Publication testpub_schema_except2 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_nopk" + "pub_test.testpub_tbl_s1" + +-- fail: EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2 EXCEPT (TABLE pub_test.testpub_nopk); +ERROR: EXCEPT is not allowed for TABLE publication objects +LINE 2: FOR TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2 EXCEPT... + ^ +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testp... + ^ +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); +ERROR: table "pub_test.testpub_tbl_s1" in EXCEPT clause does not belong to schema "public" +LINE 2: ...R TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.t... + ^ +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2; CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; -- FOR ALL SEQUENCES diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 041e14a4de6..9120902dfac 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -220,7 +220,40 @@ RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); + +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + +-- Exclude multiple tables using unqualified names (implicitly qualified with the schema) +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + +-- fail: EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2 EXCEPT (TABLE pub_test.testpub_nopk); + +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); + +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2; + CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 8c58d282eee..d2b1fb8f9ff 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -24,14 +24,16 @@ my $result; sub test_except_root_partition { - my ($pubviaroot) = @_; + my ($pubviaroot, $pubsql) = @_; + $pubsql //= + "CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1) WITH (publish_via_partition_root = $pubviaroot)"; # If the root partitioned table is in the EXCEPT clause, all its # partitions are excluded from publication, regardless of the # publish_via_partition_root setting. $node_publisher->safe_psql( 'postgres', qq( - CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1) WITH (publish_via_partition_root = $pubviaroot); + $pubsql; INSERT INTO root1 VALUES (1), (101); )); $node_subscriber->safe_psql('postgres', @@ -223,6 +225,138 @@ $node_subscriber->safe_psql( test_except_root_partition('false'); test_except_root_partition('true'); +# Same validation using TABLES IN SCHEMA instead of FOR ALL TABLES. +my $schema_pub = + "CREATE PUBLICATION tap_pub_part FOR TABLES IN SCHEMA public EXCEPT (TABLE public.root1)"; +test_except_root_partition('false', + "$schema_pub WITH (publish_via_partition_root = false)"); +test_except_root_partition('true', + "$schema_pub WITH (publish_via_partition_root = true)"); + +# ============================================ +# EXCEPT test cases for TABLES IN SCHEMA +# ============================================ + +# Create a dedicated schema with two tables: one to be published and one to be +# excluded. Also create inherited tables to verify ONLY semantics. +$node_publisher->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_pub AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.tab_exc AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.par (a int); + CREATE TABLE sch1.chi (b int) INHERITS (sch1.par); +)); + +$node_subscriber->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_pub (a int); + CREATE TABLE sch1.tab_exc (a int); + CREATE TABLE sch1.par (a int); + CREATE TABLE sch1.chi (b int) INHERITS (sch1.par); +)); + +# Basic test: initial sync respects EXCEPT. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_exc)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_pub"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: initial sync copies included table'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_exc"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: initial sync skips excluded table'); + +# DML: only the included table should be replicated. +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_pub VALUES (6); + INSERT INTO sch1.tab_exc VALUES (6); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_pub"); +is($result, qq(6), + 'TABLES IN SCHEMA EXCEPT: DML on included table is replicated'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_exc"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: DML on excluded table is not replicated'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Inherited tables: excluding the parent (without ONLY) also excludes the child. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.par)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.chi VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.chi"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: excluding parent (without ONLY) also excludes child' +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Truncate chi on the publisher so the next test starts with a clean slate. +# (The previous test inserted rows into chi that would otherwise be copied by +# the initial table sync of the next subscription.) +$node_publisher->safe_psql('postgres', 'TRUNCATE sch1.chi'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE sch1.chi'); +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE ONLY sch1.par)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.chi VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.chi"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: ONLY parent in EXCEPT does not exclude child' +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); +$node_publisher->safe_psql('postgres', + 'TRUNCATE sch1.par, sch1.chi, sch1.tab_exc'); +$node_subscriber->safe_psql('postgres', + 'TRUNCATE sch1.par, sch1.chi, sch1.tab_pub, sch1.tab_exc'); + +# Cleanup schema tables before the multi-publication section. +$node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); +$node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); + # ============================================ # Test when a subscription is subscribing to multiple publications # ============================================ @@ -254,6 +388,7 @@ $node_publisher->safe_psql( DROP PUBLICATION tap_pub2; TRUNCATE tab1; )); +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_subscriber->safe_psql('postgres', qq(TRUNCATE tab1)); # OK when a table is excluded by pub1 EXCEPT clause, but it is included by pub2 -- 2.50.1 (Apple Git-155)
v5-0002-Add-EXCEPT-support-to-ALTER-PUBLICATION-ADD-TABLE.patch (application/octet-stream, 19.8K) download From d91ac2d3b13b9ea011f03d0b48c0476cc3c186b0 Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Mon, 4 May 2026 13:13:42 +0530 Subject: [PATCH v5 2/3] Add EXCEPT support to ALTER PUBLICATION ADD TABLES IN SCHEMA Extend the EXCEPT clause support to allow tables to be excluded when adding a schema to a publication via ALTER PUBLICATION ... ADD: Syntax: ALTER PUBLICATION pub ADD TABLES IN SCHEMA s EXCEPT (TABLE s.t1); Since pg_dump uses ALTER PUBLICATION ... ADD, support for it is included in this patch. --- doc/src/sgml/ref/alter_publication.sgml | 42 +++++++- src/backend/commands/publicationcmds.c | 113 +++++++++++++++++++++- src/bin/pg_dump/pg_dump.c | 30 +++++- src/bin/pg_dump/t/002_pg_dump.pl | 36 +++++++ src/bin/psql/tab-complete.in.c | 28 ++++++ src/test/regress/expected/publication.out | 18 +++- src/test/regress/sql/publication.sql | 11 ++- src/test/subscription/t/037_except.pl | 28 ++++++ 8 files changed, 301 insertions(+), 5 deletions(-) diff --git a/doc/src/sgml/ref/alter_publication.sgml b/doc/src/sgml/ref/alter_publication.sgml index aa32bb169e9..8aedfd951a5 100644 --- a/doc/src/sgml/ref/alter_publication.sgml +++ b/doc/src/sgml/ref/alter_publication.sgml @@ -31,7 +31,7 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -54,6 +54,10 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <phrase>and <replaceable class="parameter">table_object</replaceable> is:</phrase> [ ONLY ] <replaceable class="parameter">table_name</replaceable> [ * ] + +<phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> + + [ ONLY ] <replaceable class="parameter">table_name</replaceable> [ * ] </synopsis> </refsynopsisdiv> @@ -110,6 +114,15 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <literal>ADD TABLE</literal>. </para> + <para> + The <literal>EXCEPT</literal> clause can be used with + <literal>ADD TABLES IN SCHEMA</literal> to exclude specific tables from a + schema-level publication. <literal>EXCEPT</literal> is not supported with + <literal>DROP TABLES IN SCHEMA</literal>; instead, dropping a schema from + the publication automatically removes all of its associated + <literal>EXCEPT</literal> entries. + </para> + <para> The fourth variant of this command listed in the synopsis can change all of the publication properties specified in @@ -198,6 +211,23 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r </listitem> </varlistentry> + <varlistentry> + <term><literal>EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] )</literal></term> + <listitem> + <para> + Specifies tables to be excluded from a schema-level publication entry. + This clause may be used with <literal>ADD TABLES IN SCHEMA</literal> + and not with <literal>DROP TABLES IN SCHEMA</literal>. Each named + table must belong to the schema specified in the same + <literal>TABLES IN SCHEMA</literal> clause. Table names may be + schema-qualified or unqualified; unqualified names are implicitly + qualified with the schema named in the same clause. See + <xref linkend="sql-createpublication"/> for further details on the + semantics of <literal>EXCEPT</literal>. + </para> + </listitem> + </varlistentry> + <varlistentry> <term><literal>SET ( <replaceable class="parameter">publication_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] )</literal></term> <listitem> @@ -288,6 +318,16 @@ ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA marketing, sales; </programlisting> </para> + <para> + Add schema <structname>sales</structname> to the publication + <structname>sales_publication</structname>, excluding the + <structname>sales.internal</structname> and + <structname>sales.drafts</structname> tables: +<programlisting> +ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA sales EXCEPT (TABLE sales.internal, sales.drafts); +</programlisting> + </para> + <para> Add tables <structname>users</structname>, <structname>departments</structname> and schema diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index dfe3e1f9706..858c0d0944d 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -70,6 +70,9 @@ static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok); static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); +static void AlterPublicationExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, List *exceptrelations, + List *schemaidlist); static char defGetGeneratedColsOption(DefElem *def); @@ -1528,6 +1531,13 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, } PublicationAddSchemas(pubform->oid, schemaidlist, false, stmt); + + /* + * Increment the command counter so that is_schema_publication() in + * GetExcludedPublicationTables() can see the just-inserted schema + * rows when AlterPublicationExceptTables runs next. + */ + CommandCounterIncrement(); } else if (stmt->action == AP_DropObjects) PublicationDropSchemas(pubform->oid, schemaidlist, false); @@ -1553,6 +1563,100 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, * skip existing ones when doing catalog update. */ PublicationAddSchemas(pubform->oid, schemaidlist, true, stmt); + + /* + * Increment the command counter so that is_schema_publication() in + * GetExcludedPublicationTables() can see the just-inserted schema + * rows when AlterPublicationExceptTables runs next. + */ + CommandCounterIncrement(); + } +} + +/* + * Alter the EXCEPT list of a publication. + * + * Adds, removes, or replaces except-table entries in pg_publication_rel + * (rows with prexcept = true). These entries suppress publication of the + * named tables that would otherwise be covered by a FOR TABLES IN SCHEMA + * or FOR ALL TABLES clause. + */ +static void +AlterPublicationExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, List *exceptrelations, + List *schemaidlist) +{ + Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); + Oid pubid = pubform->oid; + + /* + * Nothing to do if no EXCEPT entries. + */ + if (!exceptrelations) + return; + + /* + * This function handles EXCEPT entries for schema-level publications + * only. For FOR ALL TABLES publications, EXCEPT entries are already + * processed by AlterPublicationTables(). + */ + if (schemaidlist == NIL && !is_schema_publication(pubid)) + return; + + /* + * EXCEPT is not meaningful with DROP: dropping a schema from a + * publication already removes all its except entries via cascade, and + * there is no sensible interpretation of "drop only the except entry but + * keep the schema". + */ + if (stmt->action == AP_DropObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); + + /* + * EXCEPT with SET is not supported: SET replaces the schema list but does + * not have a well-defined semantics for merging or replacing existing + * except entries. Users should DROP and re-ADD the schema with the + * desired EXCEPT list instead. + */ + if (stmt->action == AP_SetObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"))); + + if (stmt->action == AP_AddObjects) + { + List *rels; + List *explicitrelids; + ListCell *lc; + + rels = OpenTableList(exceptrelations); + + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + /* + * Validate that each excluded table is not also in the explicit table + * list (which would be contradictory). + */ + foreach(lc, rels) + { + PublicationRelInfo *pri = (PublicationRelInfo *) lfirst(lc); + Oid relid = RelationGetRelid(pri->relation); + Oid relns = RelationGetNamespace(pri->relation); + + if (list_member_oid(explicitrelids, relid)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s.%s\" cannot appear in both the table list and the EXCEPT clause", + get_namespace_name(relns), + RelationGetRelationName(pri->relation))); + } + + PublicationAddTables(pubid, rels, false, stmt); + + CloseTableList(rels); } } @@ -1763,10 +1867,17 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) errmsg("publication \"%s\" does not exist", stmt->pubname)); - relations = list_concat(relations, exceptrelations); + /* + * For FOR ALL TABLES, EXCEPT entries are processed by + * AlterPublicationTables(), so merge them in. For TABLES IN SCHEMA, + * they are handled separately by AlterPublicationExceptTables(). + */ + if (stmt->for_all_tables) + relations = list_concat(relations, exceptrelations); AlterPublicationTables(stmt, tup, relations, pstate->p_sourcetext, schemaidlist != NIL); AlterPublicationSchemas(stmt, tup, schemaidlist); + AlterPublicationExceptTables(stmt, tup, exceptrelations, schemaidlist); AlterPublicationAllFlags(stmt, rel, tup); } diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c index d56dcc701ce..e62d74c8ca0 100644 --- a/src/bin/pg_dump/pg_dump.c +++ b/src/bin/pg_dump/pg_dump.c @@ -5019,6 +5019,7 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) PublicationInfo *pubinfo = pubsinfo->publication; PQExpBuffer query; char *tag; + bool has_except = false; /* Do nothing if not dumping schema */ if (!dopt->dumpSchema) @@ -5029,7 +5030,34 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) query = createPQExpBuffer(); appendPQExpBuffer(query, "ALTER PUBLICATION %s ", fmtId(pubinfo->dobj.name)); - appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s;\n", fmtId(schemainfo->dobj.name)); + appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s", fmtId(schemainfo->dobj.name)); + + /* + * Append EXCEPT clause for any tables that belong to this schema + * and are excluded from the publication. + */ + for (SimplePtrListCell *cell = pubinfo->except_tables.head; cell; cell = cell->next) + { + TableInfo *tbinfo = (TableInfo *) cell->ptr; + + if (strcmp(tbinfo->dobj.namespace->dobj.name, schemainfo->dobj.name) == 0) + { + if (!has_except) + { + appendPQExpBufferStr(query, " EXCEPT ("); + has_except = true; + } + else + appendPQExpBufferStr(query, ", "); + + appendPQExpBuffer(query, "TABLE ONLY %s", fmtId(tbinfo->dobj.name)); + } + } + + if (has_except) + appendPQExpBufferStr(query, ")"); + + appendPQExpBufferStr(query, ";\n"); /* * There is no point in creating drop query as the drop is done by schema diff --git a/src/bin/pg_dump/t/002_pg_dump.pl b/src/bin/pg_dump/t/002_pg_dump.pl index 3bc8e51561d..3ed0595ca39 100644 --- a/src/bin/pg_dump/t/002_pg_dump.pl +++ b/src/bin/pg_dump/t/002_pg_dump.pl @@ -3242,6 +3242,42 @@ my %tests = ( like => { %full_runs, section_post_data => 1, }, }, + 'CREATE PUBLICATION pub11' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub11 FOR TABLES IN SCHEMA dump_test EXCEPT (TABLE dump_test.test_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub11 WITH (publish = 'insert, update, delete, truncate');\E + /xm, + like => { %full_runs, section_post_data => 1, }, + }, + + 'ALTER PUBLICATION pub11 ADD TABLES IN SCHEMA dump_test EXCEPT (dump_test.test_table)' + => { + regexp => qr/^ + \QALTER PUBLICATION pub11 ADD TABLES IN SCHEMA dump_test EXCEPT (TABLE ONLY test_table);\E + /xm, + like => { %full_runs, section_post_data => 1, }, + }, + + 'CREATE PUBLICATION pub12' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub12 FOR TABLES IN SCHEMA dump_test EXCEPT (TABLE dump_test.test_table, dump_test.test_second_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub12 WITH (publish = 'insert, update, delete, truncate');\E + /xm, + like => { %full_runs, section_post_data => 1, }, + }, + + 'ALTER PUBLICATION pub12 ADD TABLES IN SCHEMA dump_test EXCEPT (dump_test.test_table, dump_test.test_second_table)' + => { + regexp => qr/^ + \QALTER PUBLICATION pub12 ADD TABLES IN SCHEMA dump_test EXCEPT (TABLE ONLY test_table, TABLE ONLY test_second_table);\E + /xm, + like => { %full_runs, section_post_data => 1, }, + }, + 'CREATE SUBSCRIPTION sub1' => { create_order => 50, create_sql => 'CREATE SUBSCRIPTION sub1 diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index 6c9c7552627..c930c6c672e 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2363,6 +2363,34 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); + /* After a single schema name in ADD context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + if (strchr(previous_words[3], ',') == NULL) + { + set_completion_reference(previous_words[3]); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && ends_with(prev_wd, ',')) + { + char *schema_word = previous_words[previous_words_count - 8]; + + if (strchr(schema_word, ',') == NULL) + { + set_completion_reference(schema_word); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index e78192edd01..ca163b2bb01 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -522,9 +522,25 @@ CREATE PUBLICATION testpub_except_crossschema ERROR: table "pub_test.testpub_tbl_s1" in EXCEPT clause does not belong to schema "public" LINE 2: ...R TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.t... ^ +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; +-- ADD: add a schema with an excepted table +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_alter_except; CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; -- FOR ALL SEQUENCES diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 9120902dfac..3a9a9e403f8 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -250,9 +250,18 @@ CREATE PUBLICATION testpub_except_wrongschema CREATE PUBLICATION testpub_except_crossschema FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; + +-- ADD: add a schema with an excepted table +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_alter_except + RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_alter_except; CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index d2b1fb8f9ff..64f0e2173b2 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -353,6 +353,34 @@ $node_publisher->safe_psql('postgres', $node_subscriber->safe_psql('postgres', 'TRUNCATE sch1.par, sch1.chi, sch1.tab_pub, sch1.tab_exc'); +# ============================================ +# ALTER PUBLICATION EXCEPT for TABLES IN SCHEMA +# ============================================ + +# ADD: add a schema with an excepted table; verify the except entry takes effect. +$node_publisher->safe_psql('postgres', "CREATE PUBLICATION sch_pub"); +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub ADD TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_exc)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_pub"); +is($result, qq(6), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: included table synced'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_exc"); +is($result, qq(0), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + # Cleanup schema tables before the multi-publication section. $node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); $node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); -- 2.50.1 (Apple Git-155)
v5-0003-Add-EXCEPT-support-to-ALTER-PUBLICATION-SET-TABLE.patch (application/octet-stream, 20.8K) download From e842059fd819dfb91a9948d185076d1532f205df Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Mon, 27 Apr 2026 13:22:38 +0530 Subject: [PATCH v5 3/3] Add EXCEPT support to ALTER PUBLICATION SET TABLES IN SCHEMA Extend AlterPublicationExceptTables() with the AP_SetObjects case, which redefine the publication and replaces the entire EXCEPT list. Syntax: ALTER PUBLICATION pub SET TABLES IN SCHEMA s EXCEPT (TABLE t1); This patch also cleans up EXCEPT entries when a schema is dropped from the publication. --- doc/src/sgml/ref/alter_publication.sgml | 36 ++++-- src/backend/catalog/pg_publication.c | 2 +- src/backend/commands/publicationcmds.c | 145 ++++++++++++++++++++-- src/bin/psql/tab-complete.in.c | 28 +++++ src/test/regress/expected/publication.out | 20 +++ src/test/regress/sql/publication.sql | 10 ++ src/test/subscription/t/037_except.pl | 90 ++++++++++++++ 7 files changed, 305 insertions(+), 26 deletions(-) diff --git a/doc/src/sgml/ref/alter_publication.sgml b/doc/src/sgml/ref/alter_publication.sgml index 8aedfd951a5..1b73b34e43a 100644 --- a/doc/src/sgml/ref/alter_publication.sgml +++ b/doc/src/sgml/ref/alter_publication.sgml @@ -54,10 +54,6 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <phrase>and <replaceable class="parameter">table_object</replaceable> is:</phrase> [ ONLY ] <replaceable class="parameter">table_name</replaceable> [ * ] - -<phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> - - [ ONLY ] <replaceable class="parameter">table_name</replaceable> [ * ] </synopsis> </refsynopsisdiv> @@ -97,7 +93,11 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r used with a publication defined with <literal>FOR TABLE</literal> or <literal>FOR TABLES IN SCHEMA</literal>, replaces the list of tables/schemas in the publication with the specified list; the existing tables or schemas - that were present in the publication will be removed. + that were present in the publication will be removed. When + <literal>SET TABLES IN SCHEMA</literal> is used with an + <literal>EXCEPT</literal> clause, the excluded tables for each schema are + replaced with the specified list; if <literal>EXCEPT</literal> is omitted + for a schema, any existing exclusions for that schema are cleared. </para> <para> @@ -116,7 +116,8 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <para> The <literal>EXCEPT</literal> clause can be used with - <literal>ADD TABLES IN SCHEMA</literal> to exclude specific tables from a + <literal>ADD TABLES IN SCHEMA</literal> and + <literal>SET TABLES IN SCHEMA</literal> to exclude specific tables from a schema-level publication. <literal>EXCEPT</literal> is not supported with <literal>DROP TABLES IN SCHEMA</literal>; instead, dropping a schema from the publication automatically removes all of its associated @@ -217,12 +218,12 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <para> Specifies tables to be excluded from a schema-level publication entry. This clause may be used with <literal>ADD TABLES IN SCHEMA</literal> - and not with <literal>DROP TABLES IN SCHEMA</literal>. Each named - table must belong to the schema specified in the same - <literal>TABLES IN SCHEMA</literal> clause. Table names may be - schema-qualified or unqualified; unqualified names are implicitly - qualified with the schema named in the same clause. See - <xref linkend="sql-createpublication"/> for further details on the + and <literal>SET TABLES IN SCHEMA</literal>, and not with + <literal>DROP TABLES IN SCHEMA</literal>. Each named table must belong + to the schema specified in the same <literal>TABLES IN SCHEMA</literal> + clause. Table names may be schema-qualified or unqualified; unqualified + names are implicitly qualified with the schema named in the same clause. + See <xref linkend="sql-createpublication"/> for further details on the semantics of <literal>EXCEPT</literal>. </para> </listitem> @@ -328,6 +329,17 @@ ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA sales EXCEPT (TABLE sal </programlisting> </para> + <para> + Replace the schema list of <structname>sales_publication</structname> with + <structname>sales</structname>, excluding only + <structname>sales.drafts</structname> (any previously excluded tables for + that schema are replaced, and schemas previously in the publication are + removed): +<programlisting> +ALTER PUBLICATION sales_publication SET TABLES IN SCHEMA sales EXCEPT (TABLE sales.drafts); +</programlisting> + </para> + <para> Add tables <structname>users</structname>, <structname>departments</structname> and schema diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index 85c2528873f..e63f221f1af 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -1002,7 +1002,7 @@ GetIncludedPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) List * GetExcludedPublicationTables(Oid pubid, PublicationPartOpt pub_partopt) { - Assert(GetPublication(pubid)->alltables); + Assert(GetPublication(pubid)->alltables || is_schema_publication(pubid)); return get_publication_relations(pubid, pub_partopt, true); } diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 858c0d0944d..96f653c5e95 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -1590,9 +1590,11 @@ AlterPublicationExceptTables(AlterPublicationStmt *stmt, Oid pubid = pubform->oid; /* - * Nothing to do if no EXCEPT entries. + * Nothing to do if no EXCEPT entries, except in SET: for that it is quite + * possible that the user has removed all exceptions, in which case we + * need to drop any existing ones. */ - if (!exceptrelations) + if (!exceptrelations && stmt->action != AP_SetObjects) return; /* @@ -1614,17 +1616,6 @@ AlterPublicationExceptTables(AlterPublicationStmt *stmt, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); - /* - * EXCEPT with SET is not supported: SET replaces the schema list but does - * not have a well-defined semantics for merging or replacing existing - * except entries. Users should DROP and re-ADD the schema with the - * desired EXCEPT list instead. - */ - if (stmt->action == AP_SetObjects) - ereport(ERROR, - (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"))); - if (stmt->action == AP_AddObjects) { List *rels; @@ -1656,6 +1647,95 @@ AlterPublicationExceptTables(AlterPublicationStmt *stmt, PublicationAddTables(pubid, rels, false, stmt); + CloseTableList(rels); + } + else /* AP_SetObjects */ + { + List *oldexceptrelids = NIL; + List *newexceptrelids = NIL; + List *delrelids = NIL; + List *rels; + List *explicitrelids; + ListCell *lc; + + rels = OpenTableList(exceptrelations); + + /* Collect OIDs of the desired new except list. */ + foreach(lc, rels) + { + PublicationRelInfo *pri = (PublicationRelInfo *) lfirst(lc); + + newexceptrelids = lappend_oid(newexceptrelids, + RelationGetRelid(pri->relation)); + } + + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + /* + * Validate that each excluded table is not also in the explicit table + * list (which would be contradictory). + */ + foreach(lc, rels) + { + PublicationRelInfo *pri = (PublicationRelInfo *) lfirst(lc); + Oid relid = RelationGetRelid(pri->relation); + Oid relns = RelationGetNamespace(pri->relation); + + if (list_member_oid(explicitrelids, relid)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s.%s\" cannot appear in both the table list and the EXCEPT clause", + get_namespace_name(relns), + RelationGetRelationName(pri->relation))); + } + + /* + * Get the current set of except entries. Only FOR ALL TABLES and + * schema-level publications can have except entries; for any other + * publication type oldexceptrelids stays NIL. + * + * Note: we check is_schema_publication() against the current catalog + * state (before AlterPublicationSchemas has run), so if the caller is + * doing SET TABLE t1 to convert a schema publication into a plain + * table publication, is_schema_publication() still returns true here. + * That is intentional: it lets us discover and clean up any stale + * except entries that belong to the old schema definition. + */ + if (GetPublication(pubid)->alltables || is_schema_publication(pubid)) + oldexceptrelids = GetExcludedPublicationTables(pubid, + PUBLICATION_PART_ROOT); + + /* Build a list of old except entries not present in the new list. */ + foreach(lc, oldexceptrelids) + { + Oid oldrelid = lfirst_oid(lc); + + if (!list_member_oid(newexceptrelids, oldrelid)) + delrelids = lappend_oid(delrelids, oldrelid); + } + + /* Drop old except entries not present in the new list. */ + foreach(lc, delrelids) + { + Oid relid = lfirst_oid(lc); + Oid proid; + ObjectAddress obj; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (!OidIsValid(proid)) + continue; /* already gone */ + + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + + /* Add new except entries, skipping any already present. */ + PublicationAddTables(pubid, rels, true, stmt); + CloseTableList(rels); } } @@ -2310,6 +2390,8 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) foreach(lc, schemas) { Oid schemaid = lfirst_oid(lc); + List *exceptoids; + ListCell *elc; psid = GetSysCacheOid2(PUBLICATIONNAMESPACEMAP, Anum_pg_publication_namespace_oid, @@ -2326,8 +2408,45 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) get_namespace_name(schemaid)))); } + /* + * Collect prexcept rows for tables belonging to this schema before + * removing the schema entry. GetExcludedPublicationTables relies on + * is_schema_publication(), which scans pg_publication_namespace; if + * this is the last schema in the publication, performDeletion() below + * would remove that row and make is_schema_publication() return + * false, tripping the assertion. + */ + exceptoids = GetExcludedPublicationTables(pubid, PUBLICATION_PART_ROOT); + ObjectAddressSet(obj, PublicationNamespaceRelationId, psid); performDeletion(&obj, DROP_CASCADE, 0); + + /* + * Drop any prexcept rows for tables belonging to this schema. These + * rows have no pg_depend entry pointing at the + * pg_publication_namespace row, so they are not cascaded by the + * performDeletion() call above and must be cleaned up explicitly. + */ + foreach(elc, exceptoids) + { + Oid relid = lfirst_oid(elc); + Oid proid; + + if (get_rel_namespace(relid) != schemaid) + continue; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (!OidIsValid(proid)) + continue; /* already gone */ + + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + + list_free(exceptoids); } } diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index c930c6c672e..5afcce87f72 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2391,6 +2391,34 @@ match_previous_words(int pattern_id, } else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) COMPLETE_WITH(")"); + /* After a single schema name in SET context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + if (strchr(previous_words[3], ',') == NULL) + { + set_completion_reference(previous_words[3]); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && ends_with(prev_wd, ',')) + { + char *schema_word = previous_words[previous_words_count - 8]; + + if (strchr(schema_word, ',') == NULL) + { + set_completion_reference(schema_word); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index ca163b2bb01..5b6bf3bbddd 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -538,6 +538,26 @@ Tables from schemas: Except tables: "pub_test.testpub_tbl_s1" +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s2" + +-- error: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +ERROR: EXCEPT clause is not supported with DROP in ALTER PUBLICATION +-- error: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 1: ...xcept SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.tes... + ^ RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_alter_except; diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 3a9a9e403f8..fdc6940c87d 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -259,6 +259,16 @@ CREATE PUBLICATION testpub_alter_except; ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); \dRp+ testpub_alter_except +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + +-- error: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); + +-- error: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_alter_except; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 64f0e2173b2..580acd74bca 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -378,6 +378,66 @@ $result = is($result, qq(0), 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); +# SET: replace the except list; tab_exc is now included and tab_pub is excluded. +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_pub)" +); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_pub VALUES (7); + INSERT INTO sch1.tab_exc VALUES (7); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_exc"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: newly included table is replicated' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_pub"); +is($result, qq(6), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: now-excluded table is not replicated' +); + +# SET without EXCEPT: clears the except list; both tables are now published. +# tab_pub will be re-synced because REFRESH removed its entry when it was +# excluded. Truncate the subscriber copy beforehand so the re-sync produces +# a predictable count: publisher has 7 rows (6 original + INSERT(7)), so the +# subscriber ends up with 7 after re-sync, then 8 after INSERT(8). +$node_subscriber->safe_psql('postgres', 'TRUNCATE sch1.tab_pub'); +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1"); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_pub VALUES (8); + INSERT INTO sch1.tab_exc VALUES (8); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_pub"); +is($result, qq(8), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_pub replicated after except list cleared' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_exc"); +is($result, qq(2), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_exc replicated after except list cleared' +); + $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); @@ -445,6 +505,36 @@ $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); +# OK when a table is excluded by a TABLES IN SCHEMA EXCEPT publication, +# but is included by another publication. +$node_publisher->safe_psql('postgres', 'TRUNCATE tab1'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE tab1'); + +$node_publisher->safe_psql( + 'postgres', qq( + CREATE PUBLICATION tap_pub1 FOR TABLES IN SCHEMA public EXCEPT (TABLE public.tab1); + CREATE PUBLICATION tap_pub2 FOR TABLE tab1; + INSERT INTO tab1 VALUES(1); +)); +$node_subscriber->psql('postgres', + "CREATE SUBSCRIPTION tap_sub CONNECTION '$publisher_connstr' PUBLICATION tap_pub1, tap_pub2" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'tap_sub'); + +$node_publisher->safe_psql('postgres', qq(INSERT INTO tab1 VALUES(2))); +$node_publisher->wait_for_catchup('tap_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT * FROM tab1 ORDER BY a"); +is( $result, qq(1 +2), + "TABLES IN SCHEMA EXCEPT: table excluded in schema pub but included by another pub is replicated" +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); + $node_publisher->stop('fast'); done_testing(); -- 2.50.1 (Apple Git-155)
^ permalink raw reply [nested|flat] 196+ messages in thread

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-05-15 07:19  Peter Smith <smithpb2250@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  0 siblings, 2 replies; 196+ messages in thread

From: Peter Smith @ 2026-05-15 07:19 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Hi Nisha.

Some review comments for patch v5-0001.

======
doc/src/sgml/ref/create_publication.sgml

(FOR TABLES IN SCHEMA)

1.
+      Tables listed in <literal>EXCEPT</literal> for a given schema are
+      excluded from the publication.

/Tables listed in EXCEPT.../Tables listed in the EXCEPT clause.../

There is a similar problem with the existing *head* docs in the "FOR
ALL TABLES" part. This should be fixed, too.
/Tables listed in EXCEPT clause.../Tables listed in the EXCEPT clause.../

======
src/backend/catalog/pg_publication.c

publication_add_relation:

2.
+ HeapTuple existing;

Not sure if this is the best name. How about "tup"?

~~~

3.
+ bool is_except = existing_form->prexcept;

This variable is used only once. Not sure if that vindicates having it.

~~~

4.
+ ereport(ERROR,
+ (errcode(ERRCODE_DUPLICATE_OBJECT),
+ errmsg("table \"%s.%s\" cannot be added because it is listed in
EXCEPT clause of publication \"%s\"",
+ get_namespace_name(RelationGetNamespace(targetrel)),
+ RelationGetRelationName(targetrel),
+ pub->name)));

4a.
There is a recently committed function which will give the
fully-qualified rel name, so you can use "%s" instead of "%s.%s".

~

4b.
The message seems a bit wordy.

BEFORE
"table \"%s.%s\" cannot be added because it is listed in EXCEPT clause
of publication \"%s\""
SUGGESTION
"table \"%s\" cannot be added because it is excluded from publication \"%s\""

~~~

5.
+ * For ALTER PUBLICATION, invalidation is needed when adding an EXCEPT
+ * table to either: - a FOR ALL TABLES publication (pub->alltables is
+ * true), or - a FOR TABLES IN SCHEMA publication (is_schema_publication
+ * is true).
  *
- * For ALTER PUBLICATION, invalidation is needed only when adding an
- * EXCEPT table to a publication already marked as ALL TABLES. For
- * publications that were originally empty or defined as ALL SEQUENCES and
- * are being converted to ALL TABLES, invalidation is skipped here, as
- * AlterPublicationAllFlags() function invalidates all relations while
- * marking the publication as ALL TABLES publication.
+ * The exception: when a publication is being converted to FOR ALL TABLES
+ * (pub->alltables is still false at this point),
+ * AlterPublicationAllFlags() will perform a full invalidation, so we skip
+ * it here.
  */
- inval_except_table = (alter_stmt != NULL) && pub->alltables &&
- (alter_stmt->for_all_tables && pri->except);
+ inval_except_table = (alter_stmt != NULL) && pri->except &&
+ (pub->alltables
+ ? alter_stmt->for_all_tables
+ : is_schema_publication(pubid));

Is all this comment and logic about "ALTER PUBLICATION" a bit
premature? AFAIK, patch 0001 is not yet doing anything for ALTER
PUBLICATION, so it looks like all this belongs in a later patch.

~~~

GetIncludedPublicationRelations:

6.
- * This should only be used FOR ALL TABLES publications.
+ * This is used for FOR ALL TABLES and FOR TABLES IN SCHEMA publications,
+ * both of which support EXCEPT TABLE.

So, because it might come from 2 places, shouldn't the assert in this
function be modified?

Also, since the assert was not yet modified, how does this even pass
the tests if 'alltables' was false?

~~~

GetAllSchemaPublicationRelations:

7.
+ /* get the list of tables excluded via EXCEPT TABLE for this publication */
+ if (pubschemalist != NIL)
+ exceptlist = get_publication_relations(pubid, pub_partopt, true);
+

Should this be calling 'GetExcludedPublicationTables' instead of
directly calling get_publication_relations?

~~~

8.
+ list_free(schemaRels);
+ }
+ else
+ result = list_concat(result, schemaRels);

Why is 'schemaRels' only being freed when there is an EXCEPT?

======
src/backend/commands/publicationcmds.c

CreatePublication:

9.
  List    *rels;
+ ListCell   *lc;

Looks like this can be declared at a lower scope.

~~~

10.
+ foreach(lc, rels)
+ {
+ PublicationRelInfo *pri = (PublicationRelInfo *) lfirst(lc);
+
+ explicitrelids = lappend_oid(explicitrelids,
+ RelationGetRelid(pri->relation));
+ }

Maybe this loop can be made neater using foreach_ptr().

~~~

11.
+ foreach(lc, rels)
+ {
+ PublicationRelInfo *pri = (PublicationRelInfo *) lfirst(lc);
+ Oid relid = RelationGetRelid(pri->relation);
+ Oid relns = RelationGetNamespace(pri->relation);

11a.
Maybe this loop can be made neater using foreach_ptr().

~

11b.
Maybe 'except_relid' or 'excluded_relid' is a more meaningful varname.

I also felt that some other names are a bit confusing.
- e.g. 'exceptrelations' vs 'rels' ...
  IIUC, both of these are lists of excepted relations/tables, although
  1st is a list of PublicationTable and
  2nd is a list of PublicationRelInfo
~~~

12.
+ ereport(ERROR,
+ errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("table \"%s.%s\" cannot appear in both the table list and the
EXCEPT clause",
+    get_namespace_name(relns),
+    RelationGetRelationName(pri->relation)));

This can make use of a recently committed function that returns the
schem-qualifier relname so you can use "%s" instead of "%s.%s".

======
src/backend/parser/gram.y

13.
- * TABLES IN SCHEMA schema [, ...]
+ * TABLES IN SCHEMA schema [EXCEPT ( table [, ...] )] [, ...]

In the comment just before this one, the FOR ALL TABLES EXCEPT was
written as "[EXCEPT (TABLE table [, ...] )]". So, I think this should
be the same for consistency.

~~~

14.
- | ColId opt_column_list OptWhereClause
+ | ColId opt_column_list OptWhereClause opt_pub_except_clause
  {
  $$ = makeNode(PublicationObjSpec);
  $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION;
+ $$->except_tables = $4;

This seems suspicious. You cannot have an EXCEPT clause when there is
a column list or a WHERE clause, so what is this scenario? Maybe the
"$$->except_tables = $4;" needs to be moved to the 'else' block?

~~~

preprocess_pubobj_list:

15.
+ /* Flatten EXCEPT entries into the top-level list */
+ foreach(lc, pubobj->except_tables)

Maybe the loop can be made neater by using foreach_ptr.

~~~

16.
+ if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLES_IN_SCHEMA)
+ {
+ if (eobj->pubtable->relation->schemaname == NULL)
+ eobj->pubtable->relation->schemaname = pubobj->name;
+ else if (strcmp(eobj->pubtable->relation->schemaname,
+ pubobj->name) != 0)
+ ereport(ERROR,
+ errcode(ERRCODE_SYNTAX_ERROR),
+ errmsg("table \"%s.%s\" in EXCEPT clause does not belong to schema \"%s\"",
+    eobj->pubtable->relation->schemaname,
+    eobj->pubtable->relation->relname,
+    pubobj->name),
+ parser_errposition(eobj->location));

16a.
Introducing some more variables (like 'eobj_schemaname' and
'eobj_relname') would simplify this code quite a bit.

~

16b.
Should make use of the recently committed function that gets
fully-qualified rel names so you can use "%s" instead of "%s.%s".

======
src/backend/replication/pgoutput/pgoutput.c

get_rel_sync_entry:

17.
+ if (am_partition)
+ {
+ List    *pancestore = get_partition_ancestors(relid);
+
+ schemaExceptPubids =
+ GetRelationExcludedPublications(llast_oid(pancestore));
+ list_free(pancestore);
+ }
+ else
+ schemaExceptPubids = GetRelationExcludedPublications(relid);

17a.
Typo? "pancestore" -- what's the 'e'?

~

17b.
Anyway, would it be simpler to just get the Oid up-front?

e.g.
Oid oid_root = llast_oid(get_partition_ancestors(relid));

~~~

18.
+ /*
+ * The ancestor is only considered published if it is not
+ * in the EXCEPT clause of this schema publication.
+ * GetTopMostAncestorInPublication checks schema
+ * membership but does not account for the EXCEPT list, so
+ * we must filter that out here.
+ */

So, then maybe the logic to account for EXCEPT TABLE *should* be
encapsulated within the GetTopMostAncestorInPublication, instead of
the tack-on extra filtering needed here?

======
src/bin/psql/tab-complete.in.c

19.
+ if (strchr(previous_words[3], ',') == NULL)
+ {
+ set_completion_reference(previous_words[3]);
+ COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema);
+ }

IIUC, you are not supposed to reference 'previous_words' directly like
this, so maybe this should be 'prev4_wd'?

~~~

20.
+ char    *schema_word = previous_words[previous_words_count - 8];

This looks suspicious. I don't see similar code to this anywhere else. (??)

======
src/include/nodes/parsenodes.h

21.
+ List    *except_tables; /* tables to exclude (for TABLES IN SCHEMA) */
  ParseLoc location; /* token location, or -1 if unknown */
 } PublicationObjSpec;

Maybe the wording should be worded more like the existing one in
PublicationAllObjSpec.

SUGGESTION
tables specified in the EXCEPT clause (for TABLES IN SCHEMA)


======
src/test/regress/sql/publication.sql

22.
+-- Exclude multiple tables using unqualified names (implicitly
qualified with the schema)
+CREATE PUBLICATION testpub_schema_except2
+    FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1);
+\dRp+ testpub_schema_except2

A slightly more sophisticated test might have those same excluded
table names in the 'public' schema as well as in the schema with the
EXCEPT clause, so then you can verify it is not getting them mixed up.

~~~

23.
+-- fail: EXCEPT is not allowed for FOR TABLE publications
+CREATE PUBLICATION testpub_except_err
+    FOR TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2 EXCEPT (TABLE
pub_test.testpub_nopk);

Hmm. Doesn't this test belong elsewhere instead of in the "EXCEPT
tests for TABLES IN SCHEMA" group?

~~~

24.
MORE TEST CASES (below are in no particular order)

24a.
fail - when a table in the schema EXCEPT clause is also specified by FOR TABLE

~

24b.
fail - when a non-existing table is specified in the EXCEPT clause.

~

24c.
fail - when trying to exclude partitions.

~

24d.
pass - publication with multiple schemas and multiple EXCEPT clauses

~

24e.
fail - when the TABLE keyword is omitted.


======
src/test/subscription/t/037_except.pl

25.
+my $schema_pub =
+  "CREATE PUBLICATION tap_pub_part FOR TABLES IN SCHEMA public EXCEPT
(TABLE public.root1)";
+test_except_root_partition('false',
+ "$schema_pub WITH (publish_via_partition_root = false)");
+test_except_root_partition('true',
+ "$schema_pub WITH (publish_via_partition_root = true)");

The "WITH (publish_via_partition_root = true/false)" part should be
automatically appended within the subroutine, based on the other
boolean parameter.

~~~

26.
+ CREATE TABLE sch1.tab_pub AS SELECT generate_series(1,5) AS a;
+ CREATE TABLE sch1.tab_exc AS SELECT generate_series(1,5) AS a;
+ CREATE TABLE sch1.par (a int);
+ CREATE TABLE sch1.chi (b int) INHERITS (sch1.par);

The abbreviated table names like 'tab_exc', 'par', 'chi' (instead of
'tab_excluded', 'parent', 'child') are not saving much at all, but
they are obfuscating the meaning. Descriptive names would be better,

~~~

27.
+# Truncate chi on the publisher so the next test starts with a clean slate.
+# (The previous test inserted rows into chi that would otherwise be copied by
+# the initial table sync of the next subscription.)

The comment explains the setup, but does not actually say what the
test does -- e.g. you are testing excluding ONLY the parent, so in
this case the child is expected to be replicated.

~~~

28.
+$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub');
+$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub');
+$node_publisher->safe_psql('postgres',
+ 'TRUNCATE sch1.par, sch1.chi, sch1.tab_exc');
+$node_subscriber->safe_psql('postgres',
+ 'TRUNCATE sch1.par, sch1.chi, sch1.tab_pub, sch1.tab_exc');

Are those TRUNCATEs needed? Won't the tables get trashed anyway by
CASCADE in the next ("Cleanup schema tables") part?

======
Kind Regards,
Peter Smith.
Fujitsu Australia





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-05-15 13:32  Nisha Moond <nisha.moond412@gmail.com>
  parent: Peter Smith <smithpb2250@gmail.com>
  1 sibling, 1 reply; 196+ messages in thread

From: Nisha Moond @ 2026-05-15 13:32 UTC (permalink / raw)
  To: Peter Smith <smithpb2250@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Fri, May 15, 2026 at 12:49 PM Peter Smith <smithpb2250@gmail.com> wrote:
>
> Hi Nisha.
>
> Some review comments for patch v5-0001.

Thanks Peter for the review.

>
> ~~~
>
> GetIncludedPublicationRelations:
>
> 6.
> - * This should only be used FOR ALL TABLES publications.
> + * This is used for FOR ALL TABLES and FOR TABLES IN SCHEMA publications,
> + * both of which support EXCEPT TABLE.
>
> So, because it might come from 2 places, shouldn't the assert in this
> function be modified?
>
I think you meant GetExcludedPublicationTables.
Patch-0003 updates the assert in this fuction for schema publications.

> Also, since the assert was not yet modified, how does this even pass
> the tests if 'alltables' was false?
>

As you pointed out in the next (7th) comment also, the first two
patches are not calling GetExcludedPublicationTables(), but are using
get_publication_relations() directly. Hence, the tests are passing
even without the assert modification. But patch-0003 does call it, so
the assert was updated there.

> ~~~
>
> GetAllSchemaPublicationRelations:
>
> 7.
> + /* get the list of tables excluded via EXCEPT TABLE for this publication */
> + if (pubschemalist != NIL)
> + exceptlist = get_publication_relations(pubid, pub_partopt, true);
> +
>
> Should this be calling 'GetExcludedPublicationTables' instead of
> directly calling get_publication_relations?
>

Agreed, I will make the change. With that, the above mentioned assert
will also need to be updated in patch-1 itself.
~~~~

I agree with the rest of the comments and will update and upload the
patches soon.

--
Thanks,
Nisha





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-05-17 01:32  Peter Smith <smithpb2250@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  0 siblings, 0 replies; 196+ messages in thread

From: Peter Smith @ 2026-05-17 01:32 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Fri, May 15, 2026 at 11:32 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
>
...
> > Also, since the assert was not yet modified, how does this even pass
> > the tests if 'alltables' was false?
> >
>
> As you pointed out in the next (7th) comment also, the first two
> patches are not calling GetExcludedPublicationTables(), but are using
> get_publication_relations() directly. Hence, the tests are passing
> even without the assert modification. But patch-0003 does call it, so
> the assert was updated there.
>

Ah, I missed that -- thanks for the explanation.

======
Kind Regards,
Peter Smith.
Fujitsu Australia.





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-05-19 11:14  Nisha Moond <nisha.moond412@gmail.com>
  parent: Peter Smith <smithpb2250@gmail.com>
  1 sibling, 3 replies; 196+ messages in thread

From: Nisha Moond @ 2026-05-19 11:14 UTC (permalink / raw)
  To: Peter Smith <smithpb2250@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Fri, May 15, 2026 at 12:49 PM Peter Smith <smithpb2250@gmail.com> wrote:
>
> Hi Nisha.
>
> Some review comments for patch v5-0001.
>

Thanks Peter, for the review.

> ======
> src/backend/catalog/pg_publication.c
>
> publication_add_relation:
>
> 2.
> + HeapTuple existing;
>
> Not sure if this is the best name. How about "tup"?
>

Noticed that a "HeapTuple tup;" is already declared, so we can use the
existing one.

> ~~~
>
> 3.
> + bool is_except = existing_form->prexcept;
>
> This variable is used only once. Not sure if that vindicates having it.
>

the is_except value is being used after releasing the tuple and
closing the table since the next step errors out. But I have now
removed existing_form and directly extracted the value instead.

> ~~~
>
> 8.
> + list_free(schemaRels);
> + }
> + else
> + result = list_concat(result, schemaRels);
>
> Why is 'schemaRels' only being freed when there is an EXCEPT?
>

IIUC, In the EXCEPT case, relid is an Oid, so lfirst_oid() copies the
integer value from the cell, and lappend_oid() stores that value into
a new cell in result. That means result does not reference schemaRels
cells after the loop, so list_free(schemaRels) is safe.

In the else branch, list_concat() directly transfers schemaRels cells
into result. So freeing schemaRels there would corrupt the result.

> ======
> src/backend/parser/gram.y
>
> 14.
> - | ColId opt_column_list OptWhereClause
> + | ColId opt_column_list OptWhereClause opt_pub_except_clause
>   {
>   $$ = makeNode(PublicationObjSpec);
>   $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION;
> + $$->except_tables = $4;
>
> This seems suspicious. You cannot have an EXCEPT clause when there is
> a column list or a WHERE clause, so what is this scenario? Maybe the
> "$$->except_tables = $4;" needs to be moved to the 'else' block?
>

This handles cases where multi-schema continuation is used along with
an EXCEPT clause, e.g.:
  create publication pub1 for tables in schema public, s1 except (table t1);
-- without the above, the EXCEPT clause would be silently ignored.

Now, I agree that the above case can also be handled by moving
"$$->except_tables = $4;" into the else branch. But then EXCEPT would
again get silently ignored for table continuations with a column-list
or where clause, e.g.,:
postgres=# create publication pub2 for table t1, t2 (c1) except (table t1);
CREATE PUBLICATION

The idea here is to collect the EXCEPT list whenever it is specified
for such continuation cases, and then explicitly raise an error in
preprocess_pubobj_list() if a table publication object contains an
EXCEPT list.

> ~~~
>
> 16.
> + if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLES_IN_SCHEMA)
> + {
> + if (eobj->pubtable->relation->schemaname == NULL)
> + eobj->pubtable->relation->schemaname = pubobj->name;
> + else if (strcmp(eobj->pubtable->relation->schemaname,
> + pubobj->name) != 0)
> + ereport(ERROR,
> + errcode(ERRCODE_SYNTAX_ERROR),
> + errmsg("table \"%s.%s\" in EXCEPT clause does not belong to schema \"%s\"",
> +    eobj->pubtable->relation->schemaname,
> +    eobj->pubtable->relation->relname,
> +    pubobj->name),
> + parser_errposition(eobj->location));
>
> 16a.
> Introducing some more variables (like 'eobj_schemaname' and
> 'eobj_relname') would simplify this code quite a bit.
>

Done.

> ~
>
> 16b.
> Should make use of the recently committed function that gets
> fully-qualified rel names so you can use "%s" instead of "%s.%s".
>

We cannot use RelationGetQualifiedRelationName() in the grammar, so I
used quote_qualified_identifier() instead.
~~~~

Addressed all other comments as suggested. Please find the updated v6
patches attached.

Patch-0001: updated as per the above comments.
Patch-0002 and Patch-0003: adjusted for the Patch-0001 changes and
some code simplification in tab-complete part.

--
Thanks,
Nisha

Attachments: download all (3 files, .tar.gz)

v6-0001-Support-EXCEPT-clause-for-schema-level-publicatio.patch (application/octet-stream, 42.4K) download From 4248729b91c72d68c3deea6b540cefa04b2501c1 Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Mon, 4 May 2026 12:49:27 +0530 Subject: [PATCH v6 1/3] Support EXCEPT clause for schema-level publications Extend table exclusion support in publications to allow specific tables to be excluded from schema-level publications using an EXCEPT clause in CREATE PUBLICATION. Supported syntax: CREATE PUBLICATION <pub> FOR TABLES IN SCHEMA s EXCEPT (TABLE t1,...); --- doc/src/sgml/logical-replication.sgml | 3 +- doc/src/sgml/ref/create_publication.sgml | 22 +++- src/backend/catalog/pg_publication.c | 86 +++++++++++-- src/backend/commands/publicationcmds.c | 47 ++++++- src/backend/parser/gram.y | 52 +++++++- src/backend/replication/pgoutput/pgoutput.c | 21 +++- src/bin/psql/describe.c | 18 +++ src/bin/psql/tab-complete.in.c | 26 +++- src/include/catalog/pg_publication.h | 3 +- src/include/nodes/parsenodes.h | 2 + src/test/regress/expected/publication.out | 100 ++++++++++++++- src/test/regress/sql/publication.sql | 65 +++++++++- src/test/subscription/t/037_except.pl | 133 +++++++++++++++++++- 13 files changed, 545 insertions(+), 33 deletions(-) diff --git a/doc/src/sgml/logical-replication.sgml b/doc/src/sgml/logical-replication.sgml index 9e7868487de..1433d2660fe 100644 --- a/doc/src/sgml/logical-replication.sgml +++ b/doc/src/sgml/logical-replication.sgml @@ -117,7 +117,8 @@ or <literal>FOR ALL SEQUENCES</literal>. Unlike tables, sequences can be synchronized at any time. For more information, see <xref linkend="logical-replication-sequences"/>. When a publication is - created with <literal>FOR ALL TABLES</literal>, a table or set of tables can + created with <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal>, a table or set of tables can be explicitly excluded from publication using the <link linkend="sql-createpublication-params-for-except-table"><literal>EXCEPT</literal></link> clause. diff --git a/doc/src/sgml/ref/create_publication.sgml b/doc/src/sgml/ref/create_publication.sgml index f82d640e6ca..7fa0bd11f7b 100644 --- a/doc/src/sgml/ref/create_publication.sgml +++ b/doc/src/sgml/ref/create_publication.sgml @@ -28,7 +28,7 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA <replaceable class="parameter">tables_in_schema</replaceable> [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -39,6 +39,10 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <replaceable class="parameter">table_object</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] [ WHERE ( <replaceable class="parameter">expression</replaceable> ) ] +<phrase>and <replaceable class="parameter">tables_in_schema</replaceable> is:</phrase> + + { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] + <phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> TABLE <replaceable class="parameter">table_object</replaceable> [, ... ] @@ -142,6 +146,8 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <para> Marks the publication as one that replicates changes for all tables in the specified list of schemas, including tables created in the future. + Tables listed in the <literal>EXCEPT</literal> clause for a given schema + are excluded from the publication. </para> <para> @@ -173,7 +179,7 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <para> Marks the publication as one that replicates changes for all tables in the database, including tables created in the future. Tables listed in - <literal>EXCEPT</literal> clause are excluded from the publication. + the <literal>EXCEPT</literal> clause are excluded from the publication. </para> </listitem> </varlistentry> @@ -198,7 +204,8 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <listitem> <para> This clause specifies a list of tables to be excluded from the - publication. + publication. It can be used with <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal>. </para> <para> For inherited tables, if <literal>ONLY</literal> is specified before the @@ -515,6 +522,15 @@ CREATE PUBLICATION production_publication FOR TABLE users, departments, TABLES I CREATE PUBLICATION sales_publication FOR TABLES IN SCHEMA marketing, sales; </programlisting></para> + <para> + Create a publication that publishes all changes for all the tables present in + the schema <structname>sales</structname>, except + <structname>internal</structname> and <structname>drafts</structname>: +<programlisting> +CREATE PUBLICATION sales_filtered FOR TABLES IN SCHEMA sales EXCEPT (TABLE internal, drafts); +</programlisting> + </para> + <para> Create a publication that publishes all changes for table <structname>users</structname>, but replicates only columns <structname>user_id</structname> and diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index 5c457d9aca8..6f945955901 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -446,7 +446,8 @@ GetPubPartitionOptionRelations(List *result, PublicationPartOpt pub_partopt, * ancestor is at the end of the list. */ Oid -GetTopMostAncestorInPublication(Oid puboid, List *ancestors, int *ancestor_level) +GetTopMostAncestorInPublication(Oid puboid, List *ancestors, + int *ancestor_level, List *except_pubids) { ListCell *lc; Oid topmost_relid = InvalidOid; @@ -473,7 +474,8 @@ GetTopMostAncestorInPublication(Oid puboid, List *ancestors, int *ancestor_level else { aschemaPubids = GetSchemaPublications(get_rel_namespace(ancestor)); - if (list_member_oid(aschemaPubids, puboid)) + if (list_member_oid(aschemaPubids, puboid) && + !list_member_oid(except_pubids, puboid)) { topmost_relid = ancestor; @@ -545,18 +547,30 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, * duplicates, it's here just to provide nicer error message in common * case. The real protection is the unique key on the catalog. */ - if (SearchSysCacheExists2(PUBLICATIONRELMAP, ObjectIdGetDatum(relid), - ObjectIdGetDatum(pubid))) + tup = SearchSysCache2(PUBLICATIONRELMAP, ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + + if (HeapTupleIsValid(tup)) { + bool is_except = ((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept; + + ReleaseSysCache(tup); table_close(rel, RowExclusiveLock); if (if_not_exists) return InvalidObjectAddress; - ereport(ERROR, - (errcode(ERRCODE_DUPLICATE_OBJECT), - errmsg("relation \"%s\" is already member of publication \"%s\"", - RelationGetRelationName(targetrel), pub->name))); + if (is_except) + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("table \"%s\" cannot be added because it is excluded from publication \"%s\"", + RelationGetQualifiedRelationName(targetrel), + pub->name))); + else + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("relation \"%s\" is already member of publication \"%s\"", + RelationGetRelationName(targetrel), pub->name))); } check_publication_add_relation(pri); @@ -982,12 +996,13 @@ GetIncludedPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) * Gets list of table oids that were specified in the EXCEPT clause for a * publication. * - * This should only be used FOR ALL TABLES publications. + * This is used for FOR ALL TABLES and FOR TABLES IN SCHEMA publications, + * both of which support EXCEPT TABLE. */ List * GetExcludedPublicationTables(Oid pubid, PublicationPartOpt pub_partopt) { - Assert(GetPublication(pubid)->alltables); + Assert(GetPublication(pubid)->alltables || is_schema_publication(pubid)); return get_publication_relations(pubid, pub_partopt, true); } @@ -1232,22 +1247,67 @@ GetSchemaPublicationRelations(Oid schemaid, PublicationPartOpt pub_partopt) /* * Gets the list of all relations published by FOR TABLES IN SCHEMA - * publication. + * publication, excluding any tables listed in the EXCEPT clause. */ List * GetAllSchemaPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) { List *result = NIL; List *pubschemalist = GetPublicationSchemas(pubid); + List *exceptlist = NIL; ListCell *cell; + /* get the list of tables excluded via EXCEPT TABLE for this publication */ + if (pubschemalist != NIL) + exceptlist = GetExcludedPublicationTables(pubid, pub_partopt); + foreach(cell, pubschemalist) { Oid schemaid = lfirst_oid(cell); List *schemaRels = NIL; schemaRels = GetSchemaPublicationRelations(schemaid, pub_partopt); - result = list_concat(result, schemaRels); + + if (exceptlist != NIL) + { + /* filter out any tables that appear in the EXCEPT list */ + ListCell *rlc; + + foreach(rlc, schemaRels) + { + Oid relid = lfirst_oid(rlc); + bool excluded = list_member_oid(exceptlist, relid); + + /* + * Also exclude any relation whose partition ancestor is in + * the EXCEPT list. This matters when pub_partopt is + * PUBLICATION_PART_ROOT: the except list holds only the root + * OID, but the schema scan may also return individual + * partition relations that live in the same schema. + */ + if (!excluded && get_rel_relispartition(relid)) + { + List *ancestors = get_partition_ancestors(relid); + ListCell *alc; + + foreach(alc, ancestors) + { + if (list_member_oid(exceptlist, lfirst_oid(alc))) + { + excluded = true; + break; + } + } + list_free(ancestors); + } + + if (!excluded) + result = lappend_oid(result, relid); + } + list_free(schemaRels); + } + else + result = list_concat(result, schemaRels); } return result; @@ -1381,7 +1441,7 @@ is_table_publishable_in_publication(Oid relid, Publication *pub) * the publication, it should be included (return true). */ if (relispartition && - OidIsValid(GetTopMostAncestorInPublication(pub->oid, ancestors, NULL))) + OidIsValid(GetTopMostAncestorInPublication(pub->oid, ancestors, NULL, NIL))) return !pub->pubviaroot; /* diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 440adb356ad..95186ca7377 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -305,7 +305,7 @@ pub_rf_contains_invalid_column(Oid pubid, Relation relation, List *ancestors, if (pubviaroot && relation->rd_rel->relispartition) { publish_as_relid - = GetTopMostAncestorInPublication(pubid, ancestors, NULL); + = GetTopMostAncestorInPublication(pubid, ancestors, NULL, NIL); if (!OidIsValid(publish_as_relid)) publish_as_relid = relid; @@ -389,7 +389,7 @@ pub_contains_invalid_column(Oid pubid, Relation relation, List *ancestors, */ if (pubviaroot && relation->rd_rel->relispartition) { - publish_as_relid = GetTopMostAncestorInPublication(pubid, ancestors, NULL); + publish_as_relid = GetTopMostAncestorInPublication(pubid, ancestors, NULL, NIL); if (!OidIsValid(publish_as_relid)) publish_as_relid = relid; @@ -959,6 +959,8 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) } else if (!stmt->for_all_sequences) { + List *explicitrelids = NIL; + /* FOR TABLES IN SCHEMA requires superuser */ if (schemaidlist != NIL && !superuser()) ereport(ERROR, @@ -977,6 +979,19 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) schemaidlist != NIL, publish_via_partition_root); + /* + * Collect explicit table OIDs now, before we close the relation + * list, so that except-table validation below can check for + * contradictions without relying on a catalog scan that might not + * yet see the just-inserted rows. + */ + if (exceptrelations != NIL) + { + foreach_ptr(PublicationRelInfo, pri, rels) + explicitrelids = lappend_oid(explicitrelids, + RelationGetRelid(pri->relation)); + } + PublicationAddTables(puboid, rels, true, NULL); CloseTableList(rels); } @@ -989,6 +1004,34 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) */ LockSchemaList(schemaidlist); PublicationAddSchemas(puboid, schemaidlist, true, NULL); + + if (exceptrelations != NIL) + { + List *exceptrels; + + exceptrels = OpenTableList(exceptrelations); + + /* + * Validate that each excluded table is not also in the + * explicit table list (which would be contradictory). Use the + * in-memory explicitrelids collected above rather than + * re-reading the catalog, which may not yet see the + * just-inserted rows. + */ + foreach_ptr(PublicationRelInfo, pri, exceptrels) + { + Oid except_relid = RelationGetRelid(pri->relation); + + if (list_member_oid(explicitrelids, except_relid)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" cannot appear in both the table list and the EXCEPT clause", + RelationGetQualifiedRelationName(pri->relation))); + } + + PublicationAddTables(puboid, exceptrels, true, NULL); + CloseTableList(exceptrels); + } } } diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y index ff4e1388c55..4514ef7f9c2 100644 --- a/src/backend/parser/gram.y +++ b/src/backend/parser/gram.y @@ -58,6 +58,7 @@ #include "nodes/makefuncs.h" #include "nodes/nodeFuncs.h" #include "parser/parser.h" +#include "utils/builtins.h" #include "utils/datetime.h" #include "utils/xml.h" @@ -11272,7 +11273,7 @@ AlterOwnerStmt: ALTER AGGREGATE aggregate_with_argtypes OWNER TO RoleSpec * pub_obj is one of: * * TABLE table [, ...] - * TABLES IN SCHEMA schema [, ...] + * TABLES IN SCHEMA schema [EXCEPT (TABLE table [, ...] )] [, ...] * *****************************************************************************/ @@ -11332,23 +11333,26 @@ PublicationObjSpec: $$->pubtable->columns = $3; $$->pubtable->whereClause = $4; } - | TABLES IN_P SCHEMA ColId + | TABLES IN_P SCHEMA ColId opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_SCHEMA; $$->name = $4; + $$->except_tables = $5; $$->location = @4; } - | TABLES IN_P SCHEMA CURRENT_SCHEMA + | TABLES IN_P SCHEMA CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_CUR_SCHEMA; + $$->except_tables = $5; $$->location = @4; } - | ColId opt_column_list OptWhereClause + | ColId opt_column_list OptWhereClause opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $4; /* * If either a row filter or column list is specified, create * a PublicationTable object. @@ -11392,10 +11396,11 @@ PublicationObjSpec: $$->pubtable->columns = $2; $$->pubtable->whereClause = $3; } - | CURRENT_SCHEMA + | CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $2; $$->location = @1; } ; @@ -20784,6 +20789,8 @@ preprocess_pub_all_objtype_list(List *all_objects_list, List **pubobjects, /* * Process pubobjspec_list to check for errors in any of the objects and * convert PUBLICATIONOBJ_CONTINUATION into appropriate PublicationObjSpecType. + * Also flattens except_tables from TABLES IN SCHEMA nodes into the list so + * that ObjectsInPublicationToOids() sees them as top-level EXCEPT_TABLE entries. */ static void preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) @@ -20812,6 +20819,13 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLE) { + /* EXCEPT is not valid for table objects */ + if (pubobj->except_tables != NIL) + ereport(ERROR, + errcode(ERRCODE_SYNTAX_ERROR), + errmsg("EXCEPT is not allowed for TABLE publication objects"), + parser_errposition(pubobj->location)); + /* relation name or pubtable must be set for this type of object */ if (!pubobj->name && !pubobj->pubtable) ereport(ERROR, @@ -20860,6 +20874,34 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) errcode(ERRCODE_SYNTAX_ERROR), errmsg("invalid schema name"), parser_errposition(pubobj->location)); + + /* Flatten EXCEPT entries into the top-level list */ + foreach_ptr(PublicationObjSpec, eobj, pubobj->except_tables) + { + /* + * Unqualified names are implicitly qualified with the parent + * schema. Qualified names must match the parent schema — + * each EXCEPT clause is bound to exactly one schema, so + * cross-schema entries are rejected at parse time. + */ + if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLES_IN_SCHEMA) + { + const char *eobj_schemaname = eobj->pubtable->relation->schemaname; + const char *eobj_relname = eobj->pubtable->relation->relname; + + if (eobj_schemaname == NULL) + eobj->pubtable->relation->schemaname = pubobj->name; + else if (strcmp(eobj_schemaname, pubobj->name) != 0) + ereport(ERROR, + errcode(ERRCODE_SYNTAX_ERROR), + errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", + quote_qualified_identifier(eobj_schemaname, eobj_relname), + pubobj->name), + parser_errposition(eobj->location)); + } + } + pubobjspec_list = list_concat(pubobjspec_list, pubobj->except_tables); + pubobj->except_tables = NIL; } prevobjtype = pubobj->pubobjtype; diff --git a/src/backend/replication/pgoutput/pgoutput.c b/src/backend/replication/pgoutput/pgoutput.c index 4ecfcbff7ab..b55d7ab7cd1 100644 --- a/src/backend/replication/pgoutput/pgoutput.c +++ b/src/backend/replication/pgoutput/pgoutput.c @@ -2097,6 +2097,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) * are absorbed while decoding WAL. */ List *schemaPubids = GetSchemaPublications(schemaId); + List *schemaExceptPubids; ListCell *lc; Oid publish_as_relid = relid; int publish_ancestor_level = 0; @@ -2104,6 +2105,19 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) char relkind = get_rel_relkind(relid); List *rel_publications = NIL; + /* + * For the schema EXCEPT check, we must look up the top-most ancestor + * rather than the relation itself. check_publication_add_relation() + * prevents individual partitions from appearing in the EXCEPT clause, + * so only a root (non-partition) table can have prexcept = true. + * Using the partition's own OID would always return NIL and miss the + * exclusion. + */ + Oid root_relid = am_partition ? + llast_oid(get_partition_ancestors(relid)) : relid; + + schemaExceptPubids = GetRelationExcludedPublications(root_relid); + /* Reload publications if needed before use. */ if (!publications_valid) { @@ -2267,7 +2281,8 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) ancestor = GetTopMostAncestorInPublication(pub->oid, ancestors, - &level); + &level, + schemaExceptPubids); if (ancestor != InvalidOid) { @@ -2281,7 +2296,8 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) } if (list_member_oid(pubids, pub->oid) || - list_member_oid(schemaPubids, pub->oid) || + (list_member_oid(schemaPubids, pub->oid) && + !list_member_oid(schemaExceptPubids, pub->oid)) || ancestor_published) publish = true; } @@ -2360,6 +2376,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) list_free(pubids); list_free(schemaPubids); + list_free(schemaExceptPubids); list_free(rel_publications); entry->replicate_valid = true; diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c index e1449654f96..e5b1a70e05e 100644 --- a/src/bin/psql/describe.c +++ b/src/bin/psql/describe.c @@ -7038,6 +7038,24 @@ describePublications(const char *pattern) if (!addFooterToPublicationDesc(&buf, _("Tables from schemas:"), true, &cont)) goto error_return; + + if (pset.sversion >= 190000) + { + /* + * Get tables in the EXCEPT clause for this schema + * publication. + */ + printfPQExpBuffer(&buf, + "SELECT concat(c.relnamespace::regnamespace, '.', c.relname)\n" + "FROM pg_catalog.pg_class c\n" + " JOIN pg_catalog.pg_publication_rel pr ON c.oid = pr.prrelid\n" + "WHERE pr.prpubid = '%s'\n" + " AND pr.prexcept\n" + "ORDER BY 1", pubid); + if (!addFooterToPublicationDesc(&buf, _("Except tables:"), + true, &cont)) + goto error_return; + } } } else diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index 75132528f3a..2c652cf32a0 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -1065,6 +1065,15 @@ static const SchemaQuery Query_for_trigger_of_table = { "SELECT nspname FROM pg_catalog.pg_namespace "\ " WHERE nspname LIKE '%s'" +#define Query_for_list_of_tables_in_schema \ +"SELECT n.nspname || '.' || c.relname "\ +" FROM pg_catalog.pg_class c "\ +" JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "\ +" WHERE c.relkind IN (" CppAsString2(RELKIND_RELATION) ", " \ + CppAsString2(RELKIND_PARTITIONED_TABLE) ") "\ +" AND (n.nspname || '.' || c.relname) LIKE '%s' "\ +" AND n.nspname = '%s'" + /* Use COMPLETE_WITH_QUERY_VERBATIM with these queries for GUC names: */ #define Query_for_list_of_alter_system_set_vars \ "SELECT pg_catalog.lower(name) FROM pg_catalog.pg_settings "\ @@ -3785,8 +3794,21 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); - else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && (!ends_with(prev_wd, ','))) - COMPLETE_WITH("WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE", "WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && ends_with(prev_wd, ',')) + COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* Complete "CREATE PUBLICATION <name> [...] WITH" */ else if (Matches("CREATE", "PUBLICATION", MatchAnyN, "WITH", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/include/catalog/pg_publication.h b/src/include/catalog/pg_publication.h index 89b4bb14f62..53e3d7c6f3d 100644 --- a/src/include/catalog/pg_publication.h +++ b/src/include/catalog/pg_publication.h @@ -191,7 +191,8 @@ extern List *GetPubPartitionOptionRelations(List *result, PublicationPartOpt pub_partopt, Oid relid); extern Oid GetTopMostAncestorInPublication(Oid puboid, List *ancestors, - int *ancestor_level); + int *ancestor_level, + List *except_pubids); extern bool is_publishable_relation(Relation rel); extern bool is_schema_publication(Oid pubid); diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h index 91377a6cde3..98a03c0eeda 100644 --- a/src/include/nodes/parsenodes.h +++ b/src/include/nodes/parsenodes.h @@ -4493,6 +4493,8 @@ typedef struct PublicationObjSpec PublicationObjSpecType pubobjtype; /* type of this publication object */ char *name; PublicationTable *pubtable; + List *except_tables; /* tables specified in the EXCEPT clause (for + * TABLES IN SCHEMA) */ ParseLoc location; /* token location, or -1 if unknown */ } PublicationObjSpec; diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 29e54b214a0..77d77c89d80 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -270,6 +270,12 @@ CREATE PUBLICATION testpub_foralltables_excepttable2 FOR ALL TABLES EXCEPT (test ERROR: syntax error at or near "testpub_tbl1" LINE 1: ..._foralltables_excepttable2 FOR ALL TABLES EXCEPT (testpub_tb... ^ +-- fail - EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testpub_tbl3); +ERROR: EXCEPT is not allowed for TABLE publication objects +LINE 2: FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testp... + ^ --------------------------------------------- -- SET ALL TABLES/SEQUENCES --------------------------------------------- @@ -470,7 +476,99 @@ HINT: Change the publication's EXCEPT clause using ALTER PUBLICATION ... SET AL RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Create same-named tables in public to verify unqualified EXCEPT entries +-- are qualified with the named schema, not public +CREATE TABLE testpub_nopk (foo int, bar int); +CREATE TABLE testpub_tbl_s1 (a int primary key, b text); +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + Publication testpub_schema_except1 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- Exclude multiple tables using unqualified names; same-named tables exist in +-- public to confirm unqualified names resolve to pub_test, not public +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + Publication testpub_schema_except2 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_nopk" + "pub_test.testpub_tbl_s1" + +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testp... + ^ +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); +ERROR: table "pub_test.testpub_tbl_s1" in EXCEPT clause does not belong to schema "public" +LINE 2: ...R TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.t... + ^ +-- Multiple schemas each with their own EXCEPT clause +CREATE PUBLICATION testpub_schema_except_multi + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_schema_except_multi + Publication testpub_schema_except_multi + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- fail: table appears in both the explicit table list and the EXCEPT clause +CREATE PUBLICATION testpub_except_conflict + FOR TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot appear in both the table list and the EXCEPT clause +-- fail: nonexistent table in EXCEPT clause +CREATE PUBLICATION testpub_except_norel + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- fail: partition cannot appear in EXCEPT clause; only root tables are allowed +CREATE TABLE pub_test.testpub_parted_s (a int) PARTITION BY LIST (a); +CREATE TABLE pub_test.testpub_part_s PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (1); +CREATE PUBLICATION testpub_except_partition + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); +ERROR: cannot specify relation "pub_test.testpub_part_s" in the publication EXCEPT clause +DETAIL: This operation is not supported for individual partitions. +-- fail: TABLE keyword is required for the first entry in the EXCEPT clause +CREATE PUBLICATION testpub_except_nokw + FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +ERROR: syntax error at or near "testpub_nopk" +LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + ^ +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP TABLE pub_test.testpub_parted_s CASCADE; +DROP TABLE testpub_nopk, testpub_tbl_s1; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; -- FOR ALL SEQUENCES diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 041e14a4de6..5d8a4e2637e 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -123,6 +123,9 @@ CREATE PUBLICATION testpub_foralltables_excepttable1 FOR ALL TABLES EXCEPT (TABL \d testpub_tbl1 -- fail - first table in the EXCEPT list should use TABLE keyword CREATE PUBLICATION testpub_foralltables_excepttable2 FOR ALL TABLES EXCEPT (testpub_tbl1, testpub_tbl2); +-- fail - EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testpub_tbl3); --------------------------------------------- -- SET ALL TABLES/SEQUENCES @@ -220,7 +223,67 @@ RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Create same-named tables in public to verify unqualified EXCEPT entries +-- are qualified with the named schema, not public +CREATE TABLE testpub_nopk (foo int, bar int); +CREATE TABLE testpub_tbl_s1 (a int primary key, b text); + +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + +-- Exclude multiple tables using unqualified names; same-named tables exist in +-- public to confirm unqualified names resolve to pub_test, not public +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); + +-- Multiple schemas each with their own EXCEPT clause +CREATE PUBLICATION testpub_schema_except_multi + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_schema_except_multi + +-- fail: table appears in both the explicit table list and the EXCEPT clause +CREATE PUBLICATION testpub_except_conflict + FOR TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: nonexistent table in EXCEPT clause +CREATE PUBLICATION testpub_except_norel + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- fail: partition cannot appear in EXCEPT clause; only root tables are allowed +CREATE TABLE pub_test.testpub_parted_s (a int) PARTITION BY LIST (a); +CREATE TABLE pub_test.testpub_part_s PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (1); +CREATE PUBLICATION testpub_except_partition + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); + +-- fail: TABLE keyword is required for the first entry in the EXCEPT clause +CREATE PUBLICATION testpub_except_nokw + FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP TABLE pub_test.testpub_parted_s CASCADE; +DROP TABLE testpub_nopk, testpub_tbl_s1; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; + CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 8c58d282eee..18c7b2c1fca 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -24,14 +24,17 @@ my $result; sub test_except_root_partition { - my ($pubviaroot) = @_; + my ($pubviaroot, $pubsql) = @_; + $pubsql //= + "CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1)"; + $pubsql .= " WITH (publish_via_partition_root = $pubviaroot)"; # If the root partitioned table is in the EXCEPT clause, all its # partitions are excluded from publication, regardless of the # publish_via_partition_root setting. $node_publisher->safe_psql( 'postgres', qq( - CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1) WITH (publish_via_partition_root = $pubviaroot); + $pubsql; INSERT INTO root1 VALUES (1), (101); )); $node_subscriber->safe_psql('postgres', @@ -223,6 +226,131 @@ $node_subscriber->safe_psql( test_except_root_partition('false'); test_except_root_partition('true'); +# Same validation using TABLES IN SCHEMA instead of FOR ALL TABLES. +my $schema_pub = + "CREATE PUBLICATION tap_pub_part FOR TABLES IN SCHEMA public EXCEPT (TABLE public.root1)"; +test_except_root_partition('false', $schema_pub); +test_except_root_partition('true', $schema_pub); + +# ============================================ +# EXCEPT test cases for TABLES IN SCHEMA +# ============================================ + +# Create a dedicated schema with two tables: one to be published and one to be +# excluded. Also create inherited tables to verify ONLY semantics. +$node_publisher->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_published AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.tab_excluded AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.parent (a int); + CREATE TABLE sch1.child (b int) INHERITS (sch1.parent); +)); + +$node_subscriber->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_published (a int); + CREATE TABLE sch1.tab_excluded (a int); + CREATE TABLE sch1.parent (a int); + CREATE TABLE sch1.child (b int) INHERITS (sch1.parent); +)); + +# Basic test: initial sync respects EXCEPT. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_excluded)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: initial sync copies included table'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: initial sync skips excluded table'); + +# DML: only the included table should be replicated. +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (6); + INSERT INTO sch1.tab_excluded VALUES (6); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(6), + 'TABLES IN SCHEMA EXCEPT: DML on included table is replicated'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: DML on excluded table is not replicated'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Inherited tables: excluding the parent (without ONLY) also excludes the child. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.parent)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.child VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.child"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: excluding parent (without ONLY) also excludes child' +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Test that EXCEPT (TABLE ONLY parent) excludes only the parent itself, not its +# child. Truncate child first so rows from the previous test are not copied by +# the initial table sync of the next subscription. +$node_publisher->safe_psql('postgres', 'TRUNCATE sch1.child'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE sch1.child'); +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE ONLY sch1.parent)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.child VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.child"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: ONLY parent in EXCEPT does not exclude child'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Cleanup schema tables before the multi-publication section. +$node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); +$node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); + # ============================================ # Test when a subscription is subscribing to multiple publications # ============================================ @@ -254,6 +382,7 @@ $node_publisher->safe_psql( DROP PUBLICATION tap_pub2; TRUNCATE tab1; )); +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_subscriber->safe_psql('postgres', qq(TRUNCATE tab1)); # OK when a table is excluded by pub1 EXCEPT clause, but it is included by pub2 -- 2.50.1 (Apple Git-155)
v6-0002-Add-EXCEPT-support-to-ALTER-PUBLICATION-ADD-TABLE.patch (application/octet-stream, 21.6K) download From 0313eb30e5ea34cb3983fa61e54945d6bf0dcc01 Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Tue, 19 May 2026 13:35:05 +0530 Subject: [PATCH v6 2/3] Add EXCEPT support to ALTER PUBLICATION ADD TABLES IN SCHEMA Extend the EXCEPT clause support to allow tables to be excluded when adding a schema to a publication via ALTER PUBLICATION ... ADD: Syntax: ALTER PUBLICATION pub ADD TABLES IN SCHEMA s EXCEPT (TABLE s.t1); Since pg_dump uses ALTER PUBLICATION ... ADD, support for it is included in this patch. --- doc/src/sgml/ref/alter_publication.sgml | 42 +++++++- src/backend/catalog/pg_publication.c | 19 ++-- src/backend/commands/publicationcmds.c | 113 +++++++++++++++++++++- src/bin/pg_dump/pg_dump.c | 30 +++++- src/bin/pg_dump/t/002_pg_dump.pl | 36 +++++++ src/bin/psql/tab-complete.in.c | 17 ++++ src/test/regress/expected/publication.out | 18 +++- src/test/regress/sql/publication.sql | 11 ++- src/test/subscription/t/037_except.pl | 32 ++++++ 9 files changed, 305 insertions(+), 13 deletions(-) diff --git a/doc/src/sgml/ref/alter_publication.sgml b/doc/src/sgml/ref/alter_publication.sgml index aa32bb169e9..8aedfd951a5 100644 --- a/doc/src/sgml/ref/alter_publication.sgml +++ b/doc/src/sgml/ref/alter_publication.sgml @@ -31,7 +31,7 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -54,6 +54,10 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <phrase>and <replaceable class="parameter">table_object</replaceable> is:</phrase> [ ONLY ] <replaceable class="parameter">table_name</replaceable> [ * ] + +<phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> + + [ ONLY ] <replaceable class="parameter">table_name</replaceable> [ * ] </synopsis> </refsynopsisdiv> @@ -110,6 +114,15 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <literal>ADD TABLE</literal>. </para> + <para> + The <literal>EXCEPT</literal> clause can be used with + <literal>ADD TABLES IN SCHEMA</literal> to exclude specific tables from a + schema-level publication. <literal>EXCEPT</literal> is not supported with + <literal>DROP TABLES IN SCHEMA</literal>; instead, dropping a schema from + the publication automatically removes all of its associated + <literal>EXCEPT</literal> entries. + </para> + <para> The fourth variant of this command listed in the synopsis can change all of the publication properties specified in @@ -198,6 +211,23 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r </listitem> </varlistentry> + <varlistentry> + <term><literal>EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] )</literal></term> + <listitem> + <para> + Specifies tables to be excluded from a schema-level publication entry. + This clause may be used with <literal>ADD TABLES IN SCHEMA</literal> + and not with <literal>DROP TABLES IN SCHEMA</literal>. Each named + table must belong to the schema specified in the same + <literal>TABLES IN SCHEMA</literal> clause. Table names may be + schema-qualified or unqualified; unqualified names are implicitly + qualified with the schema named in the same clause. See + <xref linkend="sql-createpublication"/> for further details on the + semantics of <literal>EXCEPT</literal>. + </para> + </listitem> + </varlistentry> + <varlistentry> <term><literal>SET ( <replaceable class="parameter">publication_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] )</literal></term> <listitem> @@ -288,6 +318,16 @@ ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA marketing, sales; </programlisting> </para> + <para> + Add schema <structname>sales</structname> to the publication + <structname>sales_publication</structname>, excluding the + <structname>sales.internal</structname> and + <structname>sales.drafts</structname> tables: +<programlisting> +ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA sales EXCEPT (TABLE sales.internal, sales.drafts); +</programlisting> + </para> + <para> Add tables <structname>users</structname>, <structname>departments</structname> and schema diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index 6f945955901..a339abf5e1b 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -645,15 +645,18 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, * here, as CreatePublication() function invalidates all relations as part * of defining a FOR ALL TABLES publication. * - * For ALTER PUBLICATION, invalidation is needed only when adding an - * EXCEPT table to a publication already marked as ALL TABLES. For - * publications that were originally empty or defined as ALL SEQUENCES and - * are being converted to ALL TABLES, invalidation is skipped here, as - * AlterPublicationAllFlags() function invalidates all relations while - * marking the publication as ALL TABLES publication. + * For ALTER PUBLICATION, invalidation is needed when adding an EXCEPT + * table to either a FOR ALL TABLES publication (pub->alltables is true) + * or a FOR TABLES IN SCHEMA publication (is_schema_publication is true). + * The exception: when a publication is being converted to FOR ALL TABLES + * (pub->alltables is still false at this point), + * AlterPublicationAllFlags() will perform a full invalidation, so we + * skip it here. */ - inval_except_table = (alter_stmt != NULL) && pub->alltables && - (alter_stmt->for_all_tables && pri->except); + inval_except_table = (alter_stmt != NULL) && pri->except && + (pub->alltables + ? alter_stmt->for_all_tables + : is_schema_publication(pubid)); if (!pri->except || inval_except_table) { diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 95186ca7377..ea689e5da7c 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -70,6 +70,9 @@ static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok); static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); +static void AlterPublicationExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, List *exceptrelations, + List *schemaidlist); static char defGetGeneratedColsOption(DefElem *def); @@ -1519,6 +1522,13 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, } PublicationAddSchemas(pubform->oid, schemaidlist, false, stmt); + + /* + * Increment the command counter so that is_schema_publication() in + * GetExcludedPublicationTables() can see the just-inserted schema + * rows when AlterPublicationExceptTables runs next. + */ + CommandCounterIncrement(); } else if (stmt->action == AP_DropObjects) PublicationDropSchemas(pubform->oid, schemaidlist, false); @@ -1544,6 +1554,100 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, * skip existing ones when doing catalog update. */ PublicationAddSchemas(pubform->oid, schemaidlist, true, stmt); + + /* + * Increment the command counter so that is_schema_publication() in + * GetExcludedPublicationTables() can see the just-inserted schema + * rows when AlterPublicationExceptTables runs next. + */ + CommandCounterIncrement(); + } +} + +/* + * Alter the EXCEPT list of a publication. + * + * Adds, removes, or replaces except-table entries in pg_publication_rel + * (rows with prexcept = true). These entries suppress publication of the + * named tables that would otherwise be covered by a FOR TABLES IN SCHEMA + * or FOR ALL TABLES clause. + */ +static void +AlterPublicationExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, List *exceptrelations, + List *schemaidlist) +{ + Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); + Oid pubid = pubform->oid; + + /* + * Nothing to do if no EXCEPT entries. + */ + if (!exceptrelations) + return; + + /* + * This function handles EXCEPT entries for schema-level publications + * only. For FOR ALL TABLES publications, EXCEPT entries are already + * processed by AlterPublicationTables(). + */ + if (schemaidlist == NIL && !is_schema_publication(pubid)) + return; + + /* + * EXCEPT is not meaningful with DROP: dropping a schema from a + * publication already removes all its except entries via cascade, and + * there is no sensible interpretation of "drop only the except entry but + * keep the schema". + */ + if (stmt->action == AP_DropObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); + + /* + * EXCEPT with SET is not supported: SET replaces the schema list but does + * not have a well-defined semantics for merging or replacing existing + * except entries. Users should DROP and re-ADD the schema with the + * desired EXCEPT list instead. + */ + if (stmt->action == AP_SetObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"))); + + if (stmt->action == AP_AddObjects) + { + List *rels; + List *explicitrelids; + ListCell *lc; + + rels = OpenTableList(exceptrelations); + + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + /* + * Validate that each excluded table is not also in the explicit table + * list (which would be contradictory). + */ + foreach(lc, rels) + { + PublicationRelInfo *pri = (PublicationRelInfo *) lfirst(lc); + Oid relid = RelationGetRelid(pri->relation); + Oid relns = RelationGetNamespace(pri->relation); + + if (list_member_oid(explicitrelids, relid)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s.%s\" cannot appear in both the table list and the EXCEPT clause", + get_namespace_name(relns), + RelationGetRelationName(pri->relation))); + } + + PublicationAddTables(pubid, rels, false, stmt); + + CloseTableList(rels); } } @@ -1754,10 +1858,17 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) errmsg("publication \"%s\" does not exist", stmt->pubname)); - relations = list_concat(relations, exceptrelations); + /* + * For FOR ALL TABLES, EXCEPT entries are processed by + * AlterPublicationTables(), so merge them in. For TABLES IN SCHEMA, + * they are handled separately by AlterPublicationExceptTables(). + */ + if (stmt->for_all_tables) + relations = list_concat(relations, exceptrelations); AlterPublicationTables(stmt, tup, relations, pstate->p_sourcetext, schemaidlist != NIL); AlterPublicationSchemas(stmt, tup, schemaidlist); + AlterPublicationExceptTables(stmt, tup, exceptrelations, schemaidlist); AlterPublicationAllFlags(stmt, rel, tup); } diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c index d56dcc701ce..e62d74c8ca0 100644 --- a/src/bin/pg_dump/pg_dump.c +++ b/src/bin/pg_dump/pg_dump.c @@ -5019,6 +5019,7 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) PublicationInfo *pubinfo = pubsinfo->publication; PQExpBuffer query; char *tag; + bool has_except = false; /* Do nothing if not dumping schema */ if (!dopt->dumpSchema) @@ -5029,7 +5030,34 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) query = createPQExpBuffer(); appendPQExpBuffer(query, "ALTER PUBLICATION %s ", fmtId(pubinfo->dobj.name)); - appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s;\n", fmtId(schemainfo->dobj.name)); + appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s", fmtId(schemainfo->dobj.name)); + + /* + * Append EXCEPT clause for any tables that belong to this schema + * and are excluded from the publication. + */ + for (SimplePtrListCell *cell = pubinfo->except_tables.head; cell; cell = cell->next) + { + TableInfo *tbinfo = (TableInfo *) cell->ptr; + + if (strcmp(tbinfo->dobj.namespace->dobj.name, schemainfo->dobj.name) == 0) + { + if (!has_except) + { + appendPQExpBufferStr(query, " EXCEPT ("); + has_except = true; + } + else + appendPQExpBufferStr(query, ", "); + + appendPQExpBuffer(query, "TABLE ONLY %s", fmtId(tbinfo->dobj.name)); + } + } + + if (has_except) + appendPQExpBufferStr(query, ")"); + + appendPQExpBufferStr(query, ";\n"); /* * There is no point in creating drop query as the drop is done by schema diff --git a/src/bin/pg_dump/t/002_pg_dump.pl b/src/bin/pg_dump/t/002_pg_dump.pl index 3ee9fda50e4..af37bcb3627 100644 --- a/src/bin/pg_dump/t/002_pg_dump.pl +++ b/src/bin/pg_dump/t/002_pg_dump.pl @@ -3242,6 +3242,42 @@ my %tests = ( like => { %full_runs, section_post_data => 1, }, }, + 'CREATE PUBLICATION pub11' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub11 FOR TABLES IN SCHEMA dump_test EXCEPT (TABLE dump_test.test_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub11 WITH (publish = 'insert, update, delete, truncate');\E + /xm, + like => { %full_runs, section_post_data => 1, }, + }, + + 'ALTER PUBLICATION pub11 ADD TABLES IN SCHEMA dump_test EXCEPT (dump_test.test_table)' + => { + regexp => qr/^ + \QALTER PUBLICATION pub11 ADD TABLES IN SCHEMA dump_test EXCEPT (TABLE ONLY test_table);\E + /xm, + like => { %full_runs, section_post_data => 1, }, + }, + + 'CREATE PUBLICATION pub12' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub12 FOR TABLES IN SCHEMA dump_test EXCEPT (TABLE dump_test.test_table, dump_test.test_second_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub12 WITH (publish = 'insert, update, delete, truncate');\E + /xm, + like => { %full_runs, section_post_data => 1, }, + }, + + 'ALTER PUBLICATION pub12 ADD TABLES IN SCHEMA dump_test EXCEPT (dump_test.test_table, dump_test.test_second_table)' + => { + regexp => qr/^ + \QALTER PUBLICATION pub12 ADD TABLES IN SCHEMA dump_test EXCEPT (TABLE ONLY test_table, TABLE ONLY test_second_table);\E + /xm, + like => { %full_runs, section_post_data => 1, }, + }, + 'CREATE SUBSCRIPTION sub1' => { create_order => 50, create_sql => 'CREATE SUBSCRIPTION sub1 diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index 2c652cf32a0..6ea92444105 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2364,6 +2364,23 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); + /* After a single schema name in ADD context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && ends_with(prev_wd, ',')) + COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 77d77c89d80..a9d5e7a49db 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -564,11 +564,27 @@ CREATE PUBLICATION testpub_except_nokw ERROR: syntax error at or near "testpub_nopk" LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); ^ +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; +-- ADD: add a schema with an excepted table +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP TABLE pub_test.testpub_parted_s CASCADE; DROP TABLE testpub_nopk, testpub_tbl_s1; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi, testpub_alter_except; CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; -- FOR ALL SEQUENCES diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 5d8a4e2637e..6b9eb26a2af 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -278,11 +278,20 @@ CREATE PUBLICATION testpub_except_partition CREATE PUBLICATION testpub_except_nokw FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; + +-- ADD: add a schema with an excepted table +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_alter_except + RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP TABLE pub_test.testpub_parted_s CASCADE; DROP TABLE testpub_nopk, testpub_tbl_s1; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi, testpub_alter_except; CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 18c7b2c1fca..0ba6d6f8bb2 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -347,6 +347,38 @@ is($result, qq(5), $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); +# ============================================ +# ALTER PUBLICATION EXCEPT for TABLES IN SCHEMA +# ============================================ + +# Truncate subscriber tables to remove data accumulated from previous tests. +$node_subscriber->safe_psql('postgres', + 'TRUNCATE sch1.tab_published, sch1.tab_excluded, sch1.parent, sch1.child'); + +# ADD: add a schema with an excepted table; verify the except entry takes effect. +$node_publisher->safe_psql('postgres', "CREATE PUBLICATION sch_pub"); +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub ADD TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_excluded)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(6), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: included table synced'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + # Cleanup schema tables before the multi-publication section. $node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); $node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); -- 2.50.1 (Apple Git-155)
v6-0003-Add-EXCEPT-support-to-ALTER-PUBLICATION-SET-TABLE.patch (application/octet-stream, 20.0K) download From d7088cb54fa57c9000e57054f6db16721bbf0013 Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Tue, 19 May 2026 13:44:35 +0530 Subject: [PATCH v6 3/3] Add EXCEPT support to ALTER PUBLICATION SET TABLES IN SCHEMA Extend AlterPublicationExceptTables() with the AP_SetObjects case, which redefine the publication and replaces the entire EXCEPT list. Syntax: ALTER PUBLICATION pub SET TABLES IN SCHEMA s EXCEPT (TABLE t1); This patch also cleans up EXCEPT entries when a schema is dropped from the publication. --- doc/src/sgml/ref/alter_publication.sgml | 36 ++++-- src/backend/commands/publicationcmds.c | 145 ++++++++++++++++++++-- src/bin/psql/tab-complete.in.c | 17 +++ src/test/regress/expected/publication.out | 20 +++ src/test/regress/sql/publication.sql | 10 ++ src/test/subscription/t/037_except.pl | 90 ++++++++++++++ 6 files changed, 293 insertions(+), 25 deletions(-) diff --git a/doc/src/sgml/ref/alter_publication.sgml b/doc/src/sgml/ref/alter_publication.sgml index 8aedfd951a5..1b73b34e43a 100644 --- a/doc/src/sgml/ref/alter_publication.sgml +++ b/doc/src/sgml/ref/alter_publication.sgml @@ -54,10 +54,6 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <phrase>and <replaceable class="parameter">table_object</replaceable> is:</phrase> [ ONLY ] <replaceable class="parameter">table_name</replaceable> [ * ] - -<phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> - - [ ONLY ] <replaceable class="parameter">table_name</replaceable> [ * ] </synopsis> </refsynopsisdiv> @@ -97,7 +93,11 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r used with a publication defined with <literal>FOR TABLE</literal> or <literal>FOR TABLES IN SCHEMA</literal>, replaces the list of tables/schemas in the publication with the specified list; the existing tables or schemas - that were present in the publication will be removed. + that were present in the publication will be removed. When + <literal>SET TABLES IN SCHEMA</literal> is used with an + <literal>EXCEPT</literal> clause, the excluded tables for each schema are + replaced with the specified list; if <literal>EXCEPT</literal> is omitted + for a schema, any existing exclusions for that schema are cleared. </para> <para> @@ -116,7 +116,8 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <para> The <literal>EXCEPT</literal> clause can be used with - <literal>ADD TABLES IN SCHEMA</literal> to exclude specific tables from a + <literal>ADD TABLES IN SCHEMA</literal> and + <literal>SET TABLES IN SCHEMA</literal> to exclude specific tables from a schema-level publication. <literal>EXCEPT</literal> is not supported with <literal>DROP TABLES IN SCHEMA</literal>; instead, dropping a schema from the publication automatically removes all of its associated @@ -217,12 +218,12 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <para> Specifies tables to be excluded from a schema-level publication entry. This clause may be used with <literal>ADD TABLES IN SCHEMA</literal> - and not with <literal>DROP TABLES IN SCHEMA</literal>. Each named - table must belong to the schema specified in the same - <literal>TABLES IN SCHEMA</literal> clause. Table names may be - schema-qualified or unqualified; unqualified names are implicitly - qualified with the schema named in the same clause. See - <xref linkend="sql-createpublication"/> for further details on the + and <literal>SET TABLES IN SCHEMA</literal>, and not with + <literal>DROP TABLES IN SCHEMA</literal>. Each named table must belong + to the schema specified in the same <literal>TABLES IN SCHEMA</literal> + clause. Table names may be schema-qualified or unqualified; unqualified + names are implicitly qualified with the schema named in the same clause. + See <xref linkend="sql-createpublication"/> for further details on the semantics of <literal>EXCEPT</literal>. </para> </listitem> @@ -328,6 +329,17 @@ ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA sales EXCEPT (TABLE sal </programlisting> </para> + <para> + Replace the schema list of <structname>sales_publication</structname> with + <structname>sales</structname>, excluding only + <structname>sales.drafts</structname> (any previously excluded tables for + that schema are replaced, and schemas previously in the publication are + removed): +<programlisting> +ALTER PUBLICATION sales_publication SET TABLES IN SCHEMA sales EXCEPT (TABLE sales.drafts); +</programlisting> + </para> + <para> Add tables <structname>users</structname>, <structname>departments</structname> and schema diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index ea689e5da7c..5118881ff6c 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -1581,9 +1581,11 @@ AlterPublicationExceptTables(AlterPublicationStmt *stmt, Oid pubid = pubform->oid; /* - * Nothing to do if no EXCEPT entries. + * Nothing to do if no EXCEPT entries, except in SET: for that it is quite + * possible that the user has removed all exceptions, in which case we + * need to drop any existing ones. */ - if (!exceptrelations) + if (!exceptrelations && stmt->action != AP_SetObjects) return; /* @@ -1605,17 +1607,6 @@ AlterPublicationExceptTables(AlterPublicationStmt *stmt, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); - /* - * EXCEPT with SET is not supported: SET replaces the schema list but does - * not have a well-defined semantics for merging or replacing existing - * except entries. Users should DROP and re-ADD the schema with the - * desired EXCEPT list instead. - */ - if (stmt->action == AP_SetObjects) - ereport(ERROR, - (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"))); - if (stmt->action == AP_AddObjects) { List *rels; @@ -1647,6 +1638,95 @@ AlterPublicationExceptTables(AlterPublicationStmt *stmt, PublicationAddTables(pubid, rels, false, stmt); + CloseTableList(rels); + } + else /* AP_SetObjects */ + { + List *oldexceptrelids = NIL; + List *newexceptrelids = NIL; + List *delrelids = NIL; + List *rels; + List *explicitrelids; + ListCell *lc; + + rels = OpenTableList(exceptrelations); + + /* Collect OIDs of the desired new except list. */ + foreach(lc, rels) + { + PublicationRelInfo *pri = (PublicationRelInfo *) lfirst(lc); + + newexceptrelids = lappend_oid(newexceptrelids, + RelationGetRelid(pri->relation)); + } + + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + /* + * Validate that each excluded table is not also in the explicit table + * list (which would be contradictory). + */ + foreach(lc, rels) + { + PublicationRelInfo *pri = (PublicationRelInfo *) lfirst(lc); + Oid relid = RelationGetRelid(pri->relation); + Oid relns = RelationGetNamespace(pri->relation); + + if (list_member_oid(explicitrelids, relid)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s.%s\" cannot appear in both the table list and the EXCEPT clause", + get_namespace_name(relns), + RelationGetRelationName(pri->relation))); + } + + /* + * Get the current set of except entries. Only FOR ALL TABLES and + * schema-level publications can have except entries; for any other + * publication type oldexceptrelids stays NIL. + * + * Note: we check is_schema_publication() against the current catalog + * state (before AlterPublicationSchemas has run), so if the caller is + * doing SET TABLE t1 to convert a schema publication into a plain + * table publication, is_schema_publication() still returns true here. + * That is intentional: it lets us discover and clean up any stale + * except entries that belong to the old schema definition. + */ + if (GetPublication(pubid)->alltables || is_schema_publication(pubid)) + oldexceptrelids = GetExcludedPublicationTables(pubid, + PUBLICATION_PART_ROOT); + + /* Build a list of old except entries not present in the new list. */ + foreach(lc, oldexceptrelids) + { + Oid oldrelid = lfirst_oid(lc); + + if (!list_member_oid(newexceptrelids, oldrelid)) + delrelids = lappend_oid(delrelids, oldrelid); + } + + /* Drop old except entries not present in the new list. */ + foreach(lc, delrelids) + { + Oid relid = lfirst_oid(lc); + Oid proid; + ObjectAddress obj; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (!OidIsValid(proid)) + continue; /* already gone */ + + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + + /* Add new except entries, skipping any already present. */ + PublicationAddTables(pubid, rels, true, stmt); + CloseTableList(rels); } } @@ -2301,6 +2381,8 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) foreach(lc, schemas) { Oid schemaid = lfirst_oid(lc); + List *exceptoids; + ListCell *elc; psid = GetSysCacheOid2(PUBLICATIONNAMESPACEMAP, Anum_pg_publication_namespace_oid, @@ -2317,8 +2399,45 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) get_namespace_name(schemaid)))); } + /* + * Collect prexcept rows for tables belonging to this schema before + * removing the schema entry. GetExcludedPublicationTables relies on + * is_schema_publication(), which scans pg_publication_namespace; if + * this is the last schema in the publication, performDeletion() below + * would remove that row and make is_schema_publication() return + * false, tripping the assertion. + */ + exceptoids = GetExcludedPublicationTables(pubid, PUBLICATION_PART_ROOT); + ObjectAddressSet(obj, PublicationNamespaceRelationId, psid); performDeletion(&obj, DROP_CASCADE, 0); + + /* + * Drop any prexcept rows for tables belonging to this schema. These + * rows have no pg_depend entry pointing at the + * pg_publication_namespace row, so they are not cascaded by the + * performDeletion() call above and must be cleaned up explicitly. + */ + foreach(elc, exceptoids) + { + Oid relid = lfirst_oid(elc); + Oid proid; + + if (get_rel_namespace(relid) != schemaid) + continue; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (!OidIsValid(proid)) + continue; /* already gone */ + + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + + list_free(exceptoids); } } diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index 6ea92444105..8dce408143f 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2381,6 +2381,23 @@ match_previous_words(int pattern_id, COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables); else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) COMPLETE_WITH(")"); + /* After a single schema name in SET context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && ends_with(prev_wd, ',')) + COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index a9d5e7a49db..c93d1c96276 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -580,6 +580,26 @@ Tables from schemas: Except tables: "pub_test.testpub_tbl_s1" +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s2" + +-- error: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +ERROR: EXCEPT clause is not supported with DROP in ALTER PUBLICATION +-- error: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 1: ...xcept SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.tes... + ^ RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP TABLE pub_test.testpub_parted_s CASCADE; diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 6b9eb26a2af..496c039ca25 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -287,6 +287,16 @@ CREATE PUBLICATION testpub_alter_except; ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); \dRp+ testpub_alter_except +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + +-- error: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); + +-- error: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP TABLE pub_test.testpub_parted_s CASCADE; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 0ba6d6f8bb2..a32b2d7861a 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -376,6 +376,66 @@ $result = is($result, qq(0), 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); +# SET: replace the except list; tab_excluded is now included and tab_published is excluded. +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_published)" +); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (7); + INSERT INTO sch1.tab_excluded VALUES (7); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(7), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: newly included table is replicated' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(6), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: now-excluded table is not replicated' +); + +# SET without EXCEPT: clears the except list; both tables are now published. +# tab_published will be re-synced because REFRESH removed its entry when it was +# excluded. Truncate the subscriber copy beforehand so the re-sync produces +# a predictable count: publisher has 7 rows (6 original + INSERT(7)), so the +# subscriber ends up with 7 after re-sync, then 8 after INSERT(8). +$node_subscriber->safe_psql('postgres', 'TRUNCATE sch1.tab_published'); +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1"); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (8); + INSERT INTO sch1.tab_excluded VALUES (8); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(8), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_published replicated after except list cleared' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(8), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_excluded replicated after except list cleared' +); + $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); @@ -443,6 +503,36 @@ $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); +# OK when a table is excluded by a TABLES IN SCHEMA EXCEPT publication, +# but is included by another publication. +$node_publisher->safe_psql('postgres', 'TRUNCATE tab1'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE tab1'); + +$node_publisher->safe_psql( + 'postgres', qq( + CREATE PUBLICATION tap_pub1 FOR TABLES IN SCHEMA public EXCEPT (TABLE public.tab1); + CREATE PUBLICATION tap_pub2 FOR TABLE tab1; + INSERT INTO tab1 VALUES(1); +)); +$node_subscriber->psql('postgres', + "CREATE SUBSCRIPTION tap_sub CONNECTION '$publisher_connstr' PUBLICATION tap_pub1, tap_pub2" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'tap_sub'); + +$node_publisher->safe_psql('postgres', qq(INSERT INTO tab1 VALUES(2))); +$node_publisher->wait_for_catchup('tap_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT * FROM tab1 ORDER BY a"); +is( $result, qq(1 +2), + "TABLES IN SCHEMA EXCEPT: table excluded in schema pub but included by another pub is replicated" +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); + $node_publisher->stop('fast'); done_testing(); -- 2.50.1 (Apple Git-155)
^ permalink raw reply [nested|flat] 196+ messages in thread

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-05-22 02:26  Peter Smith <smithpb2250@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  2 siblings, 1 reply; 196+ messages in thread

From: Peter Smith @ 2026-05-22 02:26 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Hi Nisha.

Here are some review comments for patch v6-0001.

======
src/backend/catalog/pg_publication.c

GetTopMostAncestorInPublication:

1.
+GetTopMostAncestorInPublication(Oid puboid, List *ancestors,
+ int *ancestor_level, List *except_pubids)

I am having dificulty understanding this function. There needs to be a
description what does the input parameter 'except_pubids' mean. The
param name doesn't tell me anything much -- just that it is a list of
pubids that "something" (what?) is excluded from. And how does that
relate to the 'ancestors'?

~~~

2.
  {
  aschemaPubids = GetSchemaPublications(get_rel_namespace(ancestor));
- if (list_member_oid(aschemaPubids, puboid))
+ if (list_member_oid(aschemaPubids, puboid) &&
+ !list_member_oid(except_pubids, puboid))

Is this new code in the right place? I'm not 100% sure of the
'except_pubids' details, but shouldn't it be checked sooner? e.g.  if
we know already that this pubid is no good
(!list_member_oid(except_pubids, puboid)) then what is the point to
even assign/check aschemaPubids?

~~~

3.
+ if (is_except)
+ ereport(ERROR,
+ (errcode(ERRCODE_DUPLICATE_OBJECT),
+ errmsg("table \"%s\" cannot be added because it is excluded from
publication \"%s\"",
+ RelationGetQualifiedRelationName(targetrel),
+ pub->name)));
+ else
+ ereport(ERROR,
+ (errcode(ERRCODE_DUPLICATE_OBJECT),
+ errmsg("relation \"%s\" is already member of publication \"%s\"",
+ RelationGetRelationName(targetrel), pub->name)));

Fully qualified 'targetrel' in the first error, but not in the second? Is it OK?

~~~

GetAllSchemaPublicationRelations:

4.
+ List    *exceptlist = NIL;

The varname is a bit vague; it is a list of "what"? Maybe say
'except_relids' or similar.

======
src/backend/replication/pgoutput/pgoutput.c

get_rel_sync_entry:

5.
+ /*
+ * For the schema EXCEPT check, we must look up the top-most ancestor
+ * rather than the relation itself.  check_publication_add_relation()
+ * prevents individual partitions from appearing in the EXCEPT clause,
+ * so only a root (non-partition) table can have prexcept = true.
+ * Using the partition's own OID would always return NIL and miss the
+ * exclusion.
+ */
+ Oid root_relid = am_partition ?
+ llast_oid(get_partition_ancestors(relid)) : relid;
+
+ schemaExceptPubids = GetRelationExcludedPublications(root_relid);

5a.
The varname 'schemaExceptPubids' seems ambiguous. It sounds like it is
pubids that have EXCEPT SCHEMA. In the future the ALL TABLES may
introduce "EXCEPT SCHEMA", but currently there is no such thing.
Meanwhile, here I think it means "EXCEPT TABLE", so IMO that varname
needs to indicate the meaning better.

~

5b.
Actually, this is becoming a GENERAL comment. There too many ways that
these EXCEPT tables are getting named, and it is causing confusion:
- except_pubids
- exceptlist
- exceptrelations
- exceptrels
- except_relid
- except_tables
- schemaExceptPubids

Can we standardize on some common names, to make all the code more consistent?

~

5c.
Previously, the result of 'get_partition_ancestors' was being freed,
but now it is not. I'm not sure how importatnt that is, because I
found other examples in PG source code also not freeing...

======
src/bin/psql/tab-complete.in.c

6.
+ else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES",
"IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) &&
ends_with(prev_wd, ','))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables);

I'm not sure if this is working as intended.

When testing for multiple except tables I get results like:
----
test_pub=# create publication pub1 for tables IN SCHEMA myschema <TAB>
EXCEPT ( TABLE  WITH (
test_pub=# create publication pub1 for tables IN SCHEMA myschema
except ( table <TAB>
test_pub=# create publication pub1 for tables IN SCHEMA myschema
except ( table myschema.t<TAB>
myschema.t1  myschema.t2  myschema.t3
test_pub=# create publication pub1 for tables IN SCHEMA myschema
except ( table myschema.t1,<TAB>
information_schema.  myschema.            public.              t1
             t2                   t3
----

Note: it is offering suggstions for schema names outside of the
"myschema". Should this code be calling
Query_for_list_of_tables_in_schema instead of
Query_for_list_of_tables?

======
src/test/regress/sql/publication.sql

7.
---- Tests for publications with SEQUENCES
+---------------------------------------------
+-- EXCEPT tests for TABLES IN SCHEMA
+---------------------------------------------
+SET client_min_messages = 'ERROR';

It looks like a previous comment for the SEQUENCES tests has been
accidentally removed.

I should be put back, and made more prominent like the other big comments.
e.g.
---------------------------------------------
-- Tests for publications with SEQUENCES
---------------------------------------------

~~~

8.
+RESET client_min_messages;
+DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2;
+DROP TABLE pub_test.testpub_parted_s CASCADE;
+DROP TABLE testpub_nopk, testpub_tbl_s1;
+DROP PUBLICATION testpub_schema_except1, testpub_schema_except2,
testpub_schema_except_multi;
+

Add a "Cleanup" comment.

======
Kind Regards,
Peter Smith.
Fujitsu Australia.





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-05-22 05:30  Peter Smith <smithpb2250@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  2 siblings, 1 reply; 196+ messages in thread

From: Peter Smith @ 2026-05-22 05:30 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Hi Nisha.

Here are some review comments for patch v6-0002.

======
Commit message

1.
Extend the EXCEPT clause support to allow tables to be excluded when
adding a schema to a publication via ALTER PUBLICATION ... ADD:

~

/ADD:/ADD./

======
doc/src/sgml/ref/alter_publication.sgml

Synopsis.

2.
-    TABLES IN SCHEMA { <replaceable
class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ...
]
+    TABLES IN SCHEMA { <replaceable
class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [
EXCEPT ( <replaceable
class="parameter">except_table_object</replaceable> [, ... ] ) ] [,
... ]

~

Probably needs to change to introduce the 'tables_in_schema' part,
same as in the CREATE PUBLICATION synopsis.

~~~

3.
+
+<phrase>and <replaceable
class="parameter">except_table_object</replaceable> is:</phrase>
+
+   [ ONLY ] <replaceable class="parameter">table_name</replaceable> [ * ]

Something is wrong. Now the synopsis has 'except_table_object' 2x.

~~~

4.
+  <para>
+   The <literal>EXCEPT</literal> clause can be used with
+   <literal>ADD TABLES IN SCHEMA</literal> to exclude specific tables from a
+   schema-level publication. <literal>EXCEPT</literal> is not supported with
+   <literal>DROP TABLES IN SCHEMA</literal>; instead, dropping a schema from
+   the publication automatically removes all of its associated
+   <literal>EXCEPT</literal> entries.
+  </para>

4a.
I didn't think you need to say it is a "schema-level" publication.
That much is obvious because it already says "TABLES IN SCHEMA".

~

4b.
Maybe do not say "is not supported", because IMO that implies it will
cause an error.

SUGGESTION (or something like this)
Using <literal>DROP TABLES IN SCHEMA</literal> on a publication will
automatically also remove any associated <literal>EXCEPT</literal>
entries.

~~~

EXCEPT

5.
+   <varlistentry>
+    <term><literal>EXCEPT ( <replaceable
class="parameter">except_table_object</replaceable> [, ... ]
)</literal></term>
+    <listitem>
+     <para>
+      Specifies tables to be excluded from a schema-level publication entry.
+      This clause may be used with <literal>ADD TABLES IN SCHEMA</literal>
+      and not with <literal>DROP TABLES IN SCHEMA</literal>.  Each named
+      table must belong to the schema specified in the same
+      <literal>TABLES IN SCHEMA</literal> clause.  Table names may be
+      schema-qualified or unqualified; unqualified names are implicitly
+      qualified with the schema named in the same clause.  See
+      <xref linkend="sql-createpublication"/> for further details on the
+      semantics of <literal>EXCEPT</literal>.
+     </para>
+    </listitem>
+   </varlistentry>
+

5a.
Oh! If this EXCEPT part was previously missing even for the "FOR ALL
TABLES", then IMO that is a separate bug that should be in another
thread and patched/fixed asap, then your patch should just make small
changes to to it.

~

5b.
I don't think you need to say "schema-level" here... Maybe reword like
"When used with ADD TABLES IN SCHEMA...". Anyway, all this wording
will need to change a bit after the aforementioned fix for "FOR ALL
TABLES EXCEPT" patched/pushed.

~~~

Examples

6.
+<programlisting>
+ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA sales EXCEPT
(TABLE sales.internal, sales.drafts);
+</programlisting>

It is OK left in the description, but IMO it is better if you don't
use the schema-qualified name in the actual code fragment.

======
src/backend/commands/publicationcmds.c

AlterPublicationSchemas:

7.
+ /*
+ * Increment the command counter so that is_schema_publication() in
+ * GetExcludedPublicationTables() can see the just-inserted schema
+ * rows when AlterPublicationExceptTables runs next.
+ */
+ CommandCounterIncrement();

Should this cut/paste common code be done afterwards just if
stmt->action == AP_AddObjects/SetObjects ?

~~~

AlterPublicationExceptTables:

8.
+ /*
+ * This function handles EXCEPT entries for schema-level publications
+ * only.  For FOR ALL TABLES publications, EXCEPT entries are already
+ * processed by AlterPublicationTables().
+ */
+ if (schemaidlist == NIL && !is_schema_publication(pubid))
+ return;

Huh? It seems contrary to the function comment that was also talking
about "FOR ALL TABLES".

Should this function really be called something different like
'AlterPublicationSchemaExceptTables'?

~~~

9.
+ /*
+ * EXCEPT with SET is not supported: SET replaces the schema list but does
+ * not have a well-defined semantics for merging or replacing existing
+ * except entries.  Users should DROP and re-ADD the schema with the
+ * desired EXCEPT list instead.
+ */
+ if (stmt->action == AP_SetObjects)
+ ereport(ERROR,
+ (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION")));

9a.
Not sure about this comment saying "does not have a well-defined
semantics". Should you instead just have XXX comment to simply say
"Not yet implemented", because this is getting replaced later by your
patch 0003 I think.

SUGGESTION
XXX EXCEPT with SET is not currently implemented. Workaround: Users
should DROP and re-ADD the schema with the desired EXCEPT list.

~

9b.
The ereport should be temporarily (until patch 0003 is pushed) have
using an errhint to say the workaround.

~~~

10.
+ if (stmt->action == AP_AddObjects)
+ {
+ List    *rels;
+ List    *explicitrelids;
+ ListCell   *lc;
+
+ rels = OpenTableList(exceptrelations);
+
+ explicitrelids = GetIncludedPublicationRelations(pubid,
+ PUBLICATION_PART_ROOT);
+
+ /*
+ * Validate that each excluded table is not also in the explicit table
+ * list (which would be contradictory).
+ */
+ foreach(lc, rels)

Can tidy this using a foreach_ptr look instead of 'lc'.

~~~

11.
+ if (list_member_oid(explicitrelids, relid))
+ ereport(ERROR,
+ errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("table \"%s.%s\" cannot appear in both the table list and the
EXCEPT clause",
+    get_namespace_name(relns),
+    RelationGetRelationName(pri->relation)));

Make use of the new function to get fully qualified names and replace
\"%s.%s\" with \"%s\".

~~~

12.
+ /*
+ * For FOR ALL TABLES, EXCEPT entries are processed by
+ * AlterPublicationTables(), so merge them in.  For TABLES IN SCHEMA,
+ * they are handled separately by AlterPublicationExceptTables().
+ */
+ if (stmt->for_all_tables)
+ relations = list_concat(relations, exceptrelations);
  AlterPublicationTables(stmt, tup, relations, pstate->p_sourcetext,
     schemaidlist != NIL);
  AlterPublicationSchemas(stmt, tup, schemaidlist);
+ AlterPublicationExceptTables(stmt, tup, exceptrelations, schemaidlist);

Would it be simpler if AlterPublicationExceptTables was merged (or
delegated from) the AlterPublicationSchemas?

======
src/bin/pg_dump/t/002_pg_dump.pl

13.
+ 'CREATE PUBLICATION pub11' => {
+ create_order => 50,
+ create_sql =>
+   'CREATE PUBLICATION pub11 FOR TABLES IN SCHEMA dump_test EXCEPT
(TABLE dump_test.test_table);',
+ regexp => qr/^
+ \QCREATE PUBLICATION pub11 WITH (publish = 'insert, update, delete,
truncate');\E
+ /xm,
+ like => { %full_runs, section_post_data => 1, },
+ },
+
+ 'ALTER PUBLICATION pub11 ADD TABLES IN SCHEMA dump_test EXCEPT
(dump_test.test_table)'
+   => {
+ regexp => qr/^
+ \QALTER PUBLICATION pub11 ADD TABLES IN SCHEMA dump_test EXCEPT
(TABLE ONLY test_table);\E
+ /xm,
+ like => { %full_runs, section_post_data => 1, },
+   },
+
+ 'CREATE PUBLICATION pub12' => {
+ create_order => 50,
+ create_sql =>
+   'CREATE PUBLICATION pub12 FOR TABLES IN SCHEMA dump_test EXCEPT
(TABLE dump_test.test_table, dump_test.test_second_table);',
+ regexp => qr/^
+ \QCREATE PUBLICATION pub12 WITH (publish = 'insert, update, delete,
truncate');\E
+ /xm,
+ like => { %full_runs, section_post_data => 1, },
+ },
+
+ 'ALTER PUBLICATION pub12 ADD TABLES IN SCHEMA dump_test EXCEPT
(dump_test.test_table, dump_test.test_second_table)'
+   => {
+ regexp => qr/^
+ \QALTER PUBLICATION pub12 ADD TABLES IN SCHEMA dump_test EXCEPT
(TABLE ONLY test_table, TABLE ONLY test_second_table);\E
+ /xm,
+ like => { %full_runs, section_post_data => 1, },
+   },
+

Should not need to specify schema-qualified names in the CREATE
PUBLICATION or the ALTER PUBLICATION. I think a better test would have
one of each (e.g. don't qualify the 'dump_test.test_table') in any of
those SQL.

======
src/bin/psql/tab-complete.in.c

14.
+ else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES",
"IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) &&
ends_with(prev_wd, ','))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables);
+ else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES",
"IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) &&
!ends_with(prev_wd, ','))
+ COMPLETE_WITH(")");

I've not tested this, but the code looks the same. so I suspect this
suffers the same problem where it lists potentially all tables instead
of just the table of the current schema. Maybe this is an unavoidable
quirk...

======
src/test/regress/sql/publication.sql

15.
Should you add a some more test cases?

e.g. Pass with EXCEPT without the schema-qualified name.
e.g. Pass with multiple excepted tables.
e.g. Fail because non-existing table name.
e.g. Fail because table not in schema.
e.g. Fail syntax because missing keyword TABLE.
e.g. do a DROP TABLES IN SCHEMA to test that the except tables gove removed too

======
Kind Regards,
Peter Smith.
Fujitsu Australia.





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-05-26 05:56  Peter Smith <smithpb2250@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  2 siblings, 1 reply; 196+ messages in thread

From: Peter Smith @ 2026-05-26 05:56 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Hi Nisha.

Some review comments for patch v6-0003.

======
Commit Message

1.
Extend AlterPublicationExceptTables() with the AP_SetObjects case,
which redefine the publication and replaces the entire EXCEPT list.

~

/redefine/redefines/

======
doc/src/sgml/ref/alter_publication.sgml

2.
-
-<phrase>and <replaceable
class="parameter">except_table_object</replaceable> is:</phrase>
-
-   [ ONLY ] <replaceable class="parameter">table_name</replaceable> [ * ]

IIUC this is just removing some duplicate entry in the synopsis that
was not supposed to be there in the first place.

~~~

3.
    The <literal>EXCEPT</literal> clause can be used with
-   <literal>ADD TABLES IN SCHEMA</literal> to exclude specific tables from a
+   <literal>ADD TABLES IN SCHEMA</literal> and
+   <literal>SET TABLES IN SCHEMA</literal> to exclude specific tables from a
    schema-level publication. <literal>EXCEPT</literal> is not supported with
    <literal>DROP TABLES IN SCHEMA</literal>; instead, dropping a schema from
    the publication automatically removes all of its associated

3a.
This whole description section seems arranged in a confusing way IMO.
Anyway, it is not all the fault of the current patch. But I don't
think it should be talking about "SET TABLES IN SCHEMA" here because
that was all mentioned already in the earlier "third variant"
paragraph.

~

3b.
That last sentence all about EXCEPT with DROP TABLES IN SCHEMA seems
redundant to me. It is not allowed by the synopsis, so there is no
possible confusion about it being supported. Isn't it better to just
say nothing?

~~~

EXCEPT

4.
      <para>
       Specifies tables to be excluded from a schema-level publication entry.
       This clause may be used with <literal>ADD TABLES IN SCHEMA</literal>
-      and not with <literal>DROP TABLES IN SCHEMA</literal>.  Each named
-      table must belong to the schema specified in the same
-      <literal>TABLES IN SCHEMA</literal> clause.  Table names may be
-      schema-qualified or unqualified; unqualified names are implicitly
-      qualified with the schema named in the same clause.  See
-      <xref linkend="sql-createpublication"/> for further details on the
+      and <literal>SET TABLES IN SCHEMA</literal>, and not with
+      <literal>DROP TABLES IN SCHEMA</literal>.  Each named table must belong
+      to the schema specified in the same <literal>TABLES IN SCHEMA</literal>
+      clause.  Table names may be schema-qualified or unqualified; unqualified
+      names are implicitly qualified with the schema named in the same clause.
+      See <xref linkend="sql-createpublication"/> for further details on the
       semantics of <literal>EXCEPT</literal>.
      </para>

4a.
IMO there is no reason to mention the "DROP TABLES IN SCHEMA" has no
EXCEPT. That is not possible just by looking at the synopsis, so there
is no ambiguity. Why say anything at all?

~

4b.
This description about EXCEPT is missing talking about FOR ALL TABLES
EXCEPT, but IIRC I already reported that in a previous review.

~~~

EXAMPLES

5.
+   Replace the schema list of <structname>sales_publication</structname> with
+   <structname>sales</structname>, excluding only
+   <structname>sales.drafts</structname> (any previously excluded tables for
+   that schema are replaced, and schemas previously in the publication are
+   removed):

BEFORE
(any previously excluded tables for that schema are replaced, and
schemas previously in the publication are removed):

SUGGESTION
Other than sales.drafts, any previously excluded tables for schema
sales are no longer excluded. Any schemas previously in the
sales_publication are removed.

~~~

6.
+<programlisting>
+ALTER PUBLICATION sales_publication SET TABLES IN SCHEMA sales EXCEPT
(TABLE sales.drafts);
+</programlisting>

Don't fully qualify that table in the SQL example.

======
src/backend/commands/publicationcmds.c

AlterPublicationExceptTables:

7.
- * Nothing to do if no EXCEPT entries.
+ * Nothing to do if no EXCEPT entries, except in SET: for that it is quite
+ * possible that the user has removed all exceptions, in which case we
+ * need to drop any existing ones.

Maybe reword this because it is a bit odd to have the word "except"
with the keyword "EXCEPT".

SUGGESTION
Nothing to do if there are no EXCEPT entries, unless handling the SET
command, because if the user has removed all exceptions we need to
drop any existing ones.

~~~

8.
+ {
+ List    *oldexceptrelids = NIL;
+ List    *newexceptrelids = NIL;
+ List    *delrelids = NIL;
+ List    *rels;
+ List    *explicitrelids;
+ ListCell   *lc;
+
+ rels = OpenTableList(exceptrelations);
+
+ /* Collect OIDs of the desired new except list. */
+ foreach(lc, rels)

There are multiple foreach() loops which can probably be simplified
all by using foreach_ptr(...) instead.

~~~

9.
+ /* Collect OIDs of the desired new except list. */
+ foreach(lc, rels)

/except/EXCEPT/

~~~

10.
+ ereport(ERROR,
+ errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("table \"%s.%s\" cannot appear in both the table list and the
EXCEPT clause",
+    get_namespace_name(relns),
+    RelationGetRelationName(pri->relation)));

Use the new function to get a fully qualified name and just substitute
\"%s\" instead of \"%s.%s\".

~~~

11.
+ /*
+ * Get the current set of except entries.  Only FOR ALL TABLES and
+ * schema-level publications can have except entries; for any other
+ * publication type oldexceptrelids stays NIL.
+ *
+ * Note: we check is_schema_publication() against the current catalog
+ * state (before AlterPublicationSchemas has run), so if the caller is
+ * doing SET TABLE t1 to convert a schema publication into a plain
+ * table publication, is_schema_publication() still returns true here.
+ * That is intentional: it lets us discover and clean up any stale
+ * except entries that belong to the old schema definition.
+ */
+ if (GetPublication(pubid)->alltables || is_schema_publication(pubid))
+ oldexceptrelids = GetExcludedPublicationTables(pubid,
+    PUBLICATION_PART_ROOT);
+
+ /* Build a list of old except entries not present in the new list. */
+ foreach(lc, oldexceptrelids)
+ {
+ Oid oldrelid = lfirst_oid(lc);
+
+ if (!list_member_oid(newexceptrelids, oldrelid))
+ delrelids = lappend_oid(delrelids, oldrelid);
+ }
+
+ /* Drop old except entries not present in the new list. */
+ foreach(lc, delrelids)

There are multiple comments here mentioning "except entries", but I
think they should say "EXCEPT entries".

~~~

PublicationDropSchemas:

12.
+ /*
+ * Collect prexcept rows for tables belonging to this schema before
+ * removing the schema entry.  GetExcludedPublicationTables relies on
+ * is_schema_publication(), which scans pg_publication_namespace; if
+ * this is the last schema in the publication, performDeletion() below
+ * would remove that row and make is_schema_publication() return
+ * false, tripping the assertion.
+ */

What assertion?

~~~

13.
+ foreach(elc, exceptoids)
+ {
+ Oid relid = lfirst_oid(elc);
+ Oid proid;

Maybe this can be changed to be a foreach_oid(...) loop.

======
src/bin/psql/tab-complete.in.c

14.
+ else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES",
"IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) &&
ends_with(prev_wd, ','))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables);

Not sure if this also ought to be
'Query_for_list_of_tables_in_schema', instead of
'Query_for_list_of_tables'.

======
src/test/regress/sql/publication.sql

15.
+-- error: EXCEPT is not allowed with DROP

I think we should keep all the SET tests together. The DROP test seems
to be between other SET tests.

~~~

16.
Perhaps there should be some more tests -- eg. a test case to hit this
new error "table \"%s.%s\" cannot appear in both the table list and
the EXCEPT clause"

======
src/test/subscription/t/037_except.pl

17.
+$node_publisher->safe_psql(
+ 'postgres', qq(
+ INSERT INTO sch1.tab_published VALUES (7);
+ INSERT INTO sch1.tab_excluded VALUES (7);
+));
+$node_publisher->wait_for_catchup('sch_sub');
+
+$result =
+  $node_subscriber->safe_psql('postgres',
+ "SELECT count(*) FROM sch1.tab_excluded");
+is($result, qq(7),
+ 'ALTER ... SET TABLES IN SCHEMA EXCEPT: newly included table is replicated'
+);
+$result =
+  $node_subscriber->safe_psql('postgres',
+ "SELECT count(*) FROM sch1.tab_published");
+is($result, qq(6),
+ 'ALTER ... SET TABLES IN SCHEMA EXCEPT: now-excluded table is not replicated'
+);

Instead of having to keep track of the running totals IMO it might be
simpler if you just did "SELECT ... WHERE a = 7;" then the answer
would be just 1 or 0 rows.

~~~

18.
+# SET without EXCEPT: clears the except list; both tables are now published.
+# tab_published will be re-synced because REFRESH removed its entry when it was
+# excluded.  Truncate the subscriber copy beforehand so the re-sync produces
+# a predictable count: publisher has 7 rows (6 original + INSERT(7)), so the
+# subscriber ends up with 7 after re-sync, then 8 after INSERT(8).

This is similar to my previous comment. There is lots of tricky
commentary here because you are trying to keep track of running totals
of rows.

I think most of this might not be needed if you changed the checks to
do ""SELECT ... WHERE a = 8;", so then you are just expecting row
count to be 1 for both tables.

======
Kind Regards,
Peter Smith.
Fujitsu Australia





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-05-28 11:26  Nisha Moond <nisha.moond412@gmail.com>
  parent: Peter Smith <smithpb2250@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: Nisha Moond @ 2026-05-28 11:26 UTC (permalink / raw)
  To: Peter Smith <smithpb2250@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

 On Fri, May 22, 2026 at 7:57 AM Peter Smith <smithpb2250@gmail.com> wrote:
>
> Hi Nisha.
>
> Here are some review comments for patch v6-0001.
>

Thanks for the review. All comments are addressed in v7. Please find
responses below for a few of the comments.

> ======
> src/backend/catalog/pg_publication.c
>
> GetTopMostAncestorInPublication:
>
> 1.
> +GetTopMostAncestorInPublication(Oid puboid, List *ancestors,
> + int *ancestor_level, List *except_pubids)
>
> I am having dificulty understanding this function. There needs to be a
> description what does the input parameter 'except_pubids' mean. The
> param name doesn't tell me anything much -- just that it is a list of
> pubids that "something" (what?) is excluded from. And how does that
> relate to the 'ancestors'?
>

Updated the function comments to explain except_pubids.

> ~~~
>
> 2.
>   {
>   aschemaPubids = GetSchemaPublications(get_rel_namespace(ancestor));
> - if (list_member_oid(aschemaPubids, puboid))
> + if (list_member_oid(aschemaPubids, puboid) &&
> + !list_member_oid(except_pubids, puboid))
>
> Is this new code in the right place? I'm not 100% sure of the
> 'except_pubids' details, but shouldn't it be checked sooner? e.g.  if
> we know already that this pubid is no good
> (!list_member_oid(except_pubids, puboid)) then what is the point to
> even assign/check aschemaPubids?
>

except_pubids represents the set of publication OIDs from which the
root relation has been explicitly excluded via EXCEPT (TABLE ...).
But yes, we can check it before computing schemaPubids. Fixed.

> ~~~
>
> 3.
> + if (is_except)
> + ereport(ERROR,
> + (errcode(ERRCODE_DUPLICATE_OBJECT),
> + errmsg("table \"%s\" cannot be added because it is excluded from
> publication \"%s\"",
> + RelationGetQualifiedRelationName(targetrel),
> + pub->name)));
> + else
> + ereport(ERROR,
> + (errcode(ERRCODE_DUPLICATE_OBJECT),
> + errmsg("relation \"%s\" is already member of publication \"%s\"",
> + RelationGetRelationName(targetrel), pub->name)));
>
> Fully qualified 'targetrel' in the first error, but not in the second? Is it OK?
>

IMO, we should use fully qualified names in both cases. Though the
second error is not part of this patch, I’ve updated it as well.
Please let me know if you think otherwise.

> ======
> src/backend/replication/pgoutput/pgoutput.c
>
> get_rel_sync_entry:
>
...
>
> 5b.
> Actually, this is becoming a GENERAL comment. There too many ways that
> these EXCEPT tables are getting named, and it is causing confusion:
> - except_pubids
> - exceptlist
> - exceptrelations
> - exceptrels
> - except_relid
> - except_tables
> - schemaExceptPubids
>
> Can we standardize on some common names, to make all the code more consistent?
>

I have now used the "except_" prefix consistently for all names to
avoid confusion. Also updated the naming in all places as below:
except_rel_names: parse-level table names in EXCEPT
except_rels: internal relations in the EXCEPT list (opened/accessed)
except_relids: list of relation OIDs wherever used
except_pubids: publication OIDs from which a given relation (or its
root) is excluded

> ~
>
> 5c.
> Previously, the result of 'get_partition_ancestors' was being freed,
> but now it is not. I'm not sure how importatnt that is, because I
> found other examples in PG source code also not freeing...
>

Sorry, this was mistakenly removed in v6 while cleaning up the code,
and I did not verify it against the older version. Fixed now.

> ======
> src/bin/psql/tab-complete.in.c
>
> 6.
> + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES",
> "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) &&
> ends_with(prev_wd, ','))
> + COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables);
>
> I'm not sure if this is working as intended.
>
> When testing for multiple except tables I get results like:
> ----
> test_pub=# create publication pub1 for tables IN SCHEMA myschema <TAB>
> EXCEPT ( TABLE  WITH (
> test_pub=# create publication pub1 for tables IN SCHEMA myschema
> except ( table <TAB>
> test_pub=# create publication pub1 for tables IN SCHEMA myschema
> except ( table myschema.t<TAB>
> myschema.t1  myschema.t2  myschema.t3
> test_pub=# create publication pub1 for tables IN SCHEMA myschema
> except ( table myschema.t1,<TAB>
> information_schema.  myschema.            public.              t1
>              t2                   t3
> ----
>
> Note: it is offering suggstions for schema names outside of the
> "myschema". Should this code be calling
> Query_for_list_of_tables_in_schema instead of
> Query_for_list_of_tables?
>

For this case, I don't think it's really possible to keep suggesting
after a comma. Even if we handle a fixed number of comma-separated
entries, the same problem reappears with the next entry.
Query_for_list_of_tables_in_schema needs a correct schema reference,
but with each comma the relative offset changes, so there is no single
fixed prev*_wd that can reliably point to the schema across all
entries.

But I see, the current call to Query_for_list_of_tables is clearly
incorrect here. I have now suppressed suggestions after a comma,
instead of showing incorrect suggestions.
Thoughts?

--
Thanks,
Nisha





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-05-28 11:28  Nisha Moond <nisha.moond412@gmail.com>
  parent: Peter Smith <smithpb2250@gmail.com>
  0 siblings, 0 replies; 196+ messages in thread

From: Nisha Moond @ 2026-05-28 11:28 UTC (permalink / raw)
  To: Peter Smith <smithpb2250@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Fri, May 22, 2026 at 11:00 AM Peter Smith <smithpb2250@gmail.com> wrote:
>
> Hi Nisha.
>
> Here are some review comments for patch v6-0002.
>

Thanks for the review. All comments are addressed in v7. Please find
responses below for a few of the comments.

>
> EXCEPT
>
> 5.
> +   <varlistentry>
> +    <term><literal>EXCEPT ( <replaceable
> class="parameter">except_table_object</replaceable> [, ... ]
> )</literal></term>
> +    <listitem>
> +     <para>
> +      Specifies tables to be excluded from a schema-level publication entry.
> +      This clause may be used with <literal>ADD TABLES IN SCHEMA</literal>
> +      and not with <literal>DROP TABLES IN SCHEMA</literal>.  Each named
> +      table must belong to the schema specified in the same
> +      <literal>TABLES IN SCHEMA</literal> clause.  Table names may be
> +      schema-qualified or unqualified; unqualified names are implicitly
> +      qualified with the schema named in the same clause.  See
> +      <xref linkend="sql-createpublication"/> for further details on the
> +      semantics of <literal>EXCEPT</literal>.
> +     </para>
> +    </listitem>
> +   </varlistentry>
> +
>
> 5a.
> Oh! If this EXCEPT part was previously missing even for the "FOR ALL
> TABLES", then IMO that is a separate bug that should be in another
> thread and patched/fixed asap, then your patch should just make small
> changes to to it.
>

Agree. I'll make a separate patch for it and start a thread.

> ======
> src/backend/commands/publicationcmds.c
>
> AlterPublicationSchemas:
>
> 7.
> + /*
> + * Increment the command counter so that is_schema_publication() in
> + * GetExcludedPublicationTables() can see the just-inserted schema
> + * rows when AlterPublicationExceptTables runs next.
> + */
> + CommandCounterIncrement();
>
> Should this cut/paste common code be done afterwards just if
> stmt->action == AP_AddObjects/SetObjects ?
>

Agree, fixed.

> ~~~
>
> AlterPublicationExceptTables:
>
> 8.
> + /*
> + * This function handles EXCEPT entries for schema-level publications
> + * only.  For FOR ALL TABLES publications, EXCEPT entries are already
> + * processed by AlterPublicationTables().
> + */
> + if (schemaidlist == NIL && !is_schema_publication(pubid))
> + return;
>
> Huh? It seems contrary to the function comment that was also talking
> about "FOR ALL TABLES".
>

Corrected the function comments. It is for only schema publications.

> Should this function really be called something different like
> 'AlterPublicationSchemaExceptTables'?
>

Done. Renamed as suggested.

> ~~~
>
> 12.
> + /*
> + * For FOR ALL TABLES, EXCEPT entries are processed by
> + * AlterPublicationTables(), so merge them in.  For TABLES IN SCHEMA,
> + * they are handled separately by AlterPublicationExceptTables().
> + */
> + if (stmt->for_all_tables)
> + relations = list_concat(relations, exceptrelations);
>   AlterPublicationTables(stmt, tup, relations, pstate->p_sourcetext,
>      schemaidlist != NIL);
>   AlterPublicationSchemas(stmt, tup, schemaidlist);
> + AlterPublicationExceptTables(stmt, tup, exceptrelations, schemaidlist);
>
> Would it be simpler if AlterPublicationExceptTables was merged (or
> delegated from) the AlterPublicationSchemas?
>

+1, fixed.

--
Thanks,
Nisha





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-05-28 11:28  Nisha Moond <nisha.moond412@gmail.com>
  parent: Peter Smith <smithpb2250@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: Nisha Moond @ 2026-05-28 11:28 UTC (permalink / raw)
  To: Peter Smith <smithpb2250@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Tue, May 26, 2026 at 11:27 AM Peter Smith <smithpb2250@gmail.com> wrote:
>
> Hi Nisha.
>
> Some review comments for patch v6-0003.
>

Thanks for the review. All comments are addressed in v7. Please find
responses below for a few of the comments.

>
> 3.
>     The <literal>EXCEPT</literal> clause can be used with
> -   <literal>ADD TABLES IN SCHEMA</literal> to exclude specific tables from a
> +   <literal>ADD TABLES IN SCHEMA</literal> and
> +   <literal>SET TABLES IN SCHEMA</literal> to exclude specific tables from a
>     schema-level publication. <literal>EXCEPT</literal> is not supported with
>     <literal>DROP TABLES IN SCHEMA</literal>; instead, dropping a schema from
>     the publication automatically removes all of its associated
>
> 3a.
> This whole description section seems arranged in a confusing way IMO.
> Anyway, it is not all the fault of the current patch. But I don't
> think it should be talking about "SET TABLES IN SCHEMA" here because
> that was all mentioned already in the earlier "third variant"
> paragraph.
>

Right. it seems repeating. Removed "SET TABLES IN SCHEMA" related info.

> ~
>
> 3b.
> That last sentence all about EXCEPT with DROP TABLES IN SCHEMA seems
> redundant to me. It is not allowed by the synopsis, so there is no
> possible confusion about it being supported. Isn't it better to just
> say nothing?
>

Okay, that makes sense. Fixed.

> ~~~
>
> 4b.
> This description about EXCEPT is missing talking about FOR ALL TABLES
> EXCEPT, but IIRC I already reported that in a previous review.
>

Yes, we can handle this in a separate patch.

> ~~~
>
> PublicationDropSchemas:
>
> 12.
> + /*
> + * Collect prexcept rows for tables belonging to this schema before
> + * removing the schema entry.  GetExcludedPublicationTables relies on
> + * is_schema_publication(), which scans pg_publication_namespace; if
> + * this is the last schema in the publication, performDeletion() below
> + * would remove that row and make is_schema_publication() return
> + * false, tripping the assertion.
> + */
>
> What assertion?
>

The assertion is Assert(GetPublication(pubid)->alltables ||
is_schema_publication(pubid)) in GetExcludedPublicationTables().
I’ve trimmed the comment a bit, as it felt slightly over-explained.
~~~~

Please find the updated patch-set v7 attached.

--
Thanks,
Nisha

Attachments: download all (3 files, .tar.gz)

v7-0001-Support-EXCEPT-clause-for-schema-level-publicatio.patch (application/x-patch, 47.1K) download From b46bea926dfb201005201bbefda3716ba7a8beee Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Mon, 4 May 2026 12:49:27 +0530 Subject: [PATCH v7 1/3] Support EXCEPT clause for schema-level publications Extend table exclusion support in publications to allow specific tables to be excluded from schema-level publications using an EXCEPT clause in CREATE PUBLICATION. Supported syntax: CREATE PUBLICATION <pub> FOR TABLES IN SCHEMA s EXCEPT (TABLE t1,...); --- doc/src/sgml/logical-replication.sgml | 3 +- doc/src/sgml/ref/create_publication.sgml | 22 +++- src/backend/catalog/pg_publication.c | 97 +++++++++++--- src/backend/commands/publicationcmds.c | 65 ++++++++-- src/backend/parser/gram.y | 52 +++++++- src/backend/replication/pgoutput/pgoutput.c | 30 ++++- src/bin/psql/describe.c | 18 +++ src/bin/psql/tab-complete.in.c | 24 +++- src/include/catalog/pg_publication.h | 3 +- src/include/nodes/parsenodes.h | 2 + src/test/regress/expected/publication.out | 106 +++++++++++++++- src/test/regress/sql/publication.sql | 69 +++++++++- src/test/subscription/t/037_except.pl | 133 +++++++++++++++++++- 13 files changed, 577 insertions(+), 47 deletions(-) diff --git a/doc/src/sgml/logical-replication.sgml b/doc/src/sgml/logical-replication.sgml index 9e7868487de..1433d2660fe 100644 --- a/doc/src/sgml/logical-replication.sgml +++ b/doc/src/sgml/logical-replication.sgml @@ -117,7 +117,8 @@ or <literal>FOR ALL SEQUENCES</literal>. Unlike tables, sequences can be synchronized at any time. For more information, see <xref linkend="logical-replication-sequences"/>. When a publication is - created with <literal>FOR ALL TABLES</literal>, a table or set of tables can + created with <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal>, a table or set of tables can be explicitly excluded from publication using the <link linkend="sql-createpublication-params-for-except-table"><literal>EXCEPT</literal></link> clause. diff --git a/doc/src/sgml/ref/create_publication.sgml b/doc/src/sgml/ref/create_publication.sgml index f82d640e6ca..7fa0bd11f7b 100644 --- a/doc/src/sgml/ref/create_publication.sgml +++ b/doc/src/sgml/ref/create_publication.sgml @@ -28,7 +28,7 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA <replaceable class="parameter">tables_in_schema</replaceable> [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -39,6 +39,10 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <replaceable class="parameter">table_object</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] [ WHERE ( <replaceable class="parameter">expression</replaceable> ) ] +<phrase>and <replaceable class="parameter">tables_in_schema</replaceable> is:</phrase> + + { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] + <phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> TABLE <replaceable class="parameter">table_object</replaceable> [, ... ] @@ -142,6 +146,8 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <para> Marks the publication as one that replicates changes for all tables in the specified list of schemas, including tables created in the future. + Tables listed in the <literal>EXCEPT</literal> clause for a given schema + are excluded from the publication. </para> <para> @@ -173,7 +179,7 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <para> Marks the publication as one that replicates changes for all tables in the database, including tables created in the future. Tables listed in - <literal>EXCEPT</literal> clause are excluded from the publication. + the <literal>EXCEPT</literal> clause are excluded from the publication. </para> </listitem> </varlistentry> @@ -198,7 +204,8 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <listitem> <para> This clause specifies a list of tables to be excluded from the - publication. + publication. It can be used with <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal>. </para> <para> For inherited tables, if <literal>ONLY</literal> is specified before the @@ -515,6 +522,15 @@ CREATE PUBLICATION production_publication FOR TABLE users, departments, TABLES I CREATE PUBLICATION sales_publication FOR TABLES IN SCHEMA marketing, sales; </programlisting></para> + <para> + Create a publication that publishes all changes for all the tables present in + the schema <structname>sales</structname>, except + <structname>internal</structname> and <structname>drafts</structname>: +<programlisting> +CREATE PUBLICATION sales_filtered FOR TABLES IN SCHEMA sales EXCEPT (TABLE internal, drafts); +</programlisting> + </para> + <para> Create a publication that publishes all changes for table <structname>users</structname>, but replicates only columns <structname>user_id</structname> and diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index 5c457d9aca8..b4c5a317869 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -444,9 +444,14 @@ GetPubPartitionOptionRelations(List *result, PublicationPartOpt pub_partopt, * * Note that the list of ancestors should be ordered such that the topmost * ancestor is at the end of the list. + * + * except_pubids is a list of publication OIDs whose schema membership + * should be ignored for the ancestor (because the ancestor is in their + * EXCEPT clause). */ Oid -GetTopMostAncestorInPublication(Oid puboid, List *ancestors, int *ancestor_level) +GetTopMostAncestorInPublication(Oid puboid, List *ancestors, + int *ancestor_level, List *except_pubids) { ListCell *lc; Oid topmost_relid = InvalidOid; @@ -470,7 +475,7 @@ GetTopMostAncestorInPublication(Oid puboid, List *ancestors, int *ancestor_level if (ancestor_level) *ancestor_level = level; } - else + else if (!list_member_oid(except_pubids, puboid)) { aschemaPubids = GetSchemaPublications(get_rel_namespace(ancestor)); if (list_member_oid(aschemaPubids, puboid)) @@ -545,18 +550,30 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, * duplicates, it's here just to provide nicer error message in common * case. The real protection is the unique key on the catalog. */ - if (SearchSysCacheExists2(PUBLICATIONRELMAP, ObjectIdGetDatum(relid), - ObjectIdGetDatum(pubid))) + tup = SearchSysCache2(PUBLICATIONRELMAP, ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + + if (HeapTupleIsValid(tup)) { + bool is_except = ((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept; + + ReleaseSysCache(tup); table_close(rel, RowExclusiveLock); if (if_not_exists) return InvalidObjectAddress; - ereport(ERROR, - (errcode(ERRCODE_DUPLICATE_OBJECT), - errmsg("relation \"%s\" is already member of publication \"%s\"", - RelationGetRelationName(targetrel), pub->name))); + if (is_except) + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("relation \"%s\" cannot be added because it is excluded from publication \"%s\"", + RelationGetQualifiedRelationName(targetrel), + pub->name))); + else + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("relation \"%s\" is already member of publication \"%s\"", + RelationGetQualifiedRelationName(targetrel), pub->name))); } check_publication_add_relation(pri); @@ -982,12 +999,13 @@ GetIncludedPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) * Gets list of table oids that were specified in the EXCEPT clause for a * publication. * - * This should only be used FOR ALL TABLES publications. + * This is used for FOR ALL TABLES and FOR TABLES IN SCHEMA publications, + * both of which support EXCEPT TABLE. */ List * GetExcludedPublicationTables(Oid pubid, PublicationPartOpt pub_partopt) { - Assert(GetPublication(pubid)->alltables); + Assert(GetPublication(pubid)->alltables || is_schema_publication(pubid)); return get_publication_relations(pubid, pub_partopt, true); } @@ -1049,13 +1067,13 @@ GetAllPublicationRelations(Oid pubid, char relkind, bool pubviaroot) TableScanDesc scan; HeapTuple tuple; List *result = NIL; - List *exceptlist = NIL; + List *except_relids = NIL; Assert(!(relkind == RELKIND_SEQUENCE && pubviaroot)); /* EXCEPT filtering applies only to relations, not sequences */ if (relkind == RELKIND_RELATION) - exceptlist = GetExcludedPublicationTables(pubid, pubviaroot ? + except_relids = GetExcludedPublicationTables(pubid, pubviaroot ? PUBLICATION_PART_ROOT : PUBLICATION_PART_LEAF); @@ -1075,7 +1093,7 @@ GetAllPublicationRelations(Oid pubid, char relkind, bool pubviaroot) if (is_publishable_class(relid, relForm) && !(relForm->relispartition && pubviaroot) && - !list_member_oid(exceptlist, relid)) + !list_member_oid(except_relids, relid)) result = lappend_oid(result, relid); } @@ -1097,7 +1115,7 @@ GetAllPublicationRelations(Oid pubid, char relkind, bool pubviaroot) if (is_publishable_class(relid, relForm) && !relForm->relispartition && - !list_member_oid(exceptlist, relid)) + !list_member_oid(except_relids, relid)) result = lappend_oid(result, relid); } @@ -1232,22 +1250,67 @@ GetSchemaPublicationRelations(Oid schemaid, PublicationPartOpt pub_partopt) /* * Gets the list of all relations published by FOR TABLES IN SCHEMA - * publication. + * publication, excluding any tables listed in the EXCEPT clause. */ List * GetAllSchemaPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) { List *result = NIL; List *pubschemalist = GetPublicationSchemas(pubid); + List *except_relids = NIL; ListCell *cell; + /* get the list of tables excluded via EXCEPT TABLE for this publication */ + if (pubschemalist != NIL) + except_relids = GetExcludedPublicationTables(pubid, pub_partopt); + foreach(cell, pubschemalist) { Oid schemaid = lfirst_oid(cell); List *schemaRels = NIL; schemaRels = GetSchemaPublicationRelations(schemaid, pub_partopt); - result = list_concat(result, schemaRels); + + if (except_relids != NIL) + { + /* filter out any tables that appear in the EXCEPT list */ + ListCell *rlc; + + foreach(rlc, schemaRels) + { + Oid relid = lfirst_oid(rlc); + bool excluded = list_member_oid(except_relids, relid); + + /* + * Also exclude any relation whose partition ancestor is in + * the EXCEPT list. This matters when pub_partopt is + * PUBLICATION_PART_ROOT: the except list holds only the root + * OID, but the schema scan may also return individual + * partition relations that live in the same schema. + */ + if (!excluded && get_rel_relispartition(relid)) + { + List *ancestors = get_partition_ancestors(relid); + ListCell *alc; + + foreach(alc, ancestors) + { + if (list_member_oid(except_relids, lfirst_oid(alc))) + { + excluded = true; + break; + } + } + list_free(ancestors); + } + + if (!excluded) + result = lappend_oid(result, relid); + } + list_free(schemaRels); + } + else + result = list_concat(result, schemaRels); } return result; @@ -1381,7 +1444,7 @@ is_table_publishable_in_publication(Oid relid, Publication *pub) * the publication, it should be included (return true). */ if (relispartition && - OidIsValid(GetTopMostAncestorInPublication(pub->oid, ancestors, NULL))) + OidIsValid(GetTopMostAncestorInPublication(pub->oid, ancestors, NULL, NIL))) return !pub->pubviaroot; /* diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 440adb356ad..65ae40210db 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -181,7 +181,7 @@ parse_publication_options(ParseState *pstate, */ static void ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, - List **rels, List **exceptrels, List **schemas) + List **rels, List **except_rel_names, List **schemas) { ListCell *cell; PublicationObjSpec *pubobj; @@ -200,7 +200,7 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, { case PUBLICATIONOBJ_EXCEPT_TABLE: pubobj->pubtable->except = true; - *exceptrels = lappend(*exceptrels, pubobj->pubtable); + *except_rel_names = lappend(*except_rel_names, pubobj->pubtable); break; case PUBLICATIONOBJ_TABLE: pubobj->pubtable->except = false; @@ -305,7 +305,7 @@ pub_rf_contains_invalid_column(Oid pubid, Relation relation, List *ancestors, if (pubviaroot && relation->rd_rel->relispartition) { publish_as_relid - = GetTopMostAncestorInPublication(pubid, ancestors, NULL); + = GetTopMostAncestorInPublication(pubid, ancestors, NULL, NIL); if (!OidIsValid(publish_as_relid)) publish_as_relid = relid; @@ -389,7 +389,7 @@ pub_contains_invalid_column(Oid pubid, Relation relation, List *ancestors, */ if (pubviaroot && relation->rd_rel->relispartition) { - publish_as_relid = GetTopMostAncestorInPublication(pubid, ancestors, NULL); + publish_as_relid = GetTopMostAncestorInPublication(pubid, ancestors, NULL, NIL); if (!OidIsValid(publish_as_relid)) publish_as_relid = relid; @@ -849,7 +849,7 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) char publish_generated_columns; AclResult aclresult; List *relations = NIL; - List *exceptrelations = NIL; + List *except_rel_names = NIL; List *schemaidlist = NIL; /* must have CREATE privilege on database */ @@ -936,16 +936,16 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) /* Associate objects with the publication. */ ObjectsInPublicationToOids(stmt->pubobjects, pstate, &relations, - &exceptrelations, &schemaidlist); + &except_rel_names, &schemaidlist); if (stmt->for_all_tables) { /* Process EXCEPT table list */ - if (exceptrelations != NIL) + if (except_rel_names != NIL) { List *rels; - rels = OpenTableList(exceptrelations); + rels = OpenTableList(except_rel_names); PublicationAddTables(puboid, rels, true, NULL); CloseTableList(rels); } @@ -959,6 +959,8 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) } else if (!stmt->for_all_sequences) { + List *explicitrelids = NIL; + /* FOR TABLES IN SCHEMA requires superuser */ if (schemaidlist != NIL && !superuser()) ereport(ERROR, @@ -977,6 +979,19 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) schemaidlist != NIL, publish_via_partition_root); + /* + * Collect explicit table OIDs now, before we close the relation + * list, so that except-table validation below can check for + * contradictions without relying on a catalog scan that might not + * yet see the just-inserted rows. + */ + if (except_rel_names != NIL) + { + foreach_ptr(PublicationRelInfo, pri, rels) + explicitrelids = lappend_oid(explicitrelids, + RelationGetRelid(pri->relation)); + } + PublicationAddTables(puboid, rels, true, NULL); CloseTableList(rels); } @@ -989,6 +1004,34 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) */ LockSchemaList(schemaidlist); PublicationAddSchemas(puboid, schemaidlist, true, NULL); + + if (except_rel_names != NIL) + { + List *except_rels; + + except_rels = OpenTableList(except_rel_names); + + /* + * Validate that each excluded table is not also in the + * explicit table list (which would be contradictory). Use the + * in-memory explicitrelids collected above rather than + * re-reading the catalog, which may not yet see the + * just-inserted rows. + */ + foreach_ptr(PublicationRelInfo, pri, except_rels) + { + Oid except_relid = RelationGetRelid(pri->relation); + + if (list_member_oid(explicitrelids, except_relid)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" cannot appear in both the table list and the EXCEPT clause", + RelationGetQualifiedRelationName(pri->relation))); + } + + PublicationAddTables(puboid, except_rels, true, NULL); + CloseTableList(except_rels); + } } } @@ -1683,12 +1726,12 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) else { List *relations = NIL; - List *exceptrelations = NIL; + List *except_rel_names = NIL; List *schemaidlist = NIL; Oid pubid = pubform->oid; ObjectsInPublicationToOids(stmt->pubobjects, pstate, &relations, - &exceptrelations, &schemaidlist); + &except_rel_names, &schemaidlist); CheckAlterPublication(stmt, tup, relations, schemaidlist); @@ -1711,7 +1754,7 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) errmsg("publication \"%s\" does not exist", stmt->pubname)); - relations = list_concat(relations, exceptrelations); + relations = list_concat(relations, except_rel_names); AlterPublicationTables(stmt, tup, relations, pstate->p_sourcetext, schemaidlist != NIL); AlterPublicationSchemas(stmt, tup, schemaidlist); diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y index ff4e1388c55..4514ef7f9c2 100644 --- a/src/backend/parser/gram.y +++ b/src/backend/parser/gram.y @@ -58,6 +58,7 @@ #include "nodes/makefuncs.h" #include "nodes/nodeFuncs.h" #include "parser/parser.h" +#include "utils/builtins.h" #include "utils/datetime.h" #include "utils/xml.h" @@ -11272,7 +11273,7 @@ AlterOwnerStmt: ALTER AGGREGATE aggregate_with_argtypes OWNER TO RoleSpec * pub_obj is one of: * * TABLE table [, ...] - * TABLES IN SCHEMA schema [, ...] + * TABLES IN SCHEMA schema [EXCEPT (TABLE table [, ...] )] [, ...] * *****************************************************************************/ @@ -11332,23 +11333,26 @@ PublicationObjSpec: $$->pubtable->columns = $3; $$->pubtable->whereClause = $4; } - | TABLES IN_P SCHEMA ColId + | TABLES IN_P SCHEMA ColId opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_SCHEMA; $$->name = $4; + $$->except_tables = $5; $$->location = @4; } - | TABLES IN_P SCHEMA CURRENT_SCHEMA + | TABLES IN_P SCHEMA CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_CUR_SCHEMA; + $$->except_tables = $5; $$->location = @4; } - | ColId opt_column_list OptWhereClause + | ColId opt_column_list OptWhereClause opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $4; /* * If either a row filter or column list is specified, create * a PublicationTable object. @@ -11392,10 +11396,11 @@ PublicationObjSpec: $$->pubtable->columns = $2; $$->pubtable->whereClause = $3; } - | CURRENT_SCHEMA + | CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $2; $$->location = @1; } ; @@ -20784,6 +20789,8 @@ preprocess_pub_all_objtype_list(List *all_objects_list, List **pubobjects, /* * Process pubobjspec_list to check for errors in any of the objects and * convert PUBLICATIONOBJ_CONTINUATION into appropriate PublicationObjSpecType. + * Also flattens except_tables from TABLES IN SCHEMA nodes into the list so + * that ObjectsInPublicationToOids() sees them as top-level EXCEPT_TABLE entries. */ static void preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) @@ -20812,6 +20819,13 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLE) { + /* EXCEPT is not valid for table objects */ + if (pubobj->except_tables != NIL) + ereport(ERROR, + errcode(ERRCODE_SYNTAX_ERROR), + errmsg("EXCEPT is not allowed for TABLE publication objects"), + parser_errposition(pubobj->location)); + /* relation name or pubtable must be set for this type of object */ if (!pubobj->name && !pubobj->pubtable) ereport(ERROR, @@ -20860,6 +20874,34 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) errcode(ERRCODE_SYNTAX_ERROR), errmsg("invalid schema name"), parser_errposition(pubobj->location)); + + /* Flatten EXCEPT entries into the top-level list */ + foreach_ptr(PublicationObjSpec, eobj, pubobj->except_tables) + { + /* + * Unqualified names are implicitly qualified with the parent + * schema. Qualified names must match the parent schema — + * each EXCEPT clause is bound to exactly one schema, so + * cross-schema entries are rejected at parse time. + */ + if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLES_IN_SCHEMA) + { + const char *eobj_schemaname = eobj->pubtable->relation->schemaname; + const char *eobj_relname = eobj->pubtable->relation->relname; + + if (eobj_schemaname == NULL) + eobj->pubtable->relation->schemaname = pubobj->name; + else if (strcmp(eobj_schemaname, pubobj->name) != 0) + ereport(ERROR, + errcode(ERRCODE_SYNTAX_ERROR), + errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", + quote_qualified_identifier(eobj_schemaname, eobj_relname), + pubobj->name), + parser_errposition(eobj->location)); + } + } + pubobjspec_list = list_concat(pubobjspec_list, pubobj->except_tables); + pubobj->except_tables = NIL; } prevobjtype = pubobj->pubobjtype; diff --git a/src/backend/replication/pgoutput/pgoutput.c b/src/backend/replication/pgoutput/pgoutput.c index 4ecfcbff7ab..c5f17bf2338 100644 --- a/src/backend/replication/pgoutput/pgoutput.c +++ b/src/backend/replication/pgoutput/pgoutput.c @@ -2097,6 +2097,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) * are absorbed while decoding WAL. */ List *schemaPubids = GetSchemaPublications(schemaId); + List *except_pubids; ListCell *lc; Oid publish_as_relid = relid; int publish_ancestor_level = 0; @@ -2104,6 +2105,28 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) char relkind = get_rel_relkind(relid); List *rel_publications = NIL; + /* + * For the schema EXCEPT check, we must look up the top-most ancestor + * rather than the relation itself. check_publication_add_relation() + * prevents individual partitions from appearing in the EXCEPT clause, + * so only a root (non-partition) table can have prexcept = true. + * Using the partition's own OID would always return NIL and miss the + * exclusion. + */ + Oid root_relid; + + if (am_partition) + { + List *part_ancestors = get_partition_ancestors(relid); + + root_relid = llast_oid(part_ancestors); + list_free(part_ancestors); + } + else + root_relid = relid; + + except_pubids = GetRelationExcludedPublications(root_relid); + /* Reload publications if needed before use. */ if (!publications_valid) { @@ -2267,7 +2290,8 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) ancestor = GetTopMostAncestorInPublication(pub->oid, ancestors, - &level); + &level, + except_pubids); if (ancestor != InvalidOid) { @@ -2281,7 +2305,8 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) } if (list_member_oid(pubids, pub->oid) || - list_member_oid(schemaPubids, pub->oid) || + (list_member_oid(schemaPubids, pub->oid) && + !list_member_oid(except_pubids, pub->oid)) || ancestor_published) publish = true; } @@ -2360,6 +2385,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) list_free(pubids); list_free(schemaPubids); + list_free(except_pubids); list_free(rel_publications); entry->replicate_valid = true; diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c index e1449654f96..e5b1a70e05e 100644 --- a/src/bin/psql/describe.c +++ b/src/bin/psql/describe.c @@ -7038,6 +7038,24 @@ describePublications(const char *pattern) if (!addFooterToPublicationDesc(&buf, _("Tables from schemas:"), true, &cont)) goto error_return; + + if (pset.sversion >= 190000) + { + /* + * Get tables in the EXCEPT clause for this schema + * publication. + */ + printfPQExpBuffer(&buf, + "SELECT concat(c.relnamespace::regnamespace, '.', c.relname)\n" + "FROM pg_catalog.pg_class c\n" + " JOIN pg_catalog.pg_publication_rel pr ON c.oid = pr.prrelid\n" + "WHERE pr.prpubid = '%s'\n" + " AND pr.prexcept\n" + "ORDER BY 1", pubid); + if (!addFooterToPublicationDesc(&buf, _("Except tables:"), + true, &cont)) + goto error_return; + } } } else diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index de547a8cb37..fe11dc619ac 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -1065,6 +1065,15 @@ static const SchemaQuery Query_for_trigger_of_table = { "SELECT nspname FROM pg_catalog.pg_namespace "\ " WHERE nspname LIKE '%s'" +#define Query_for_list_of_tables_in_schema \ +"SELECT n.nspname || '.' || c.relname "\ +" FROM pg_catalog.pg_class c "\ +" JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "\ +" WHERE c.relkind IN (" CppAsString2(RELKIND_RELATION) ", " \ + CppAsString2(RELKIND_PARTITIONED_TABLE) ") "\ +" AND (n.nspname || '.' || c.relname) LIKE '%s' "\ +" AND n.nspname = '%s'" + /* Use COMPLETE_WITH_QUERY_VERBATIM with these queries for GUC names: */ #define Query_for_list_of_alter_system_set_vars \ "SELECT pg_catalog.lower(name) FROM pg_catalog.pg_settings "\ @@ -3787,8 +3796,19 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); - else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && (!ends_with(prev_wd, ','))) - COMPLETE_WITH("WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE", "WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* Complete "CREATE PUBLICATION <name> [...] WITH" */ else if (Matches("CREATE", "PUBLICATION", MatchAnyN, "WITH", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/include/catalog/pg_publication.h b/src/include/catalog/pg_publication.h index 89b4bb14f62..53e3d7c6f3d 100644 --- a/src/include/catalog/pg_publication.h +++ b/src/include/catalog/pg_publication.h @@ -191,7 +191,8 @@ extern List *GetPubPartitionOptionRelations(List *result, PublicationPartOpt pub_partopt, Oid relid); extern Oid GetTopMostAncestorInPublication(Oid puboid, List *ancestors, - int *ancestor_level); + int *ancestor_level, + List *except_pubids); extern bool is_publishable_relation(Relation rel); extern bool is_schema_publication(Oid pubid); diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h index 91377a6cde3..98a03c0eeda 100644 --- a/src/include/nodes/parsenodes.h +++ b/src/include/nodes/parsenodes.h @@ -4493,6 +4493,8 @@ typedef struct PublicationObjSpec PublicationObjSpecType pubobjtype; /* type of this publication object */ char *name; PublicationTable *pubtable; + List *except_tables; /* tables specified in the EXCEPT clause (for + * TABLES IN SCHEMA) */ ParseLoc location; /* token location, or -1 if unknown */ } PublicationObjSpec; diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 29e54b214a0..161db458f49 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -270,6 +270,12 @@ CREATE PUBLICATION testpub_foralltables_excepttable2 FOR ALL TABLES EXCEPT (test ERROR: syntax error at or near "testpub_tbl1" LINE 1: ..._foralltables_excepttable2 FOR ALL TABLES EXCEPT (testpub_tb... ^ +-- fail - EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testpub_tbl3); +ERROR: EXCEPT is not allowed for TABLE publication objects +LINE 2: FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testp... + ^ --------------------------------------------- -- SET ALL TABLES/SEQUENCES --------------------------------------------- @@ -470,7 +476,103 @@ HINT: Change the publication's EXCEPT clause using ALTER PUBLICATION ... SET AL RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Create same-named tables in public to verify unqualified EXCEPT entries +-- are qualified with the named schema, not public +CREATE TABLE testpub_nopk (foo int, bar int); +CREATE TABLE testpub_tbl_s1 (a int primary key, b text); +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + Publication testpub_schema_except1 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- Exclude multiple tables using unqualified names; same-named tables exist in +-- public to confirm unqualified names resolve to pub_test, not public +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + Publication testpub_schema_except2 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_nopk" + "pub_test.testpub_tbl_s1" + +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testp... + ^ +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); +ERROR: table "pub_test.testpub_tbl_s1" in EXCEPT clause does not belong to schema "public" +LINE 2: ...R TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.t... + ^ +-- Multiple schemas each with their own EXCEPT clause +CREATE PUBLICATION testpub_schema_except_multi + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_schema_except_multi + Publication testpub_schema_except_multi + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- fail: table appears in both the explicit table list and the EXCEPT clause +CREATE PUBLICATION testpub_except_conflict + FOR TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot appear in both the table list and the EXCEPT clause +-- fail: nonexistent table in EXCEPT clause +CREATE PUBLICATION testpub_except_norel + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- fail: partition cannot appear in EXCEPT clause; only root tables are allowed +CREATE TABLE pub_test.testpub_parted_s (a int) PARTITION BY LIST (a); +CREATE TABLE pub_test.testpub_part_s PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (1); +CREATE PUBLICATION testpub_except_partition + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); +ERROR: cannot specify relation "pub_test.testpub_part_s" in the publication EXCEPT clause +DETAIL: This operation is not supported for individual partitions. +-- fail: TABLE keyword is required for the first entry in the EXCEPT clause +CREATE PUBLICATION testpub_except_nokw + FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +ERROR: syntax error at or near "testpub_nopk" +LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + ^ +-- Cleanup +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP TABLE pub_test.testpub_parted_s CASCADE; +DROP TABLE testpub_nopk, testpub_tbl_s1; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +--------------------------------------------- +-- Tests for publications with SEQUENCES +--------------------------------------------- CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; -- FOR ALL SEQUENCES @@ -1522,7 +1624,7 @@ CREATE PUBLICATION testpub_fortbl FOR TABLE testpub_tbl1, pub_test.testpub_nopk; RESET client_min_messages; -- fail - already added ALTER PUBLICATION testpub_fortbl ADD TABLE testpub_tbl1; -ERROR: relation "testpub_tbl1" is already member of publication "testpub_fortbl" +ERROR: relation "public.testpub_tbl1" is already member of publication "testpub_fortbl" -- fail - already added CREATE PUBLICATION testpub_fortbl FOR TABLE testpub_tbl1; ERROR: publication "testpub_fortbl" already exists diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 041e14a4de6..9162d4d15a5 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -123,6 +123,9 @@ CREATE PUBLICATION testpub_foralltables_excepttable1 FOR ALL TABLES EXCEPT (TABL \d testpub_tbl1 -- fail - first table in the EXCEPT list should use TABLE keyword CREATE PUBLICATION testpub_foralltables_excepttable2 FOR ALL TABLES EXCEPT (testpub_tbl1, testpub_tbl2); +-- fail - EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testpub_tbl3); --------------------------------------------- -- SET ALL TABLES/SEQUENCES @@ -220,7 +223,71 @@ RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Create same-named tables in public to verify unqualified EXCEPT entries +-- are qualified with the named schema, not public +CREATE TABLE testpub_nopk (foo int, bar int); +CREATE TABLE testpub_tbl_s1 (a int primary key, b text); + +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + +-- Exclude multiple tables using unqualified names; same-named tables exist in +-- public to confirm unqualified names resolve to pub_test, not public +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); + +-- Multiple schemas each with their own EXCEPT clause +CREATE PUBLICATION testpub_schema_except_multi + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_schema_except_multi + +-- fail: table appears in both the explicit table list and the EXCEPT clause +CREATE PUBLICATION testpub_except_conflict + FOR TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: nonexistent table in EXCEPT clause +CREATE PUBLICATION testpub_except_norel + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- fail: partition cannot appear in EXCEPT clause; only root tables are allowed +CREATE TABLE pub_test.testpub_parted_s (a int) PARTITION BY LIST (a); +CREATE TABLE pub_test.testpub_part_s PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (1); +CREATE PUBLICATION testpub_except_partition + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); + +-- fail: TABLE keyword is required for the first entry in the EXCEPT clause +CREATE PUBLICATION testpub_except_nokw + FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + +-- Cleanup +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP TABLE pub_test.testpub_parted_s CASCADE; +DROP TABLE testpub_nopk, testpub_tbl_s1; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; + +--------------------------------------------- +-- Tests for publications with SEQUENCES +--------------------------------------------- CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 8c58d282eee..18c7b2c1fca 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -24,14 +24,17 @@ my $result; sub test_except_root_partition { - my ($pubviaroot) = @_; + my ($pubviaroot, $pubsql) = @_; + $pubsql //= + "CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1)"; + $pubsql .= " WITH (publish_via_partition_root = $pubviaroot)"; # If the root partitioned table is in the EXCEPT clause, all its # partitions are excluded from publication, regardless of the # publish_via_partition_root setting. $node_publisher->safe_psql( 'postgres', qq( - CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1) WITH (publish_via_partition_root = $pubviaroot); + $pubsql; INSERT INTO root1 VALUES (1), (101); )); $node_subscriber->safe_psql('postgres', @@ -223,6 +226,131 @@ $node_subscriber->safe_psql( test_except_root_partition('false'); test_except_root_partition('true'); +# Same validation using TABLES IN SCHEMA instead of FOR ALL TABLES. +my $schema_pub = + "CREATE PUBLICATION tap_pub_part FOR TABLES IN SCHEMA public EXCEPT (TABLE public.root1)"; +test_except_root_partition('false', $schema_pub); +test_except_root_partition('true', $schema_pub); + +# ============================================ +# EXCEPT test cases for TABLES IN SCHEMA +# ============================================ + +# Create a dedicated schema with two tables: one to be published and one to be +# excluded. Also create inherited tables to verify ONLY semantics. +$node_publisher->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_published AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.tab_excluded AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.parent (a int); + CREATE TABLE sch1.child (b int) INHERITS (sch1.parent); +)); + +$node_subscriber->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_published (a int); + CREATE TABLE sch1.tab_excluded (a int); + CREATE TABLE sch1.parent (a int); + CREATE TABLE sch1.child (b int) INHERITS (sch1.parent); +)); + +# Basic test: initial sync respects EXCEPT. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_excluded)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: initial sync copies included table'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: initial sync skips excluded table'); + +# DML: only the included table should be replicated. +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (6); + INSERT INTO sch1.tab_excluded VALUES (6); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(6), + 'TABLES IN SCHEMA EXCEPT: DML on included table is replicated'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: DML on excluded table is not replicated'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Inherited tables: excluding the parent (without ONLY) also excludes the child. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.parent)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.child VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.child"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: excluding parent (without ONLY) also excludes child' +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Test that EXCEPT (TABLE ONLY parent) excludes only the parent itself, not its +# child. Truncate child first so rows from the previous test are not copied by +# the initial table sync of the next subscription. +$node_publisher->safe_psql('postgres', 'TRUNCATE sch1.child'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE sch1.child'); +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE ONLY sch1.parent)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.child VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.child"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: ONLY parent in EXCEPT does not exclude child'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Cleanup schema tables before the multi-publication section. +$node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); +$node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); + # ============================================ # Test when a subscription is subscribing to multiple publications # ============================================ @@ -254,6 +382,7 @@ $node_publisher->safe_psql( DROP PUBLICATION tap_pub2; TRUNCATE tab1; )); +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_subscriber->safe_psql('postgres', qq(TRUNCATE tab1)); # OK when a table is excluded by pub1 EXCEPT clause, but it is included by pub2 -- 2.50.1 (Apple Git-155)
v7-0002-Add-EXCEPT-support-to-ALTER-PUBLICATION-ADD-TABLE.patch (application/x-patch, 25.9K) download From ef242e34926ddd310c35d8e7028b376f493d4771 Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Tue, 26 May 2026 15:36:07 +0530 Subject: [PATCH v7 2/3] Add EXCEPT support to ALTER PUBLICATION ADD TABLES IN SCHEMA Extend the EXCEPT clause support to allow tables to be excluded when adding a schema to a publication via ALTER PUBLICATION ... ADD. Syntax: ALTER PUBLICATION pub ADD TABLES IN SCHEMA s EXCEPT (TABLE s.t1); Since pg_dump uses ALTER PUBLICATION ... ADD, support for it is included in this patch. --- doc/src/sgml/ref/alter_publication.sgml | 40 +++++++- src/backend/catalog/pg_publication.c | 19 ++-- src/backend/commands/publicationcmds.c | 108 +++++++++++++++++++++- src/bin/pg_dump/pg_dump.c | 30 +++++- src/bin/pg_dump/t/002_pg_dump.pl | 36 ++++++++ src/bin/psql/tab-complete.in.c | 15 +++ src/test/regress/expected/publication.out | 69 +++++++++++++- src/test/regress/sql/publication.sql | 34 ++++++- src/test/subscription/t/037_except.pl | 32 +++++++ 9 files changed, 368 insertions(+), 15 deletions(-) diff --git a/doc/src/sgml/ref/alter_publication.sgml b/doc/src/sgml/ref/alter_publication.sgml index aa32bb169e9..73f6375a66f 100644 --- a/doc/src/sgml/ref/alter_publication.sgml +++ b/doc/src/sgml/ref/alter_publication.sgml @@ -31,7 +31,7 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA <replaceable class="parameter">tables_in_schema</replaceable> [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -47,6 +47,10 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <replaceable class="parameter">table_object</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] [ WHERE ( <replaceable class="parameter">expression</replaceable> ) ] +<phrase>and <replaceable class="parameter">tables_in_schema</replaceable> is:</phrase> + + { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] + <phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> TABLE <replaceable class="parameter">table_object</replaceable> [, ... ] @@ -110,6 +114,14 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <literal>ADD TABLE</literal>. </para> + <para> + The <literal>EXCEPT</literal> clause can be used with + <literal>ADD TABLES IN SCHEMA</literal> to exclude specific tables from the + publication. Using <literal>DROP TABLES IN SCHEMA</literal> on a publication + will automatically also remove any associated <literal>EXCEPT</literal> + entries. + </para> + <para> The fourth variant of this command listed in the synopsis can change all of the publication properties specified in @@ -198,6 +210,22 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r </listitem> </varlistentry> + <varlistentry> + <term><literal>EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] )</literal></term> + <listitem> + <para> + When used with <literal>ADD TABLES IN SCHEMA</literal>, specifies + tables to be excluded from the publication. Each named + table must belong to the schema specified in the same + <literal>TABLES IN SCHEMA</literal> clause. Table names may be + schema-qualified or unqualified; unqualified names are implicitly + qualified with the schema named in the same clause. See + <xref linkend="sql-createpublication"/> for further details on the + semantics of <literal>EXCEPT</literal>. + </para> + </listitem> + </varlistentry> + <varlistentry> <term><literal>SET ( <replaceable class="parameter">publication_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] )</literal></term> <listitem> @@ -288,6 +316,16 @@ ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA marketing, sales; </programlisting> </para> + <para> + Add schema <structname>sales</structname> to the publication + <structname>sales_publication</structname>, excluding the + <structname>sales.internal</structname> and + <structname>sales.drafts</structname> tables: +<programlisting> +ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA sales EXCEPT (TABLE internal, drafts); +</programlisting> + </para> + <para> Add tables <structname>users</structname>, <structname>departments</structname> and schema diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index b4c5a317869..c7fa81bfc33 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -648,15 +648,18 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, * here, as CreatePublication() function invalidates all relations as part * of defining a FOR ALL TABLES publication. * - * For ALTER PUBLICATION, invalidation is needed only when adding an - * EXCEPT table to a publication already marked as ALL TABLES. For - * publications that were originally empty or defined as ALL SEQUENCES and - * are being converted to ALL TABLES, invalidation is skipped here, as - * AlterPublicationAllFlags() function invalidates all relations while - * marking the publication as ALL TABLES publication. + * For ALTER PUBLICATION, invalidation is needed when adding an EXCEPT + * table to either a FOR ALL TABLES publication (pub->alltables is true) + * or a FOR TABLES IN SCHEMA publication (is_schema_publication is true). + * The exception: when a publication is being converted to FOR ALL TABLES + * (pub->alltables is still false at this point), + * AlterPublicationAllFlags() will perform a full invalidation, so we + * skip it here. */ - inval_except_table = (alter_stmt != NULL) && pub->alltables && - (alter_stmt->for_all_tables && pri->except); + inval_except_table = (alter_stmt != NULL) && pri->except && + (pub->alltables + ? alter_stmt->for_all_tables + : is_schema_publication(pubid)); if (!pri->except || inval_except_table) { diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 65ae40210db..f23893bbd10 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -70,6 +70,13 @@ static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok); static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); +static void AlterPublicationSchemas(AlterPublicationStmt *stmt, + HeapTuple tup, List *schemaidlist, + List *except_rel_names); +static void AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, + List *except_rel_names, + List *schemaidlist); static char defGetGeneratedColsOption(DefElem *def); @@ -1468,7 +1475,8 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, */ static void AlterPublicationSchemas(AlterPublicationStmt *stmt, - HeapTuple tup, List *schemaidlist) + HeapTuple tup, List *schemaidlist, + List *except_rel_names) { Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); @@ -1545,6 +1553,98 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, */ PublicationAddSchemas(pubform->oid, schemaidlist, true, stmt); } + + /* + * Increment the command counter so that is_schema_publication() in + * GetExcludedPublicationTables() can see the just-inserted schema + * rows when AlterPublicationSchemaExceptTables runs next. + */ + if (stmt->action == AP_AddObjects || stmt->action == AP_SetObjects) + CommandCounterIncrement(); + + AlterPublicationSchemaExceptTables(stmt, tup, except_rel_names, schemaidlist); +} + +/* + * Alter the EXCEPT list of a schema-level publication. + * + * Adds, removes, or replaces except-table entries in pg_publication_rel + * (rows with prexcept = true). These entries suppress publication of the + * named tables that would otherwise be covered by a FOR TABLES IN SCHEMA + * clause. + */ +static void +AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, List *except_rel_names, + List *schemaidlist) +{ + Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); + Oid pubid = pubform->oid; + + /* + * Nothing to do if no EXCEPT entries. + */ + if (!except_rel_names) + return; + + /* + * This function handles EXCEPT entries for schema-level publications + * only. For FOR ALL TABLES publications, EXCEPT entries are already + * processed by AlterPublicationTables(). + */ + if (schemaidlist == NIL && !is_schema_publication(pubid)) + return; + + /* + * EXCEPT is not meaningful with DROP: dropping a schema from a + * publication already removes all its except entries via cascade, and + * there is no sensible interpretation of "drop only the except entry but + * keep the schema". + */ + if (stmt->action == AP_DropObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); + + /* + * XXX EXCEPT with SET is not currently implemented. Workaround: DROP and + * re-ADD the schema with the desired EXCEPT list. + */ + if (stmt->action == AP_SetObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"), + errhint("Drop and re-add the schema with the desired EXCEPT list."))); + + if (stmt->action == AP_AddObjects) + { + List *rels; + List *explicitrelids; + + rels = OpenTableList(except_rel_names); + + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + /* + * Validate that each excluded table is not also in the explicit table + * list (which would be contradictory). + */ + foreach_ptr(PublicationRelInfo, pri, rels) + { + Oid relid = RelationGetRelid(pri->relation); + + if (list_member_oid(explicitrelids, relid)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" cannot appear in both the table list and the EXCEPT clause", + RelationGetQualifiedRelationName(pri->relation))); + } + + PublicationAddTables(pubid, rels, false, stmt); + + CloseTableList(rels); + } } /* @@ -1754,10 +1854,12 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) errmsg("publication \"%s\" does not exist", stmt->pubname)); - relations = list_concat(relations, except_rel_names); + if (stmt->for_all_tables) + relations = list_concat(relations, except_rel_names); + AlterPublicationTables(stmt, tup, relations, pstate->p_sourcetext, schemaidlist != NIL); - AlterPublicationSchemas(stmt, tup, schemaidlist); + AlterPublicationSchemas(stmt, tup, schemaidlist, except_rel_names); AlterPublicationAllFlags(stmt, rel, tup); } diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c index d56dcc701ce..e62d74c8ca0 100644 --- a/src/bin/pg_dump/pg_dump.c +++ b/src/bin/pg_dump/pg_dump.c @@ -5019,6 +5019,7 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) PublicationInfo *pubinfo = pubsinfo->publication; PQExpBuffer query; char *tag; + bool has_except = false; /* Do nothing if not dumping schema */ if (!dopt->dumpSchema) @@ -5029,7 +5030,34 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) query = createPQExpBuffer(); appendPQExpBuffer(query, "ALTER PUBLICATION %s ", fmtId(pubinfo->dobj.name)); - appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s;\n", fmtId(schemainfo->dobj.name)); + appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s", fmtId(schemainfo->dobj.name)); + + /* + * Append EXCEPT clause for any tables that belong to this schema + * and are excluded from the publication. + */ + for (SimplePtrListCell *cell = pubinfo->except_tables.head; cell; cell = cell->next) + { + TableInfo *tbinfo = (TableInfo *) cell->ptr; + + if (strcmp(tbinfo->dobj.namespace->dobj.name, schemainfo->dobj.name) == 0) + { + if (!has_except) + { + appendPQExpBufferStr(query, " EXCEPT ("); + has_except = true; + } + else + appendPQExpBufferStr(query, ", "); + + appendPQExpBuffer(query, "TABLE ONLY %s", fmtId(tbinfo->dobj.name)); + } + } + + if (has_except) + appendPQExpBufferStr(query, ")"); + + appendPQExpBufferStr(query, ";\n"); /* * There is no point in creating drop query as the drop is done by schema diff --git a/src/bin/pg_dump/t/002_pg_dump.pl b/src/bin/pg_dump/t/002_pg_dump.pl index 3ee9fda50e4..de554436205 100644 --- a/src/bin/pg_dump/t/002_pg_dump.pl +++ b/src/bin/pg_dump/t/002_pg_dump.pl @@ -3242,6 +3242,42 @@ my %tests = ( like => { %full_runs, section_post_data => 1, }, }, + 'CREATE PUBLICATION pub11' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub11 FOR TABLES IN SCHEMA dump_test EXCEPT (TABLE test_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub11 WITH (publish = 'insert, update, delete, truncate');\E + /xm, + like => { %full_runs, section_post_data => 1, }, + }, + + 'ALTER PUBLICATION pub11 ADD TABLES IN SCHEMA dump_test EXCEPT (TABLE test_table)' + => { + regexp => qr/^ + \QALTER PUBLICATION pub11 ADD TABLES IN SCHEMA dump_test EXCEPT (TABLE ONLY test_table);\E + /xm, + like => { %full_runs, section_post_data => 1, }, + }, + + 'CREATE PUBLICATION pub12' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub12 FOR TABLES IN SCHEMA dump_test EXCEPT (TABLE test_table, dump_test.test_second_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub12 WITH (publish = 'insert, update, delete, truncate');\E + /xm, + like => { %full_runs, section_post_data => 1, }, + }, + + 'ALTER PUBLICATION pub12 ADD TABLES IN SCHEMA dump_test EXCEPT (TABLE test_table, dump_test.test_second_table)' + => { + regexp => qr/^ + \QALTER PUBLICATION pub12 ADD TABLES IN SCHEMA dump_test EXCEPT (TABLE ONLY test_table, TABLE ONLY test_second_table);\E + /xm, + like => { %full_runs, section_post_data => 1, }, + }, + 'CREATE SUBSCRIPTION sub1' => { create_order => 50, create_sql => 'CREATE SUBSCRIPTION sub1 diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index fe11dc619ac..8db3e129928 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2364,6 +2364,21 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); + /* After a single schema name in ADD context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 161db458f49..c912cfcea00 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -564,12 +564,79 @@ CREATE PUBLICATION testpub_except_nokw ERROR: syntax error at or near "testpub_nopk" LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); ^ +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; +-- ADD: schema-qualified name in EXCEPT +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- DROP TABLES IN SCHEMA also removes associated EXCEPT entries +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Except tables: + "pub_test.testpub_tbl_s1" + +-- ADD: unqualified name is implicitly qualified with the schema, not public +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s2); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + "pub_test.testpub_tbl_s2" + +-- ADD: multiple excepted tables using unqualified names +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1, testpub_tbl_s2); +ERROR: relation "pub_test.testpub_tbl_s1" cannot be added because it is excluded from publication "testpub_alter_except" +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Except tables: + "pub_test.testpub_tbl_s1" + "pub_test.testpub_tbl_s2" + +-- fail: non-existing table in EXCEPT clause +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; +ERROR: tables from schema "pub_test" are not part of the publication +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- fail: EXCEPT table belongs to a different schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 1: ...xcept ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.tes... + ^ +-- fail: TABLE keyword is required for the first entry in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +ERROR: syntax error at or near "testpub_nopk" +LINE 1: ...lter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_no... + ^ -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP TABLE pub_test.testpub_parted_s CASCADE; DROP TABLE testpub_nopk, testpub_tbl_s1; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi, testpub_alter_except; --------------------------------------------- -- Tests for publications with SEQUENCES --------------------------------------------- diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 9162d4d15a5..9f816effa70 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -278,12 +278,44 @@ CREATE PUBLICATION testpub_except_partition CREATE PUBLICATION testpub_except_nokw FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; + +-- ADD: schema-qualified name in EXCEPT +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_alter_except + +-- DROP TABLES IN SCHEMA also removes associated EXCEPT entries +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + +-- ADD: unqualified name is implicitly qualified with the schema, not public +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s2); +\dRp+ testpub_alter_except + +-- ADD: multiple excepted tables using unqualified names +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1, testpub_tbl_s2); +\dRp+ testpub_alter_except + +-- fail: non-existing table in EXCEPT clause +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- fail: EXCEPT table belongs to a different schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- fail: TABLE keyword is required for the first entry in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP TABLE pub_test.testpub_parted_s CASCADE; DROP TABLE testpub_nopk, testpub_tbl_s1; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi, testpub_alter_except; --------------------------------------------- -- Tests for publications with SEQUENCES diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 18c7b2c1fca..0ba6d6f8bb2 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -347,6 +347,38 @@ is($result, qq(5), $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); +# ============================================ +# ALTER PUBLICATION EXCEPT for TABLES IN SCHEMA +# ============================================ + +# Truncate subscriber tables to remove data accumulated from previous tests. +$node_subscriber->safe_psql('postgres', + 'TRUNCATE sch1.tab_published, sch1.tab_excluded, sch1.parent, sch1.child'); + +# ADD: add a schema with an excepted table; verify the except entry takes effect. +$node_publisher->safe_psql('postgres', "CREATE PUBLICATION sch_pub"); +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub ADD TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_excluded)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(6), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: included table synced'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + # Cleanup schema tables before the multi-publication section. $node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); $node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); -- 2.50.1 (Apple Git-155)
v7-0003-Add-EXCEPT-support-to-ALTER-PUBLICATION-SET-TABLE.patch (application/x-patch, 26.9K) download From 85d685fffef948dd6917273b8001cdc6da58e232 Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Thu, 28 May 2026 12:14:31 +0530 Subject: [PATCH v7 3/3] Add EXCEPT support to ALTER PUBLICATION SET TABLES IN SCHEMA Extend AlterPublicationExceptTables() with the AP_SetObjects case, which redefines the publication and replaces the entire EXCEPT list. Syntax: ALTER PUBLICATION pub SET TABLES IN SCHEMA s EXCEPT (TABLE t1); This patch also cleans up EXCEPT entries when a schema is dropped from the publication. --- doc/src/sgml/ref/alter_publication.sgml | 27 +++- src/backend/commands/publicationcmds.c | 131 ++++++++++++++++++-- src/backend/replication/pgoutput/pgoutput.c | 10 +- src/bin/psql/tab-complete.in.c | 15 +++ src/test/regress/expected/publication.out | 82 +++++++++++- src/test/regress/sql/publication.sql | 34 +++++ src/test/subscription/t/037_except.pl | 85 +++++++++++++ 7 files changed, 355 insertions(+), 29 deletions(-) diff --git a/doc/src/sgml/ref/alter_publication.sgml b/doc/src/sgml/ref/alter_publication.sgml index 73f6375a66f..80b038e4b2e 100644 --- a/doc/src/sgml/ref/alter_publication.sgml +++ b/doc/src/sgml/ref/alter_publication.sgml @@ -97,7 +97,11 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r used with a publication defined with <literal>FOR TABLE</literal> or <literal>FOR TABLES IN SCHEMA</literal>, replaces the list of tables/schemas in the publication with the specified list; the existing tables or schemas - that were present in the publication will be removed. + that were present in the publication will be removed. When + <literal>SET TABLES IN SCHEMA</literal> is used with an + <literal>EXCEPT</literal> clause, the excluded tables for each schema are + replaced with the specified list; if <literal>EXCEPT</literal> is omitted + for a schema, any existing exclusions for that schema are cleared. </para> <para> @@ -116,10 +120,8 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <para> The <literal>EXCEPT</literal> clause can be used with - <literal>ADD TABLES IN SCHEMA</literal> to exclude specific tables from the - publication. Using <literal>DROP TABLES IN SCHEMA</literal> on a publication - will automatically also remove any associated <literal>EXCEPT</literal> - entries. + <literal>ADD TABLES IN SCHEMA</literal> to exclude specific tables from a + schema-level publication. </para> <para> @@ -214,7 +216,8 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <term><literal>EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] )</literal></term> <listitem> <para> - When used with <literal>ADD TABLES IN SCHEMA</literal>, specifies + When used with <literal>ADD TABLES IN SCHEMA</literal> + or <literal>SET TABLES IN SCHEMA</literal>, specifies tables to be excluded from the publication. Each named table must belong to the schema specified in the same <literal>TABLES IN SCHEMA</literal> clause. Table names may be @@ -326,6 +329,18 @@ ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA sales EXCEPT (TABLE int </programlisting> </para> + <para> + Replace the schema list of <structname>sales_publication</structname> with + <structname>sales</structname>, excluding only + <structname>sales.drafts</structname>. Other than + <structname>sales.drafts</structname>, any previously excluded tables for schema + <structname>sales</structname> are no longer excluded. Any schemas previously in + <structname>sales_publication</structname> are removed: +<programlisting> +ALTER PUBLICATION sales_publication SET TABLES IN SCHEMA sales EXCEPT (TABLE drafts); +</programlisting> + </para> + <para> Add tables <structname>users</structname>, <structname>departments</structname> and schema diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index f23893bbd10..58e0c938f83 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -1582,9 +1582,11 @@ AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, Oid pubid = pubform->oid; /* - * Nothing to do if no EXCEPT entries. + * Nothing to do if there are no EXCEPT entries, unless handling the SET + * command, because if the user has removed all exceptions we need to + * drop any existing ones. */ - if (!except_rel_names) + if (!except_rel_names && stmt->action != AP_SetObjects) return; /* @@ -1597,7 +1599,7 @@ AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, /* * EXCEPT is not meaningful with DROP: dropping a schema from a - * publication already removes all its except entries via cascade, and + * publication already removes all its EXCEPT entries via cascade, and * there is no sensible interpretation of "drop only the except entry but * keep the schema". */ @@ -1606,16 +1608,6 @@ AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); - /* - * XXX EXCEPT with SET is not currently implemented. Workaround: DROP and - * re-ADD the schema with the desired EXCEPT list. - */ - if (stmt->action == AP_SetObjects) - ereport(ERROR, - (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"), - errhint("Drop and re-add the schema with the desired EXCEPT list."))); - if (stmt->action == AP_AddObjects) { List *rels; @@ -1643,6 +1635,86 @@ AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, PublicationAddTables(pubid, rels, false, stmt); + CloseTableList(rels); + } + else /* AP_SetObjects */ + { + List *oldexceptrelids = NIL; + List *newexceptrelids = NIL; + List *delrelids = NIL; + List *rels; + List *explicitrelids; + + rels = OpenTableList(except_rel_names); + + /* Collect OIDs of the desired new EXCEPT list. */ + foreach_ptr(PublicationRelInfo, pri, rels) + { + newexceptrelids = lappend_oid(newexceptrelids, + RelationGetRelid(pri->relation)); + } + + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + /* + * Validate that each excluded table is not also in the explicit table + * list (which would be contradictory). + */ + foreach_ptr(PublicationRelInfo, pri, rels) + { + Oid relid = RelationGetRelid(pri->relation); + + if (list_member_oid(explicitrelids, relid)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" cannot appear in both the table list and the EXCEPT clause", + RelationGetQualifiedRelationName(pri->relation))); + } + + /* + * Get the current set of EXCEPT entries. Only FOR ALL TABLES and + * schema-level publications can have EXCEPT entries; for any other + * publication type oldexceptrelids stays NIL. + * + * Note: we check is_schema_publication() against the current catalog + * state (before AlterPublicationSchemas has run), so if the caller is + * doing SET TABLE t1 to convert a schema publication into a plain + * table publication, is_schema_publication() still returns true here. + * That is intentional: it lets us discover and clean up any stale + * EXCEPT entries that belong to the old schema definition. + */ + if (GetPublication(pubid)->alltables || is_schema_publication(pubid)) + oldexceptrelids = GetExcludedPublicationTables(pubid, + PUBLICATION_PART_ROOT); + + /* Build a list of old EXCEPT entries not present in the new list. */ + foreach_oid(oldrelid, oldexceptrelids) + { + if (!list_member_oid(newexceptrelids, oldrelid)) + delrelids = lappend_oid(delrelids, oldrelid); + } + + /* Drop old EXCEPT entries not present in the new list. */ + foreach_oid(relid, delrelids) + { + Oid proid; + ObjectAddress obj; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (!OidIsValid(proid)) + continue; /* already gone */ + + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + + /* Add new EXCEPT entries, skipping any already present. */ + PublicationAddTables(pubid, rels, true, stmt); + CloseTableList(rels); } } @@ -2292,6 +2364,7 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) foreach(lc, schemas) { Oid schemaid = lfirst_oid(lc); + List *except_relids; psid = GetSysCacheOid2(PUBLICATIONNAMESPACEMAP, Anum_pg_publication_namespace_oid, @@ -2308,8 +2381,40 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) get_namespace_name(schemaid)))); } + /* + * Collect EXCEPT entries for tables belonging to this schema before + * removing the schema entry. + */ + except_relids = GetExcludedPublicationTables(pubid, PUBLICATION_PART_ROOT); + ObjectAddressSet(obj, PublicationNamespaceRelationId, psid); performDeletion(&obj, DROP_CASCADE, 0); + + /* + * Drop any prexcept rows for tables belonging to this schema. These + * rows have no pg_depend entry pointing at the + * pg_publication_namespace row, so they are not cascaded by the + * performDeletion() call above and must be cleaned up explicitly. + */ + foreach_oid(relid, except_relids) + { + Oid proid; + + if (get_rel_namespace(relid) != schemaid) + continue; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (!OidIsValid(proid)) + continue; /* already gone */ + + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + + list_free(except_relids); } } diff --git a/src/backend/replication/pgoutput/pgoutput.c b/src/backend/replication/pgoutput/pgoutput.c index c5f17bf2338..785a045ead2 100644 --- a/src/backend/replication/pgoutput/pgoutput.c +++ b/src/backend/replication/pgoutput/pgoutput.c @@ -2229,7 +2229,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) */ if (pub->alltables) { - List *exceptpubids = NIL; + List *except_pubids = NIL; if (am_partition) { @@ -2252,7 +2252,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) * clause. Therefore, for a partition, exclusion must be * evaluated at the top-most ancestor. */ - exceptpubids = GetRelationExcludedPublications(last_ancestor_relid); + except_pubids = GetRelationExcludedPublications(last_ancestor_relid); } else { @@ -2260,13 +2260,13 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) * For a regular table or a root partitioned table, check * exclusion on table itself. */ - exceptpubids = GetRelationExcludedPublications(pub_relid); + except_pubids = GetRelationExcludedPublications(pub_relid); } - if (!list_member_oid(exceptpubids, pub->oid)) + if (!list_member_oid(except_pubids, pub->oid)) publish = true; - list_free(exceptpubids); + list_free(except_pubids); if (!publish) continue; diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index 8db3e129928..11c87b1b006 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2379,6 +2379,21 @@ match_previous_words(int pattern_id, } else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) COMPLETE_WITH(")"); + /* After a single schema name in SET context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index c912cfcea00..ff1cb4bed1e 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -587,8 +587,7 @@ ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description --------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- regress_publication_user | f | f | t | t | t | t | none | f | -Except tables: - "pub_test.testpub_tbl_s1" +(1 row) -- ADD: unqualified name is implicitly qualified with the schema, not public ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s2); @@ -600,25 +599,98 @@ ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TAB Tables from schemas: "pub_test" Except tables: - "pub_test.testpub_tbl_s1" "pub_test.testpub_tbl_s2" -- ADD: multiple excepted tables using unqualified names ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1, testpub_tbl_s2); -ERROR: relation "pub_test.testpub_tbl_s1" cannot be added because it is excluded from publication "testpub_alter_except" \dRp+ testpub_alter_except Publication testpub_alter_except Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description --------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" Except tables: "pub_test.testpub_tbl_s1" "pub_test.testpub_tbl_s2" +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s2" + +-- fail: table in EXCEPT clause also appears in the explicit table list +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot appear in both the table list and the EXCEPT clause +-- error: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 1: ...xcept SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.tes... + ^ +-- error: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +ERROR: EXCEPT clause is not supported with DROP in ALTER PUBLICATION +-- SET: unqualified name in EXCEPT is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- SET without EXCEPT clears the existing except list +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + +-- SET to a different schema removes old schema's EXCEPT entries +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA public; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "public" + +-- fail: nonexistent table in EXCEPT clause (SET path) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- SET: multiple schemas each with their own EXCEPT clause +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + -- fail: non-existing table in EXCEPT clause ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; -ERROR: tables from schema "pub_test" are not part of the publication ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); ERROR: relation "pub_test.nonexistent_table" does not exist -- fail: EXCEPT table belongs to a different schema diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 9f816effa70..d008114e05b 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -300,6 +300,40 @@ ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1, testpub_tbl_s2); \dRp+ testpub_alter_except +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + +-- fail: table in EXCEPT clause also appears in the explicit table list +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- error: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- error: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); + +-- SET: unqualified name in EXCEPT is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +\dRp+ testpub_alter_except + +-- SET without EXCEPT clears the existing except list +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + +-- SET to a different schema removes old schema's EXCEPT entries +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA public; +\dRp+ testpub_alter_except + +-- fail: nonexistent table in EXCEPT clause (SET path) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- SET: multiple schemas each with their own EXCEPT clause +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_alter_except + -- fail: non-existing table in EXCEPT clause ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 0ba6d6f8bb2..1308b6e43ed 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -376,6 +376,61 @@ $result = is($result, qq(0), 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); +# SET: replace the except list; tab_excluded is now included and tab_published is excluded. +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_published)" +); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (7); + INSERT INTO sch1.tab_excluded VALUES (7); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT a FROM sch1.tab_excluded WHERE a = 7"); +is($result, qq(7), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: newly included table is replicated' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT a FROM sch1.tab_published WHERE a = 7"); +is($result, qq(), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: now-excluded table is not replicated' +); + +# SET without EXCEPT: clears the except list; both tables are now published. +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1"); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (8); + INSERT INTO sch1.tab_excluded VALUES (8); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT a FROM sch1.tab_published WHERE a = 8"); +is($result, qq(8), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_published replicated after except list cleared' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT a FROM sch1.tab_excluded WHERE a = 8"); +is($result, qq(8), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_excluded replicated after except list cleared' +); + $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); @@ -443,6 +498,36 @@ $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); +# OK when a table is excluded by a TABLES IN SCHEMA EXCEPT publication, +# but is included by another publication. +$node_publisher->safe_psql('postgres', 'TRUNCATE tab1'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE tab1'); + +$node_publisher->safe_psql( + 'postgres', qq( + CREATE PUBLICATION tap_pub1 FOR TABLES IN SCHEMA public EXCEPT (TABLE public.tab1); + CREATE PUBLICATION tap_pub2 FOR TABLE tab1; + INSERT INTO tab1 VALUES(1); +)); +$node_subscriber->psql('postgres', + "CREATE SUBSCRIPTION tap_sub CONNECTION '$publisher_connstr' PUBLICATION tap_pub1, tap_pub2" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'tap_sub'); + +$node_publisher->safe_psql('postgres', qq(INSERT INTO tab1 VALUES(2))); +$node_publisher->wait_for_catchup('tap_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT * FROM tab1 ORDER BY a"); +is( $result, qq(1 +2), + "TABLES IN SCHEMA EXCEPT: table excluded in schema pub but included by another pub is replicated" +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); + $node_publisher->stop('fast'); done_testing(); -- 2.50.1 (Apple Git-155)
^ permalink raw reply [nested|flat] 196+ messages in thread

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-05-29 05:31  Peter Smith <smithpb2250@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: Peter Smith @ 2026-05-29 05:31 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Hi Nisha.

Some review comments for patch v7-0001.

======
src/backend/catalog/pg_publication.c

GetTopMostAncestorInPublication:

1.
- else
+ else if (!list_member_oid(except_pubids, puboid))
  {
  aschemaPubids = GetSchemaPublications(get_rel_namespace(ancestor));

IIUC this `except_pubids` and `puboid` are not changing, so you do not
need to be doing this member check every loop iteration. Is it better
to assign some variable up-front?

e.g.
bool check_schemas = !list_member_oid(except_pubids, puboid);

~~~

publication_add_relation:

2.
+ if (is_except)
+ ereport(ERROR,
+ (errcode(ERRCODE_DUPLICATE_OBJECT),
+ errmsg("relation \"%s\" cannot be added because it is excluded from
publication \"%s\"",
+ RelationGetQualifiedRelationName(targetrel),
+ pub->name)));

I am unsure about the changed wording from "table" to "relation". IIUC
we say "relation" when it could be either a table or a sequence. So
maybe "table" is correct for your patch;l OTHOH this should change to
"relation" by Shlok's EXCEPT SEQUENCE patch [1].

~~~

3.
+ ereport(ERROR,
+ (errcode(ERRCODE_DUPLICATE_OBJECT),
+ errmsg("relation \"%s\" is already member of publication \"%s\"",
+ RelationGetQualifiedRelationName(targetrel), pub->name)));

IMO making everything fully qualified like this would be a good
change, but doing it here perhaps does not belong in your patch. I
have resurrected this question in the other thread [2], which would
affect not only this statement. but many others. Please post your
opinion about this on that other thread.

======
src/backend/commands/publicationcmds.c

ObjectsInPublicationToOids:

4.
 static void
 ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate,
-    List **rels, List **exceptrels, List **schemas)
+    List **rels, List **except_rel_names, List **schemas)

Is `except_rel_names` an accurate name? IMO it makes it sound like
it's a list of char* names, but IIUC that is not the case; aren't
these PublicationTable objects? Would something like
`except_pubtables` be more correct?

~~~

CreatePublication:

5.
- List    *exceptrelations = NIL;
+ List    *except_rel_names = NIL;

Same doubts about this `except_rel_names` variable name.

~~~

AlterPublication:
6.
  List    *relations = NIL;
- List    *exceptrelations = NIL;
+ List    *except_rel_names = NIL;

Same doubts about this `except_rel_names` variable name.

======
src/backend/replication/pgoutput/pgoutput.c

get_rel_sync_entry:

7.
+ if (am_partition)
+ {
+ List    *part_ancestors = get_partition_ancestors(relid);
+
+ root_relid = llast_oid(part_ancestors);
+ list_free(part_ancestors);

I think just call this `ancestors` (not `part_ancestors`) for
consistency with other code in the same function.

======
src/bin/psql/tab-complete.in.c

On Thu, May 28, 2026 at 9:27 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
>
>  On Fri, May 22, 2026 at 7:57 AM Peter Smith <smithpb2250@gmail.com> wrote:
...
> > 6.
> > + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES",
> > "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) &&
> > ends_with(prev_wd, ','))
> > + COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables);
> >
> > I'm not sure if this is working as intended.
> >
> > When testing for multiple except tables I get results like:
> > ----
> > test_pub=# create publication pub1 for tables IN SCHEMA myschema <TAB>
> > EXCEPT ( TABLE  WITH (
> > test_pub=# create publication pub1 for tables IN SCHEMA myschema
> > except ( table <TAB>
> > test_pub=# create publication pub1 for tables IN SCHEMA myschema
> > except ( table myschema.t<TAB>
> > myschema.t1  myschema.t2  myschema.t3
> > test_pub=# create publication pub1 for tables IN SCHEMA myschema
> > except ( table myschema.t1,<TAB>
> > information_schema.  myschema.            public.              t1
> >              t2                   t3
> > ----
> >
> > Note: it is offering suggstions for schema names outside of the
> > "myschema". Should this code be calling
> > Query_for_list_of_tables_in_schema instead of
> > Query_for_list_of_tables?
> >
>
> For this case, I don't think it's really possible to keep suggesting
> after a comma. Even if we handle a fixed number of comma-separated
> entries, the same problem reappears with the next entry.
> Query_for_list_of_tables_in_schema needs a correct schema reference,
> but with each comma the relative offset changes, so there is no single
> fixed prev*_wd that can reliably point to the schema across all
> entries.
>
> But I see, the current call to Query_for_list_of_tables is clearly
> incorrect here. I have now suppressed suggestions after a comma,
> instead of showing incorrect suggestions.
> Thoughts?
>

8.
REPLY: Yeah, I don't have any good ideas how to fix this, or if a fix
is even possible, but I agree that doing nothing is better than doing
the wrong thing.

~~~

9.
BTW, the current code is not able to handle multiple schemas.

So, this works:
test_pub=# CREATE PUBLICATION pub1 for TABLES IN SCHEMA myschema <TAB>
EXCEPT ( TABLE  WITH (

but, this doesn't do anything:
test_pub=# CREATE PUBLICATION pub1 for TABLES IN SCHEMA public, myschema <TAB>

======
[1] Shlok EXCEPT -
https://www.postgresql.org/message-id/flat/CAHut%2BPsUrYmbZ996ZybjMWvpW_ufXB8WM94pdvAPyzQpoe%2BHRA%4...
[2] schema-qualified messages -
https://www.postgresql.org/message-id/CAHut%2BPvWoOyLKFb627Ch%2BXg3TYHuHdaOZ_XmxYgKVYdOzpqFsw%40mail...

Kind Regards,
Peter Smith.
Fujitsu Australia





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-05-29 08:24  Peter Smith <smithpb2250@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: Peter Smith @ 2026-05-29 08:24 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Hi Nisha.

Some review comments for patch v7-0002.

======
src/backend/commands/publicationcmds.c

1.
+static void AlterPublicationSchemas(AlterPublicationStmt *stmt,
+ HeapTuple tup, List *schemaidlist,
+ List *except_rel_names);
+static void AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt,
+    HeapTuple tup,
+    List *except_rel_names,
+    List *schemaidlist);

Maybe the same doubts about the `except_rel_names` parameter/variable
are continued into this patch. See patch 0001 where I first queried
this.

======
src/bin/pg_dump/t/002_pg_dump.pl

2.
+ 'CREATE PUBLICATION pub12' => {
+ create_order => 50,
+ create_sql =>
+   'CREATE PUBLICATION pub12 FOR TABLES IN SCHEMA dump_test EXCEPT
(TABLE test_table, dump_test.test_second_table);',
+ regexp => qr/^
+ \QCREATE PUBLICATION pub12 WITH (publish = 'insert, update, delete,
truncate');\E
+ /xm,
+ like => { %full_runs, section_post_data => 1, },
+ },
+
+ 'ALTER PUBLICATION pub12 ADD TABLES IN SCHEMA dump_test EXCEPT
(TABLE test_table, dump_test.test_second_table)'
+   => {
+ regexp => qr/^
+ \QALTER PUBLICATION pub12 ADD TABLES IN SCHEMA dump_test EXCEPT
(TABLE ONLY test_table, TABLE ONLY test_second_table);\E
+ /xm,
+ like => { %full_runs, section_post_data => 1, },
+   },

I found those hard to read at first. How about just changing the test
title of the ALTER parts

BEFORE
+ 'ALTER PUBLICATION pub12 ADD TABLES IN SCHEMA dump_test EXCEPT
(TABLE test_table, dump_test.test_second_table)'
SUGGESTION
+ 'CREATE PUBLICATION pub12 test continues ...'

(2 places like this)

======
src/test/regress/expected/publication.out

3.
+-- DROP TABLES IN SCHEMA also removes associated EXCEPT entries
+ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test;
+\dRp+ testpub_alter_except
+                                                       Publication
testpub_alter_except
+          Owner           | All tables | All sequences | Inserts |
Updates | Deletes | Truncates | Generated columns | Via root |
Description
+--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+-------------
+ regress_publication_user | f          | f             | t       | t
     | t       | t         | none              | f        |
+Except tables:
+    "pub_test.testpub_tbl_s1"
+

Isn't this showing a BUG, because after the DROP the "Except tables"
are still listed.

~~~

4.
+-- ADD: unqualified name is implicitly qualified with the schema, not public
+ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test
EXCEPT (TABLE testpub_tbl_s2);
+\dRp+ testpub_alter_except
+                                                       Publication
testpub_alter_except
+          Owner           | All tables | All sequences | Inserts |
Updates | Deletes | Truncates | Generated columns | Via root |
Description
+--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+-------------
+ regress_publication_user | f          | f             | t       | t
     | t       | t         | none              | f        |
+Tables from schemas:
+    "pub_test"
+Except tables:
+    "pub_test.testpub_tbl_s1"
+    "pub_test.testpub_tbl_s2"
+

Isn't this showing the same BUG as the previous test, because "s1" is
still in the "Except tables" list, even though it was not part of the
EXCEPT.

~~~

5.
+-- ADD: multiple excepted tables using unqualified names
+ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test;
+ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test
EXCEPT (TABLE testpub_tbl_s1, testpub_tbl_s2);
+ERROR:  relation "pub_test.testpub_tbl_s1" cannot be added because it
is excluded from publication "testpub_alter_except"

Isn't this showing the same BUG again, because "s1" was already in the
EXCEPT list when it should not be.

======
Kind Regards,
Peter Smith.
Fujitsu Australia





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-05-30 04:32  Nisha Moond <nisha.moond412@gmail.com>
  parent: Peter Smith <smithpb2250@gmail.com>
  0 siblings, 2 replies; 196+ messages in thread

From: Nisha Moond @ 2026-05-30 04:32 UTC (permalink / raw)
  To: Peter Smith <smithpb2250@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Fri, May 29, 2026 at 11:01 AM Peter Smith <smithpb2250@gmail.com> wrote:
>
> Hi Nisha.
>
> Some review comments for patch v7-0001.
>

Thanks for the review.

>
> publication_add_relation:
>
> 2.
> + if (is_except)
> + ereport(ERROR,
> + (errcode(ERRCODE_DUPLICATE_OBJECT),
> + errmsg("relation \"%s\" cannot be added because it is excluded from
> publication \"%s\"",
> + RelationGetQualifiedRelationName(targetrel),
> + pub->name)));
>
> I am unsure about the changed wording from "table" to "relation". IIUC
> we say "relation" when it could be either a table or a sequence. So
> maybe "table" is correct for your patch;l OTHOH this should change to
> "relation" by Shlok's EXCEPT SEQUENCE patch [1].
>

Okay, makes sense, changed back to "table".

> ~~~
>
> 3.
> + ereport(ERROR,
> + (errcode(ERRCODE_DUPLICATE_OBJECT),
> + errmsg("relation \"%s\" is already member of publication \"%s\"",
> + RelationGetQualifiedRelationName(targetrel), pub->name)));
>
> IMO making everything fully qualified like this would be a good
> change, but doing it here perhaps does not belong in your patch. I
> have resurrected this question in the other thread [2], which would
> affect not only this statement. but many others. Please post your
> opinion about this on that other thread.
>

That is fine with me. I've reverted the change from my patch.

> ======
> src/backend/commands/publicationcmds.c
>
> ObjectsInPublicationToOids:
>
> 4.
>  static void
>  ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate,
> -    List **rels, List **exceptrels, List **schemas)
> +    List **rels, List **except_rel_names, List **schemas)
>
> Is `except_rel_names` an accurate name? IMO it makes it sound like
> it's a list of char* names, but IIUC that is not the case; aren't
> these PublicationTable objects? Would something like
> `except_pubtables` be more correct?
>

Yes these are PublicationTable objects, changed the name as sugegsted.

> ~~~
>
> 9.
> BTW, the current code is not able to handle multiple schemas.
>
> So, this works:
> test_pub=# CREATE PUBLICATION pub1 for TABLES IN SCHEMA myschema <TAB>
> EXCEPT ( TABLE  WITH (
>
> but, this doesn't do anything:
> test_pub=# CREATE PUBLICATION pub1 for TABLES IN SCHEMA public, myschema <TAB>
>

I think the above preserves the existing behavior. Currently, we do
not suggest "WITH (" after the second schema onwards. To support this
properly, we would also need to handle "WITH (" suggestions for
subsequent schema entries.

I’ve created a top-up patch (patch-002) for this. I can merge it if we
want to change the current behavior. Let me know your thoughts.
~~~~

Attached is the updated v8 patch set.
Addressed all of the above comments, along with the patch v7-0002
comments from [1]. Patch-0003 has also been updated accordingly.

[1] https://www.postgresql.org/message-id/CAHut%2BPuhL7Xj8UAK0yBmbbDsCC9xvRVmreCC_yxr%2BbMfc-dt5g%40mail...

--
Thanks,
Nisha

Attachments: download all (4 files, .tar.gz)

v8-0001-Support-EXCEPT-clause-for-schema-level-publicatio.patch (application/x-patch, 46.6K) download From 9ff660dba0917fbd78052534b6e811240c2525bb Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Mon, 4 May 2026 12:49:27 +0530 Subject: [PATCH v8 1/4] Support EXCEPT clause for schema-level publications Extend table exclusion support in publications to allow specific tables to be excluded from schema-level publications using an EXCEPT clause in CREATE PUBLICATION. Supported syntax: CREATE PUBLICATION <pub> FOR TABLES IN SCHEMA s EXCEPT (TABLE t1,...); --- doc/src/sgml/logical-replication.sgml | 3 +- doc/src/sgml/ref/create_publication.sgml | 22 +++- src/backend/catalog/pg_publication.c | 98 ++++++++++++--- src/backend/commands/publicationcmds.c | 65 ++++++++-- src/backend/parser/gram.y | 52 +++++++- src/backend/replication/pgoutput/pgoutput.c | 30 ++++- src/bin/psql/describe.c | 18 +++ src/bin/psql/tab-complete.in.c | 24 +++- src/include/catalog/pg_publication.h | 3 +- src/include/nodes/parsenodes.h | 2 + src/test/regress/expected/publication.out | 104 ++++++++++++++- src/test/regress/sql/publication.sql | 69 +++++++++- src/test/subscription/t/037_except.pl | 133 +++++++++++++++++++- 13 files changed, 577 insertions(+), 46 deletions(-) diff --git a/doc/src/sgml/logical-replication.sgml b/doc/src/sgml/logical-replication.sgml index 9e7868487de..1433d2660fe 100644 --- a/doc/src/sgml/logical-replication.sgml +++ b/doc/src/sgml/logical-replication.sgml @@ -117,7 +117,8 @@ or <literal>FOR ALL SEQUENCES</literal>. Unlike tables, sequences can be synchronized at any time. For more information, see <xref linkend="logical-replication-sequences"/>. When a publication is - created with <literal>FOR ALL TABLES</literal>, a table or set of tables can + created with <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal>, a table or set of tables can be explicitly excluded from publication using the <link linkend="sql-createpublication-params-for-except-table"><literal>EXCEPT</literal></link> clause. diff --git a/doc/src/sgml/ref/create_publication.sgml b/doc/src/sgml/ref/create_publication.sgml index f82d640e6ca..7fa0bd11f7b 100644 --- a/doc/src/sgml/ref/create_publication.sgml +++ b/doc/src/sgml/ref/create_publication.sgml @@ -28,7 +28,7 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA <replaceable class="parameter">tables_in_schema</replaceable> [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -39,6 +39,10 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <replaceable class="parameter">table_object</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] [ WHERE ( <replaceable class="parameter">expression</replaceable> ) ] +<phrase>and <replaceable class="parameter">tables_in_schema</replaceable> is:</phrase> + + { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] + <phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> TABLE <replaceable class="parameter">table_object</replaceable> [, ... ] @@ -142,6 +146,8 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <para> Marks the publication as one that replicates changes for all tables in the specified list of schemas, including tables created in the future. + Tables listed in the <literal>EXCEPT</literal> clause for a given schema + are excluded from the publication. </para> <para> @@ -173,7 +179,7 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <para> Marks the publication as one that replicates changes for all tables in the database, including tables created in the future. Tables listed in - <literal>EXCEPT</literal> clause are excluded from the publication. + the <literal>EXCEPT</literal> clause are excluded from the publication. </para> </listitem> </varlistentry> @@ -198,7 +204,8 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <listitem> <para> This clause specifies a list of tables to be excluded from the - publication. + publication. It can be used with <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal>. </para> <para> For inherited tables, if <literal>ONLY</literal> is specified before the @@ -515,6 +522,15 @@ CREATE PUBLICATION production_publication FOR TABLE users, departments, TABLES I CREATE PUBLICATION sales_publication FOR TABLES IN SCHEMA marketing, sales; </programlisting></para> + <para> + Create a publication that publishes all changes for all the tables present in + the schema <structname>sales</structname>, except + <structname>internal</structname> and <structname>drafts</structname>: +<programlisting> +CREATE PUBLICATION sales_filtered FOR TABLES IN SCHEMA sales EXCEPT (TABLE internal, drafts); +</programlisting> + </para> + <para> Create a publication that publishes all changes for table <structname>users</structname>, but replicates only columns <structname>user_id</structname> and diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index 5c457d9aca8..4af0d74814a 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -444,13 +444,19 @@ GetPubPartitionOptionRelations(List *result, PublicationPartOpt pub_partopt, * * Note that the list of ancestors should be ordered such that the topmost * ancestor is at the end of the list. + * + * except_pubids is a list of publication OIDs whose schema membership + * should be ignored for the ancestor (because the ancestor is in their + * EXCEPT clause). */ Oid -GetTopMostAncestorInPublication(Oid puboid, List *ancestors, int *ancestor_level) +GetTopMostAncestorInPublication(Oid puboid, List *ancestors, + int *ancestor_level, List *except_pubids) { ListCell *lc; Oid topmost_relid = InvalidOid; int level = 0; + bool check_schemas = !list_member_oid(except_pubids, puboid); /* * Find the "topmost" ancestor that is in this publication. @@ -470,7 +476,7 @@ GetTopMostAncestorInPublication(Oid puboid, List *ancestors, int *ancestor_level if (ancestor_level) *ancestor_level = level; } - else + else if (check_schemas) { aschemaPubids = GetSchemaPublications(get_rel_namespace(ancestor)); if (list_member_oid(aschemaPubids, puboid)) @@ -545,18 +551,30 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, * duplicates, it's here just to provide nicer error message in common * case. The real protection is the unique key on the catalog. */ - if (SearchSysCacheExists2(PUBLICATIONRELMAP, ObjectIdGetDatum(relid), - ObjectIdGetDatum(pubid))) + tup = SearchSysCache2(PUBLICATIONRELMAP, ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + + if (HeapTupleIsValid(tup)) { + bool is_except = ((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept; + + ReleaseSysCache(tup); table_close(rel, RowExclusiveLock); if (if_not_exists) return InvalidObjectAddress; - ereport(ERROR, - (errcode(ERRCODE_DUPLICATE_OBJECT), - errmsg("relation \"%s\" is already member of publication \"%s\"", - RelationGetRelationName(targetrel), pub->name))); + if (is_except) + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("table \"%s\" cannot be added because it is excluded from publication \"%s\"", + RelationGetQualifiedRelationName(targetrel), + pub->name))); + else + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("relation \"%s\" is already member of publication \"%s\"", + RelationGetRelationName(targetrel), pub->name))); } check_publication_add_relation(pri); @@ -982,12 +1000,13 @@ GetIncludedPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) * Gets list of table oids that were specified in the EXCEPT clause for a * publication. * - * This should only be used FOR ALL TABLES publications. + * This is used for FOR ALL TABLES and FOR TABLES IN SCHEMA publications, + * both of which support EXCEPT TABLE. */ List * GetExcludedPublicationTables(Oid pubid, PublicationPartOpt pub_partopt) { - Assert(GetPublication(pubid)->alltables); + Assert(GetPublication(pubid)->alltables || is_schema_publication(pubid)); return get_publication_relations(pubid, pub_partopt, true); } @@ -1049,13 +1068,13 @@ GetAllPublicationRelations(Oid pubid, char relkind, bool pubviaroot) TableScanDesc scan; HeapTuple tuple; List *result = NIL; - List *exceptlist = NIL; + List *except_relids = NIL; Assert(!(relkind == RELKIND_SEQUENCE && pubviaroot)); /* EXCEPT filtering applies only to relations, not sequences */ if (relkind == RELKIND_RELATION) - exceptlist = GetExcludedPublicationTables(pubid, pubviaroot ? + except_relids = GetExcludedPublicationTables(pubid, pubviaroot ? PUBLICATION_PART_ROOT : PUBLICATION_PART_LEAF); @@ -1075,7 +1094,7 @@ GetAllPublicationRelations(Oid pubid, char relkind, bool pubviaroot) if (is_publishable_class(relid, relForm) && !(relForm->relispartition && pubviaroot) && - !list_member_oid(exceptlist, relid)) + !list_member_oid(except_relids, relid)) result = lappend_oid(result, relid); } @@ -1097,7 +1116,7 @@ GetAllPublicationRelations(Oid pubid, char relkind, bool pubviaroot) if (is_publishable_class(relid, relForm) && !relForm->relispartition && - !list_member_oid(exceptlist, relid)) + !list_member_oid(except_relids, relid)) result = lappend_oid(result, relid); } @@ -1232,22 +1251,67 @@ GetSchemaPublicationRelations(Oid schemaid, PublicationPartOpt pub_partopt) /* * Gets the list of all relations published by FOR TABLES IN SCHEMA - * publication. + * publication, excluding any tables listed in the EXCEPT clause. */ List * GetAllSchemaPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) { List *result = NIL; List *pubschemalist = GetPublicationSchemas(pubid); + List *except_relids = NIL; ListCell *cell; + /* get the list of tables excluded via EXCEPT TABLE for this publication */ + if (pubschemalist != NIL) + except_relids = GetExcludedPublicationTables(pubid, pub_partopt); + foreach(cell, pubschemalist) { Oid schemaid = lfirst_oid(cell); List *schemaRels = NIL; schemaRels = GetSchemaPublicationRelations(schemaid, pub_partopt); - result = list_concat(result, schemaRels); + + if (except_relids != NIL) + { + /* filter out any tables that appear in the EXCEPT list */ + ListCell *rlc; + + foreach(rlc, schemaRels) + { + Oid relid = lfirst_oid(rlc); + bool excluded = list_member_oid(except_relids, relid); + + /* + * Also exclude any relation whose partition ancestor is in + * the EXCEPT list. This matters when pub_partopt is + * PUBLICATION_PART_ROOT: the except list holds only the root + * OID, but the schema scan may also return individual + * partition relations that live in the same schema. + */ + if (!excluded && get_rel_relispartition(relid)) + { + List *ancestors = get_partition_ancestors(relid); + ListCell *alc; + + foreach(alc, ancestors) + { + if (list_member_oid(except_relids, lfirst_oid(alc))) + { + excluded = true; + break; + } + } + list_free(ancestors); + } + + if (!excluded) + result = lappend_oid(result, relid); + } + list_free(schemaRels); + } + else + result = list_concat(result, schemaRels); } return result; @@ -1381,7 +1445,7 @@ is_table_publishable_in_publication(Oid relid, Publication *pub) * the publication, it should be included (return true). */ if (relispartition && - OidIsValid(GetTopMostAncestorInPublication(pub->oid, ancestors, NULL))) + OidIsValid(GetTopMostAncestorInPublication(pub->oid, ancestors, NULL, NIL))) return !pub->pubviaroot; /* diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 440adb356ad..cd39d6375cd 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -181,7 +181,7 @@ parse_publication_options(ParseState *pstate, */ static void ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, - List **rels, List **exceptrels, List **schemas) + List **rels, List **except_pubtables, List **schemas) { ListCell *cell; PublicationObjSpec *pubobj; @@ -200,7 +200,7 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, { case PUBLICATIONOBJ_EXCEPT_TABLE: pubobj->pubtable->except = true; - *exceptrels = lappend(*exceptrels, pubobj->pubtable); + *except_pubtables = lappend(*except_pubtables, pubobj->pubtable); break; case PUBLICATIONOBJ_TABLE: pubobj->pubtable->except = false; @@ -305,7 +305,7 @@ pub_rf_contains_invalid_column(Oid pubid, Relation relation, List *ancestors, if (pubviaroot && relation->rd_rel->relispartition) { publish_as_relid - = GetTopMostAncestorInPublication(pubid, ancestors, NULL); + = GetTopMostAncestorInPublication(pubid, ancestors, NULL, NIL); if (!OidIsValid(publish_as_relid)) publish_as_relid = relid; @@ -389,7 +389,7 @@ pub_contains_invalid_column(Oid pubid, Relation relation, List *ancestors, */ if (pubviaroot && relation->rd_rel->relispartition) { - publish_as_relid = GetTopMostAncestorInPublication(pubid, ancestors, NULL); + publish_as_relid = GetTopMostAncestorInPublication(pubid, ancestors, NULL, NIL); if (!OidIsValid(publish_as_relid)) publish_as_relid = relid; @@ -849,7 +849,7 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) char publish_generated_columns; AclResult aclresult; List *relations = NIL; - List *exceptrelations = NIL; + List *except_pubtables = NIL; List *schemaidlist = NIL; /* must have CREATE privilege on database */ @@ -936,16 +936,16 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) /* Associate objects with the publication. */ ObjectsInPublicationToOids(stmt->pubobjects, pstate, &relations, - &exceptrelations, &schemaidlist); + &except_pubtables, &schemaidlist); if (stmt->for_all_tables) { /* Process EXCEPT table list */ - if (exceptrelations != NIL) + if (except_pubtables != NIL) { List *rels; - rels = OpenTableList(exceptrelations); + rels = OpenTableList(except_pubtables); PublicationAddTables(puboid, rels, true, NULL); CloseTableList(rels); } @@ -959,6 +959,8 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) } else if (!stmt->for_all_sequences) { + List *explicitrelids = NIL; + /* FOR TABLES IN SCHEMA requires superuser */ if (schemaidlist != NIL && !superuser()) ereport(ERROR, @@ -977,6 +979,19 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) schemaidlist != NIL, publish_via_partition_root); + /* + * Collect explicit table OIDs now, before we close the relation + * list, so that except-table validation below can check for + * contradictions without relying on a catalog scan that might not + * yet see the just-inserted rows. + */ + if (except_pubtables != NIL) + { + foreach_ptr(PublicationRelInfo, pri, rels) + explicitrelids = lappend_oid(explicitrelids, + RelationGetRelid(pri->relation)); + } + PublicationAddTables(puboid, rels, true, NULL); CloseTableList(rels); } @@ -989,6 +1004,34 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) */ LockSchemaList(schemaidlist); PublicationAddSchemas(puboid, schemaidlist, true, NULL); + + if (except_pubtables != NIL) + { + List *except_rels; + + except_rels = OpenTableList(except_pubtables); + + /* + * Validate that each excluded table is not also in the + * explicit table list (which would be contradictory). Use the + * in-memory explicitrelids collected above rather than + * re-reading the catalog, which may not yet see the + * just-inserted rows. + */ + foreach_ptr(PublicationRelInfo, pri, except_rels) + { + Oid except_relid = RelationGetRelid(pri->relation); + + if (list_member_oid(explicitrelids, except_relid)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" cannot appear in both the table list and the EXCEPT clause", + RelationGetQualifiedRelationName(pri->relation))); + } + + PublicationAddTables(puboid, except_rels, true, NULL); + CloseTableList(except_rels); + } } } @@ -1683,12 +1726,12 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) else { List *relations = NIL; - List *exceptrelations = NIL; + List *except_pubtables = NIL; List *schemaidlist = NIL; Oid pubid = pubform->oid; ObjectsInPublicationToOids(stmt->pubobjects, pstate, &relations, - &exceptrelations, &schemaidlist); + &except_pubtables, &schemaidlist); CheckAlterPublication(stmt, tup, relations, schemaidlist); @@ -1711,7 +1754,7 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) errmsg("publication \"%s\" does not exist", stmt->pubname)); - relations = list_concat(relations, exceptrelations); + relations = list_concat(relations, except_pubtables); AlterPublicationTables(stmt, tup, relations, pstate->p_sourcetext, schemaidlist != NIL); AlterPublicationSchemas(stmt, tup, schemaidlist); diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y index ff4e1388c55..4514ef7f9c2 100644 --- a/src/backend/parser/gram.y +++ b/src/backend/parser/gram.y @@ -58,6 +58,7 @@ #include "nodes/makefuncs.h" #include "nodes/nodeFuncs.h" #include "parser/parser.h" +#include "utils/builtins.h" #include "utils/datetime.h" #include "utils/xml.h" @@ -11272,7 +11273,7 @@ AlterOwnerStmt: ALTER AGGREGATE aggregate_with_argtypes OWNER TO RoleSpec * pub_obj is one of: * * TABLE table [, ...] - * TABLES IN SCHEMA schema [, ...] + * TABLES IN SCHEMA schema [EXCEPT (TABLE table [, ...] )] [, ...] * *****************************************************************************/ @@ -11332,23 +11333,26 @@ PublicationObjSpec: $$->pubtable->columns = $3; $$->pubtable->whereClause = $4; } - | TABLES IN_P SCHEMA ColId + | TABLES IN_P SCHEMA ColId opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_SCHEMA; $$->name = $4; + $$->except_tables = $5; $$->location = @4; } - | TABLES IN_P SCHEMA CURRENT_SCHEMA + | TABLES IN_P SCHEMA CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_CUR_SCHEMA; + $$->except_tables = $5; $$->location = @4; } - | ColId opt_column_list OptWhereClause + | ColId opt_column_list OptWhereClause opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $4; /* * If either a row filter or column list is specified, create * a PublicationTable object. @@ -11392,10 +11396,11 @@ PublicationObjSpec: $$->pubtable->columns = $2; $$->pubtable->whereClause = $3; } - | CURRENT_SCHEMA + | CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $2; $$->location = @1; } ; @@ -20784,6 +20789,8 @@ preprocess_pub_all_objtype_list(List *all_objects_list, List **pubobjects, /* * Process pubobjspec_list to check for errors in any of the objects and * convert PUBLICATIONOBJ_CONTINUATION into appropriate PublicationObjSpecType. + * Also flattens except_tables from TABLES IN SCHEMA nodes into the list so + * that ObjectsInPublicationToOids() sees them as top-level EXCEPT_TABLE entries. */ static void preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) @@ -20812,6 +20819,13 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLE) { + /* EXCEPT is not valid for table objects */ + if (pubobj->except_tables != NIL) + ereport(ERROR, + errcode(ERRCODE_SYNTAX_ERROR), + errmsg("EXCEPT is not allowed for TABLE publication objects"), + parser_errposition(pubobj->location)); + /* relation name or pubtable must be set for this type of object */ if (!pubobj->name && !pubobj->pubtable) ereport(ERROR, @@ -20860,6 +20874,34 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) errcode(ERRCODE_SYNTAX_ERROR), errmsg("invalid schema name"), parser_errposition(pubobj->location)); + + /* Flatten EXCEPT entries into the top-level list */ + foreach_ptr(PublicationObjSpec, eobj, pubobj->except_tables) + { + /* + * Unqualified names are implicitly qualified with the parent + * schema. Qualified names must match the parent schema — + * each EXCEPT clause is bound to exactly one schema, so + * cross-schema entries are rejected at parse time. + */ + if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLES_IN_SCHEMA) + { + const char *eobj_schemaname = eobj->pubtable->relation->schemaname; + const char *eobj_relname = eobj->pubtable->relation->relname; + + if (eobj_schemaname == NULL) + eobj->pubtable->relation->schemaname = pubobj->name; + else if (strcmp(eobj_schemaname, pubobj->name) != 0) + ereport(ERROR, + errcode(ERRCODE_SYNTAX_ERROR), + errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", + quote_qualified_identifier(eobj_schemaname, eobj_relname), + pubobj->name), + parser_errposition(eobj->location)); + } + } + pubobjspec_list = list_concat(pubobjspec_list, pubobj->except_tables); + pubobj->except_tables = NIL; } prevobjtype = pubobj->pubobjtype; diff --git a/src/backend/replication/pgoutput/pgoutput.c b/src/backend/replication/pgoutput/pgoutput.c index 4ecfcbff7ab..7ee84ec1c83 100644 --- a/src/backend/replication/pgoutput/pgoutput.c +++ b/src/backend/replication/pgoutput/pgoutput.c @@ -2097,6 +2097,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) * are absorbed while decoding WAL. */ List *schemaPubids = GetSchemaPublications(schemaId); + List *except_pubids; ListCell *lc; Oid publish_as_relid = relid; int publish_ancestor_level = 0; @@ -2104,6 +2105,28 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) char relkind = get_rel_relkind(relid); List *rel_publications = NIL; + /* + * For the schema EXCEPT check, we must look up the top-most ancestor + * rather than the relation itself. check_publication_add_relation() + * prevents individual partitions from appearing in the EXCEPT clause, + * so only a root (non-partition) table can have prexcept = true. + * Using the partition's own OID would always return NIL and miss the + * exclusion. + */ + Oid root_relid; + + if (am_partition) + { + List *ancestors = get_partition_ancestors(relid); + + root_relid = llast_oid(ancestors); + list_free(ancestors); + } + else + root_relid = relid; + + except_pubids = GetRelationExcludedPublications(root_relid); + /* Reload publications if needed before use. */ if (!publications_valid) { @@ -2267,7 +2290,8 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) ancestor = GetTopMostAncestorInPublication(pub->oid, ancestors, - &level); + &level, + except_pubids); if (ancestor != InvalidOid) { @@ -2281,7 +2305,8 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) } if (list_member_oid(pubids, pub->oid) || - list_member_oid(schemaPubids, pub->oid) || + (list_member_oid(schemaPubids, pub->oid) && + !list_member_oid(except_pubids, pub->oid)) || ancestor_published) publish = true; } @@ -2360,6 +2385,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) list_free(pubids); list_free(schemaPubids); + list_free(except_pubids); list_free(rel_publications); entry->replicate_valid = true; diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c index e1449654f96..e5b1a70e05e 100644 --- a/src/bin/psql/describe.c +++ b/src/bin/psql/describe.c @@ -7038,6 +7038,24 @@ describePublications(const char *pattern) if (!addFooterToPublicationDesc(&buf, _("Tables from schemas:"), true, &cont)) goto error_return; + + if (pset.sversion >= 190000) + { + /* + * Get tables in the EXCEPT clause for this schema + * publication. + */ + printfPQExpBuffer(&buf, + "SELECT concat(c.relnamespace::regnamespace, '.', c.relname)\n" + "FROM pg_catalog.pg_class c\n" + " JOIN pg_catalog.pg_publication_rel pr ON c.oid = pr.prrelid\n" + "WHERE pr.prpubid = '%s'\n" + " AND pr.prexcept\n" + "ORDER BY 1", pubid); + if (!addFooterToPublicationDesc(&buf, _("Except tables:"), + true, &cont)) + goto error_return; + } } } else diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index de547a8cb37..fe11dc619ac 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -1065,6 +1065,15 @@ static const SchemaQuery Query_for_trigger_of_table = { "SELECT nspname FROM pg_catalog.pg_namespace "\ " WHERE nspname LIKE '%s'" +#define Query_for_list_of_tables_in_schema \ +"SELECT n.nspname || '.' || c.relname "\ +" FROM pg_catalog.pg_class c "\ +" JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "\ +" WHERE c.relkind IN (" CppAsString2(RELKIND_RELATION) ", " \ + CppAsString2(RELKIND_PARTITIONED_TABLE) ") "\ +" AND (n.nspname || '.' || c.relname) LIKE '%s' "\ +" AND n.nspname = '%s'" + /* Use COMPLETE_WITH_QUERY_VERBATIM with these queries for GUC names: */ #define Query_for_list_of_alter_system_set_vars \ "SELECT pg_catalog.lower(name) FROM pg_catalog.pg_settings "\ @@ -3787,8 +3796,19 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); - else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && (!ends_with(prev_wd, ','))) - COMPLETE_WITH("WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE", "WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* Complete "CREATE PUBLICATION <name> [...] WITH" */ else if (Matches("CREATE", "PUBLICATION", MatchAnyN, "WITH", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/include/catalog/pg_publication.h b/src/include/catalog/pg_publication.h index 89b4bb14f62..53e3d7c6f3d 100644 --- a/src/include/catalog/pg_publication.h +++ b/src/include/catalog/pg_publication.h @@ -191,7 +191,8 @@ extern List *GetPubPartitionOptionRelations(List *result, PublicationPartOpt pub_partopt, Oid relid); extern Oid GetTopMostAncestorInPublication(Oid puboid, List *ancestors, - int *ancestor_level); + int *ancestor_level, + List *except_pubids); extern bool is_publishable_relation(Relation rel); extern bool is_schema_publication(Oid pubid); diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h index 91377a6cde3..98a03c0eeda 100644 --- a/src/include/nodes/parsenodes.h +++ b/src/include/nodes/parsenodes.h @@ -4493,6 +4493,8 @@ typedef struct PublicationObjSpec PublicationObjSpecType pubobjtype; /* type of this publication object */ char *name; PublicationTable *pubtable; + List *except_tables; /* tables specified in the EXCEPT clause (for + * TABLES IN SCHEMA) */ ParseLoc location; /* token location, or -1 if unknown */ } PublicationObjSpec; diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 29e54b214a0..008c6cebaca 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -270,6 +270,12 @@ CREATE PUBLICATION testpub_foralltables_excepttable2 FOR ALL TABLES EXCEPT (test ERROR: syntax error at or near "testpub_tbl1" LINE 1: ..._foralltables_excepttable2 FOR ALL TABLES EXCEPT (testpub_tb... ^ +-- fail - EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testpub_tbl3); +ERROR: EXCEPT is not allowed for TABLE publication objects +LINE 2: FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testp... + ^ --------------------------------------------- -- SET ALL TABLES/SEQUENCES --------------------------------------------- @@ -470,7 +476,103 @@ HINT: Change the publication's EXCEPT clause using ALTER PUBLICATION ... SET AL RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Create same-named tables in public to verify unqualified EXCEPT entries +-- are qualified with the named schema, not public +CREATE TABLE testpub_nopk (foo int, bar int); +CREATE TABLE testpub_tbl_s1 (a int primary key, b text); +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + Publication testpub_schema_except1 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- Exclude multiple tables using unqualified names; same-named tables exist in +-- public to confirm unqualified names resolve to pub_test, not public +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + Publication testpub_schema_except2 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_nopk" + "pub_test.testpub_tbl_s1" + +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testp... + ^ +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); +ERROR: table "pub_test.testpub_tbl_s1" in EXCEPT clause does not belong to schema "public" +LINE 2: ...R TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.t... + ^ +-- Multiple schemas each with their own EXCEPT clause +CREATE PUBLICATION testpub_schema_except_multi + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_schema_except_multi + Publication testpub_schema_except_multi + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- fail: table appears in both the explicit table list and the EXCEPT clause +CREATE PUBLICATION testpub_except_conflict + FOR TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot appear in both the table list and the EXCEPT clause +-- fail: nonexistent table in EXCEPT clause +CREATE PUBLICATION testpub_except_norel + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- fail: partition cannot appear in EXCEPT clause; only root tables are allowed +CREATE TABLE pub_test.testpub_parted_s (a int) PARTITION BY LIST (a); +CREATE TABLE pub_test.testpub_part_s PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (1); +CREATE PUBLICATION testpub_except_partition + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); +ERROR: cannot specify relation "pub_test.testpub_part_s" in the publication EXCEPT clause +DETAIL: This operation is not supported for individual partitions. +-- fail: TABLE keyword is required for the first entry in the EXCEPT clause +CREATE PUBLICATION testpub_except_nokw + FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +ERROR: syntax error at or near "testpub_nopk" +LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + ^ +-- Cleanup +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP TABLE pub_test.testpub_parted_s CASCADE; +DROP TABLE testpub_nopk, testpub_tbl_s1; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +--------------------------------------------- +-- Tests for publications with SEQUENCES +--------------------------------------------- CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; -- FOR ALL SEQUENCES diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 041e14a4de6..9162d4d15a5 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -123,6 +123,9 @@ CREATE PUBLICATION testpub_foralltables_excepttable1 FOR ALL TABLES EXCEPT (TABL \d testpub_tbl1 -- fail - first table in the EXCEPT list should use TABLE keyword CREATE PUBLICATION testpub_foralltables_excepttable2 FOR ALL TABLES EXCEPT (testpub_tbl1, testpub_tbl2); +-- fail - EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testpub_tbl3); --------------------------------------------- -- SET ALL TABLES/SEQUENCES @@ -220,7 +223,71 @@ RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Create same-named tables in public to verify unqualified EXCEPT entries +-- are qualified with the named schema, not public +CREATE TABLE testpub_nopk (foo int, bar int); +CREATE TABLE testpub_tbl_s1 (a int primary key, b text); + +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + +-- Exclude multiple tables using unqualified names; same-named tables exist in +-- public to confirm unqualified names resolve to pub_test, not public +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); + +-- Multiple schemas each with their own EXCEPT clause +CREATE PUBLICATION testpub_schema_except_multi + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_schema_except_multi + +-- fail: table appears in both the explicit table list and the EXCEPT clause +CREATE PUBLICATION testpub_except_conflict + FOR TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: nonexistent table in EXCEPT clause +CREATE PUBLICATION testpub_except_norel + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- fail: partition cannot appear in EXCEPT clause; only root tables are allowed +CREATE TABLE pub_test.testpub_parted_s (a int) PARTITION BY LIST (a); +CREATE TABLE pub_test.testpub_part_s PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (1); +CREATE PUBLICATION testpub_except_partition + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); + +-- fail: TABLE keyword is required for the first entry in the EXCEPT clause +CREATE PUBLICATION testpub_except_nokw + FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + +-- Cleanup +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP TABLE pub_test.testpub_parted_s CASCADE; +DROP TABLE testpub_nopk, testpub_tbl_s1; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; + +--------------------------------------------- +-- Tests for publications with SEQUENCES +--------------------------------------------- CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 8c58d282eee..18c7b2c1fca 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -24,14 +24,17 @@ my $result; sub test_except_root_partition { - my ($pubviaroot) = @_; + my ($pubviaroot, $pubsql) = @_; + $pubsql //= + "CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1)"; + $pubsql .= " WITH (publish_via_partition_root = $pubviaroot)"; # If the root partitioned table is in the EXCEPT clause, all its # partitions are excluded from publication, regardless of the # publish_via_partition_root setting. $node_publisher->safe_psql( 'postgres', qq( - CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1) WITH (publish_via_partition_root = $pubviaroot); + $pubsql; INSERT INTO root1 VALUES (1), (101); )); $node_subscriber->safe_psql('postgres', @@ -223,6 +226,131 @@ $node_subscriber->safe_psql( test_except_root_partition('false'); test_except_root_partition('true'); +# Same validation using TABLES IN SCHEMA instead of FOR ALL TABLES. +my $schema_pub = + "CREATE PUBLICATION tap_pub_part FOR TABLES IN SCHEMA public EXCEPT (TABLE public.root1)"; +test_except_root_partition('false', $schema_pub); +test_except_root_partition('true', $schema_pub); + +# ============================================ +# EXCEPT test cases for TABLES IN SCHEMA +# ============================================ + +# Create a dedicated schema with two tables: one to be published and one to be +# excluded. Also create inherited tables to verify ONLY semantics. +$node_publisher->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_published AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.tab_excluded AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.parent (a int); + CREATE TABLE sch1.child (b int) INHERITS (sch1.parent); +)); + +$node_subscriber->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_published (a int); + CREATE TABLE sch1.tab_excluded (a int); + CREATE TABLE sch1.parent (a int); + CREATE TABLE sch1.child (b int) INHERITS (sch1.parent); +)); + +# Basic test: initial sync respects EXCEPT. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_excluded)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: initial sync copies included table'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: initial sync skips excluded table'); + +# DML: only the included table should be replicated. +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (6); + INSERT INTO sch1.tab_excluded VALUES (6); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(6), + 'TABLES IN SCHEMA EXCEPT: DML on included table is replicated'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: DML on excluded table is not replicated'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Inherited tables: excluding the parent (without ONLY) also excludes the child. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.parent)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.child VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.child"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: excluding parent (without ONLY) also excludes child' +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Test that EXCEPT (TABLE ONLY parent) excludes only the parent itself, not its +# child. Truncate child first so rows from the previous test are not copied by +# the initial table sync of the next subscription. +$node_publisher->safe_psql('postgres', 'TRUNCATE sch1.child'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE sch1.child'); +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE ONLY sch1.parent)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.child VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.child"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: ONLY parent in EXCEPT does not exclude child'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Cleanup schema tables before the multi-publication section. +$node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); +$node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); + # ============================================ # Test when a subscription is subscribing to multiple publications # ============================================ @@ -254,6 +382,7 @@ $node_publisher->safe_psql( DROP PUBLICATION tap_pub2; TRUNCATE tab1; )); +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_subscriber->safe_psql('postgres', qq(TRUNCATE tab1)); # OK when a table is excluded by pub1 EXCEPT clause, but it is included by pub2 -- 2.50.1 (Apple Git-155)
v8-0002-tab-complete-to-give-suggestions-in-case-of-multi.patch (application/x-patch, 3.3K) download From 52fc21fba3983485406565321e0607057fa8e48e Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Fri, 29 May 2026 19:50:12 +0530 Subject: [PATCH v8 2/4] tab complete to give suggestions in case of multi-schema. --- src/bin/psql/tab-complete.in.c | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index fe11dc619ac..831be27ad08 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -3791,24 +3791,40 @@ match_previous_words(int pattern_id, /* * Complete "CREATE PUBLICATION <name> FOR TABLES IN SCHEMA <schema>, ..." + * + * Use HeadMatches+TailMatches instead of Matches for the EXCEPT sub-rules + * so that a comma-separated schema list (e.g. "SCHEMA s1, s2") is handled + * correctly: HeadMatches anchors the fixed prefix while TailMatches anchors + * the fixed suffix, leaving any number of schema tokens in between. */ else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA")) COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); - else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && !ends_with(prev_wd, ',')) - COMPLETE_WITH("EXCEPT ( TABLE", "WITH ("); - else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + else if (HeadMatches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA") && + TailMatches(MatchAny, "EXCEPT")) COMPLETE_WITH("( TABLE"); - else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + else if (HeadMatches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA") && + TailMatches(MatchAny, "EXCEPT", "(")) COMPLETE_WITH("TABLE"); - else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + else if (HeadMatches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA") && + TailMatches(MatchAny, "EXCEPT", "(", "TABLE")) { set_completion_reference(prev4_wd); COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); } + /* Single-schema path: handles zero-or-more table names after TABLE */ else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) COMPLETE_WITH(")"); + /* Multi-schema path: covers exactly one table name after TABLE */ + else if (HeadMatches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA") && + TailMatches("EXCEPT", "(", "TABLE", MatchAny) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); + else if (HeadMatches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA") && + (TailMatches("SCHEMA", MatchAny) || ends_with(prev2_wd, ',')) && + !ends_with(prev_wd, ',') && !ends_with(prev_wd, ')') && + !TailMatches(MatchAny, "=", MatchAny, MatchAny)) + COMPLETE_WITH("EXCEPT ( TABLE", "WITH ("); /* Complete "CREATE PUBLICATION <name> [...] WITH" */ else if (Matches("CREATE", "PUBLICATION", MatchAnyN, "WITH", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); -- 2.50.1 (Apple Git-155)
v8-0003-Add-EXCEPT-support-to-ALTER-PUBLICATION-ADD-TABLE.patch (application/x-patch, 22.6K) download From 6b0adb50ccda7ace301d398e4f5fc43e14b74c98 Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Fri, 29 May 2026 20:04:57 +0530 Subject: [PATCH v8 3/4] Add EXCEPT support to ALTER PUBLICATION ADD TABLES IN SCHEMA Extend the EXCEPT clause support to allow tables to be excluded when adding a schema to a publication via ALTER PUBLICATION ... ADD. Syntax: ALTER PUBLICATION pub ADD TABLES IN SCHEMA s EXCEPT (TABLE s.t1); Since pg_dump uses ALTER PUBLICATION ... ADD, support for it is included in this patch. --- doc/src/sgml/ref/alter_publication.sgml | 40 +++++++- src/backend/catalog/pg_publication.c | 19 ++-- src/backend/commands/publicationcmds.c | 108 +++++++++++++++++++++- src/bin/pg_dump/pg_dump.c | 30 +++++- src/bin/pg_dump/t/002_pg_dump.pl | 36 ++++++++ src/bin/psql/tab-complete.in.c | 15 +++ src/test/regress/expected/publication.out | 32 ++++++- src/test/regress/sql/publication.sql | 20 +++- src/test/subscription/t/037_except.pl | 32 +++++++ 9 files changed, 317 insertions(+), 15 deletions(-) diff --git a/doc/src/sgml/ref/alter_publication.sgml b/doc/src/sgml/ref/alter_publication.sgml index aa32bb169e9..73f6375a66f 100644 --- a/doc/src/sgml/ref/alter_publication.sgml +++ b/doc/src/sgml/ref/alter_publication.sgml @@ -31,7 +31,7 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA <replaceable class="parameter">tables_in_schema</replaceable> [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -47,6 +47,10 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <replaceable class="parameter">table_object</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] [ WHERE ( <replaceable class="parameter">expression</replaceable> ) ] +<phrase>and <replaceable class="parameter">tables_in_schema</replaceable> is:</phrase> + + { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] + <phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> TABLE <replaceable class="parameter">table_object</replaceable> [, ... ] @@ -110,6 +114,14 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <literal>ADD TABLE</literal>. </para> + <para> + The <literal>EXCEPT</literal> clause can be used with + <literal>ADD TABLES IN SCHEMA</literal> to exclude specific tables from the + publication. Using <literal>DROP TABLES IN SCHEMA</literal> on a publication + will automatically also remove any associated <literal>EXCEPT</literal> + entries. + </para> + <para> The fourth variant of this command listed in the synopsis can change all of the publication properties specified in @@ -198,6 +210,22 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r </listitem> </varlistentry> + <varlistentry> + <term><literal>EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] )</literal></term> + <listitem> + <para> + When used with <literal>ADD TABLES IN SCHEMA</literal>, specifies + tables to be excluded from the publication. Each named + table must belong to the schema specified in the same + <literal>TABLES IN SCHEMA</literal> clause. Table names may be + schema-qualified or unqualified; unqualified names are implicitly + qualified with the schema named in the same clause. See + <xref linkend="sql-createpublication"/> for further details on the + semantics of <literal>EXCEPT</literal>. + </para> + </listitem> + </varlistentry> + <varlistentry> <term><literal>SET ( <replaceable class="parameter">publication_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] )</literal></term> <listitem> @@ -288,6 +316,16 @@ ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA marketing, sales; </programlisting> </para> + <para> + Add schema <structname>sales</structname> to the publication + <structname>sales_publication</structname>, excluding the + <structname>sales.internal</structname> and + <structname>sales.drafts</structname> tables: +<programlisting> +ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA sales EXCEPT (TABLE internal, drafts); +</programlisting> + </para> + <para> Add tables <structname>users</structname>, <structname>departments</structname> and schema diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index 4af0d74814a..b30eada51df 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -649,15 +649,18 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, * here, as CreatePublication() function invalidates all relations as part * of defining a FOR ALL TABLES publication. * - * For ALTER PUBLICATION, invalidation is needed only when adding an - * EXCEPT table to a publication already marked as ALL TABLES. For - * publications that were originally empty or defined as ALL SEQUENCES and - * are being converted to ALL TABLES, invalidation is skipped here, as - * AlterPublicationAllFlags() function invalidates all relations while - * marking the publication as ALL TABLES publication. + * For ALTER PUBLICATION, invalidation is needed when adding an EXCEPT + * table to either a FOR ALL TABLES publication (pub->alltables is true) + * or a FOR TABLES IN SCHEMA publication (is_schema_publication is true). + * The exception: when a publication is being converted to FOR ALL TABLES + * (pub->alltables is still false at this point), + * AlterPublicationAllFlags() will perform a full invalidation, so we + * skip it here. */ - inval_except_table = (alter_stmt != NULL) && pub->alltables && - (alter_stmt->for_all_tables && pri->except); + inval_except_table = (alter_stmt != NULL) && pri->except && + (pub->alltables + ? alter_stmt->for_all_tables + : is_schema_publication(pubid)); if (!pri->except || inval_except_table) { diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index cd39d6375cd..f9ae00a6c2f 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -70,6 +70,13 @@ static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok); static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); +static void AlterPublicationSchemas(AlterPublicationStmt *stmt, + HeapTuple tup, List *schemaidlist, + List *except_pubtables); +static void AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, + List *except_pubtables, + List *schemaidlist); static char defGetGeneratedColsOption(DefElem *def); @@ -1468,7 +1475,8 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, */ static void AlterPublicationSchemas(AlterPublicationStmt *stmt, - HeapTuple tup, List *schemaidlist) + HeapTuple tup, List *schemaidlist, + List *except_pubtables) { Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); @@ -1545,6 +1553,98 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, */ PublicationAddSchemas(pubform->oid, schemaidlist, true, stmt); } + + /* + * Increment the command counter so that is_schema_publication() in + * GetExcludedPublicationTables() can see the just-inserted schema + * rows when AlterPublicationSchemaExceptTables runs next. + */ + if (stmt->action == AP_AddObjects || stmt->action == AP_SetObjects) + CommandCounterIncrement(); + + AlterPublicationSchemaExceptTables(stmt, tup, except_pubtables, schemaidlist); +} + +/* + * Alter the EXCEPT list of a schema-level publication. + * + * Adds, removes, or replaces except-table entries in pg_publication_rel + * (rows with prexcept = true). These entries suppress publication of the + * named tables that would otherwise be covered by a FOR TABLES IN SCHEMA + * clause. + */ +static void +AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, List *except_pubtables, + List *schemaidlist) +{ + Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); + Oid pubid = pubform->oid; + + /* + * Nothing to do if no EXCEPT entries. + */ + if (!except_pubtables) + return; + + /* + * This function handles EXCEPT entries for schema-level publications + * only. For FOR ALL TABLES publications, EXCEPT entries are already + * processed by AlterPublicationTables(). + */ + if (schemaidlist == NIL && !is_schema_publication(pubid)) + return; + + /* + * EXCEPT is not meaningful with DROP: dropping a schema from a + * publication already removes all its except entries via cascade, and + * there is no sensible interpretation of "drop only the except entry but + * keep the schema". + */ + if (stmt->action == AP_DropObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); + + /* + * XXX EXCEPT with SET is not currently implemented. Workaround: DROP and + * re-ADD the schema with the desired EXCEPT list. + */ + if (stmt->action == AP_SetObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"), + errhint("Drop and re-add the schema with the desired EXCEPT list."))); + + if (stmt->action == AP_AddObjects) + { + List *rels; + List *explicitrelids; + + rels = OpenTableList(except_pubtables); + + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + /* + * Validate that each excluded table is not also in the explicit table + * list (which would be contradictory). + */ + foreach_ptr(PublicationRelInfo, pri, rels) + { + Oid relid = RelationGetRelid(pri->relation); + + if (list_member_oid(explicitrelids, relid)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" cannot appear in both the table list and the EXCEPT clause", + RelationGetQualifiedRelationName(pri->relation))); + } + + PublicationAddTables(pubid, rels, false, stmt); + + CloseTableList(rels); + } } /* @@ -1754,10 +1854,12 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) errmsg("publication \"%s\" does not exist", stmt->pubname)); - relations = list_concat(relations, except_pubtables); + if (stmt->for_all_tables) + relations = list_concat(relations, except_pubtables); + AlterPublicationTables(stmt, tup, relations, pstate->p_sourcetext, schemaidlist != NIL); - AlterPublicationSchemas(stmt, tup, schemaidlist); + AlterPublicationSchemas(stmt, tup, schemaidlist, except_pubtables); AlterPublicationAllFlags(stmt, rel, tup); } diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c index d56dcc701ce..e62d74c8ca0 100644 --- a/src/bin/pg_dump/pg_dump.c +++ b/src/bin/pg_dump/pg_dump.c @@ -5019,6 +5019,7 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) PublicationInfo *pubinfo = pubsinfo->publication; PQExpBuffer query; char *tag; + bool has_except = false; /* Do nothing if not dumping schema */ if (!dopt->dumpSchema) @@ -5029,7 +5030,34 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) query = createPQExpBuffer(); appendPQExpBuffer(query, "ALTER PUBLICATION %s ", fmtId(pubinfo->dobj.name)); - appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s;\n", fmtId(schemainfo->dobj.name)); + appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s", fmtId(schemainfo->dobj.name)); + + /* + * Append EXCEPT clause for any tables that belong to this schema + * and are excluded from the publication. + */ + for (SimplePtrListCell *cell = pubinfo->except_tables.head; cell; cell = cell->next) + { + TableInfo *tbinfo = (TableInfo *) cell->ptr; + + if (strcmp(tbinfo->dobj.namespace->dobj.name, schemainfo->dobj.name) == 0) + { + if (!has_except) + { + appendPQExpBufferStr(query, " EXCEPT ("); + has_except = true; + } + else + appendPQExpBufferStr(query, ", "); + + appendPQExpBuffer(query, "TABLE ONLY %s", fmtId(tbinfo->dobj.name)); + } + } + + if (has_except) + appendPQExpBufferStr(query, ")"); + + appendPQExpBufferStr(query, ";\n"); /* * There is no point in creating drop query as the drop is done by schema diff --git a/src/bin/pg_dump/t/002_pg_dump.pl b/src/bin/pg_dump/t/002_pg_dump.pl index 3ee9fda50e4..ed722140877 100644 --- a/src/bin/pg_dump/t/002_pg_dump.pl +++ b/src/bin/pg_dump/t/002_pg_dump.pl @@ -3242,6 +3242,42 @@ my %tests = ( like => { %full_runs, section_post_data => 1, }, }, + 'CREATE PUBLICATION pub11' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub11 FOR TABLES IN SCHEMA dump_test EXCEPT (TABLE test_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub11 WITH (publish = 'insert, update, delete, truncate');\E + /xm, + like => { %full_runs, section_post_data => 1, }, + }, + + 'CREATE PUBLICATION pub11 - ADD TABLES IN SCHEMA EXCEPT dump' + => { + regexp => qr/^ + \QALTER PUBLICATION pub11 ADD TABLES IN SCHEMA dump_test EXCEPT (TABLE ONLY test_table);\E + /xm, + like => { %full_runs, section_post_data => 1, }, + }, + + 'CREATE PUBLICATION pub12' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub12 FOR TABLES IN SCHEMA dump_test EXCEPT (TABLE test_table, dump_test.test_second_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub12 WITH (publish = 'insert, update, delete, truncate');\E + /xm, + like => { %full_runs, section_post_data => 1, }, + }, + + 'CREATE PUBLICATION pub12 - ADD TABLES IN SCHEMA EXCEPT dump' + => { + regexp => qr/^ + \QALTER PUBLICATION pub12 ADD TABLES IN SCHEMA dump_test EXCEPT (TABLE ONLY test_table, TABLE ONLY test_second_table);\E + /xm, + like => { %full_runs, section_post_data => 1, }, + }, + 'CREATE SUBSCRIPTION sub1' => { create_order => 50, create_sql => 'CREATE SUBSCRIPTION sub1 diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index 831be27ad08..3ffe7c6e2e9 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2364,6 +2364,21 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); + /* After a single schema name in ADD context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 008c6cebaca..f56b0524ae9 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -564,12 +564,42 @@ CREATE PUBLICATION testpub_except_nokw ERROR: syntax error at or near "testpub_nopk" LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); ^ +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; +-- fail: non-existing table in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- fail: EXCEPT table belongs to a different schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 1: ...xcept ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.tes... + ^ +-- fail: TABLE keyword is required for the first entry in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +ERROR: syntax error at or near "testpub_nopk" +LINE 1: ...lter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_no... + ^ +-- ADD: qualified and unqualified names; unqualified is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + "pub_test.testpub_tbl_s2" + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP TABLE pub_test.testpub_parted_s CASCADE; DROP TABLE testpub_nopk, testpub_tbl_s1; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi, testpub_alter_except; --------------------------------------------- -- Tests for publications with SEQUENCES --------------------------------------------- diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 9162d4d15a5..072d50050cd 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -278,12 +278,30 @@ CREATE PUBLICATION testpub_except_partition CREATE PUBLICATION testpub_except_nokw FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; + +-- fail: non-existing table in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- fail: EXCEPT table belongs to a different schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- fail: TABLE keyword is required for the first entry in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + +-- ADD: qualified and unqualified names; unqualified is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); +\dRp+ testpub_alter_except + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP TABLE pub_test.testpub_parted_s CASCADE; DROP TABLE testpub_nopk, testpub_tbl_s1; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi, testpub_alter_except; --------------------------------------------- -- Tests for publications with SEQUENCES diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 18c7b2c1fca..0ba6d6f8bb2 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -347,6 +347,38 @@ is($result, qq(5), $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); +# ============================================ +# ALTER PUBLICATION EXCEPT for TABLES IN SCHEMA +# ============================================ + +# Truncate subscriber tables to remove data accumulated from previous tests. +$node_subscriber->safe_psql('postgres', + 'TRUNCATE sch1.tab_published, sch1.tab_excluded, sch1.parent, sch1.child'); + +# ADD: add a schema with an excepted table; verify the except entry takes effect. +$node_publisher->safe_psql('postgres', "CREATE PUBLICATION sch_pub"); +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub ADD TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_excluded)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(6), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: included table synced'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + # Cleanup schema tables before the multi-publication section. $node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); $node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); -- 2.50.1 (Apple Git-155)
v8-0004-Add-EXCEPT-support-to-ALTER-PUBLICATION-SET-TABLE.patch (application/x-patch, 25.6K) download From 46a4921a8958455bd4847a3f92cf316db6a57318 Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Fri, 29 May 2026 22:46:10 +0530 Subject: [PATCH v8 4/4] Add EXCEPT support to ALTER PUBLICATION SET TABLES IN SCHEMA Extend AlterPublicationExceptTables() with the AP_SetObjects case, which redefines the publication and replaces the entire EXCEPT list. Syntax: ALTER PUBLICATION pub SET TABLES IN SCHEMA s EXCEPT (TABLE t1); This patch also cleans up EXCEPT entries when a schema is dropped from the publication. --- doc/src/sgml/ref/alter_publication.sgml | 27 +++- src/backend/commands/publicationcmds.c | 131 ++++++++++++++++++-- src/backend/replication/pgoutput/pgoutput.c | 10 +- src/bin/psql/tab-complete.in.c | 15 +++ src/test/regress/expected/publication.out | 86 +++++++++++++ src/test/regress/sql/publication.sql | 38 ++++++ src/test/subscription/t/037_except.pl | 85 +++++++++++++ 7 files changed, 368 insertions(+), 24 deletions(-) diff --git a/doc/src/sgml/ref/alter_publication.sgml b/doc/src/sgml/ref/alter_publication.sgml index 73f6375a66f..80b038e4b2e 100644 --- a/doc/src/sgml/ref/alter_publication.sgml +++ b/doc/src/sgml/ref/alter_publication.sgml @@ -97,7 +97,11 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r used with a publication defined with <literal>FOR TABLE</literal> or <literal>FOR TABLES IN SCHEMA</literal>, replaces the list of tables/schemas in the publication with the specified list; the existing tables or schemas - that were present in the publication will be removed. + that were present in the publication will be removed. When + <literal>SET TABLES IN SCHEMA</literal> is used with an + <literal>EXCEPT</literal> clause, the excluded tables for each schema are + replaced with the specified list; if <literal>EXCEPT</literal> is omitted + for a schema, any existing exclusions for that schema are cleared. </para> <para> @@ -116,10 +120,8 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <para> The <literal>EXCEPT</literal> clause can be used with - <literal>ADD TABLES IN SCHEMA</literal> to exclude specific tables from the - publication. Using <literal>DROP TABLES IN SCHEMA</literal> on a publication - will automatically also remove any associated <literal>EXCEPT</literal> - entries. + <literal>ADD TABLES IN SCHEMA</literal> to exclude specific tables from a + schema-level publication. </para> <para> @@ -214,7 +216,8 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <term><literal>EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] )</literal></term> <listitem> <para> - When used with <literal>ADD TABLES IN SCHEMA</literal>, specifies + When used with <literal>ADD TABLES IN SCHEMA</literal> + or <literal>SET TABLES IN SCHEMA</literal>, specifies tables to be excluded from the publication. Each named table must belong to the schema specified in the same <literal>TABLES IN SCHEMA</literal> clause. Table names may be @@ -326,6 +329,18 @@ ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA sales EXCEPT (TABLE int </programlisting> </para> + <para> + Replace the schema list of <structname>sales_publication</structname> with + <structname>sales</structname>, excluding only + <structname>sales.drafts</structname>. Other than + <structname>sales.drafts</structname>, any previously excluded tables for schema + <structname>sales</structname> are no longer excluded. Any schemas previously in + <structname>sales_publication</structname> are removed: +<programlisting> +ALTER PUBLICATION sales_publication SET TABLES IN SCHEMA sales EXCEPT (TABLE drafts); +</programlisting> + </para> + <para> Add tables <structname>users</structname>, <structname>departments</structname> and schema diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index f9ae00a6c2f..660fd41afbb 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -1582,9 +1582,11 @@ AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, Oid pubid = pubform->oid; /* - * Nothing to do if no EXCEPT entries. + * Nothing to do if there are no EXCEPT entries, unless handling the SET + * command, because if the user has removed all exceptions we need to + * drop any existing ones. */ - if (!except_pubtables) + if (!except_pubtables && stmt->action != AP_SetObjects) return; /* @@ -1597,7 +1599,7 @@ AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, /* * EXCEPT is not meaningful with DROP: dropping a schema from a - * publication already removes all its except entries via cascade, and + * publication already removes all its EXCEPT entries via cascade, and * there is no sensible interpretation of "drop only the except entry but * keep the schema". */ @@ -1606,16 +1608,6 @@ AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); - /* - * XXX EXCEPT with SET is not currently implemented. Workaround: DROP and - * re-ADD the schema with the desired EXCEPT list. - */ - if (stmt->action == AP_SetObjects) - ereport(ERROR, - (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"), - errhint("Drop and re-add the schema with the desired EXCEPT list."))); - if (stmt->action == AP_AddObjects) { List *rels; @@ -1643,6 +1635,86 @@ AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, PublicationAddTables(pubid, rels, false, stmt); + CloseTableList(rels); + } + else /* AP_SetObjects */ + { + List *oldexceptrelids = NIL; + List *newexceptrelids = NIL; + List *delrelids = NIL; + List *rels; + List *explicitrelids; + + rels = OpenTableList(except_pubtables); + + /* Collect OIDs of the desired new EXCEPT list. */ + foreach_ptr(PublicationRelInfo, pri, rels) + { + newexceptrelids = lappend_oid(newexceptrelids, + RelationGetRelid(pri->relation)); + } + + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + /* + * Validate that each excluded table is not also in the explicit table + * list (which would be contradictory). + */ + foreach_ptr(PublicationRelInfo, pri, rels) + { + Oid relid = RelationGetRelid(pri->relation); + + if (list_member_oid(explicitrelids, relid)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" cannot appear in both the table list and the EXCEPT clause", + RelationGetQualifiedRelationName(pri->relation))); + } + + /* + * Get the current set of EXCEPT entries. Only FOR ALL TABLES and + * schema-level publications can have EXCEPT entries; for any other + * publication type oldexceptrelids stays NIL. + * + * Note: we check is_schema_publication() against the current catalog + * state (before AlterPublicationSchemas has run), so if the caller is + * doing SET TABLE t1 to convert a schema publication into a plain + * table publication, is_schema_publication() still returns true here. + * That is intentional: it lets us discover and clean up any stale + * EXCEPT entries that belong to the old schema definition. + */ + if (GetPublication(pubid)->alltables || is_schema_publication(pubid)) + oldexceptrelids = GetExcludedPublicationTables(pubid, + PUBLICATION_PART_ROOT); + + /* Build a list of old EXCEPT entries not present in the new list. */ + foreach_oid(oldrelid, oldexceptrelids) + { + if (!list_member_oid(newexceptrelids, oldrelid)) + delrelids = lappend_oid(delrelids, oldrelid); + } + + /* Drop old EXCEPT entries not present in the new list. */ + foreach_oid(relid, delrelids) + { + Oid proid; + ObjectAddress obj; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (!OidIsValid(proid)) + continue; /* already gone */ + + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + + /* Add new EXCEPT entries, skipping any already present. */ + PublicationAddTables(pubid, rels, true, stmt); + CloseTableList(rels); } } @@ -2292,6 +2364,7 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) foreach(lc, schemas) { Oid schemaid = lfirst_oid(lc); + List *except_relids; psid = GetSysCacheOid2(PUBLICATIONNAMESPACEMAP, Anum_pg_publication_namespace_oid, @@ -2308,8 +2381,40 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) get_namespace_name(schemaid)))); } + /* + * Collect EXCEPT entries for tables belonging to this schema before + * removing the schema entry. + */ + except_relids = GetExcludedPublicationTables(pubid, PUBLICATION_PART_ROOT); + ObjectAddressSet(obj, PublicationNamespaceRelationId, psid); performDeletion(&obj, DROP_CASCADE, 0); + + /* + * Drop any prexcept rows for tables belonging to this schema. These + * rows have no pg_depend entry pointing at the + * pg_publication_namespace row, so they are not cascaded by the + * performDeletion() call above and must be cleaned up explicitly. + */ + foreach_oid(relid, except_relids) + { + Oid proid; + + if (get_rel_namespace(relid) != schemaid) + continue; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (!OidIsValid(proid)) + continue; /* already gone */ + + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + + list_free(except_relids); } } diff --git a/src/backend/replication/pgoutput/pgoutput.c b/src/backend/replication/pgoutput/pgoutput.c index 7ee84ec1c83..9831be54b47 100644 --- a/src/backend/replication/pgoutput/pgoutput.c +++ b/src/backend/replication/pgoutput/pgoutput.c @@ -2229,7 +2229,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) */ if (pub->alltables) { - List *exceptpubids = NIL; + List *except_pubids = NIL; if (am_partition) { @@ -2252,7 +2252,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) * clause. Therefore, for a partition, exclusion must be * evaluated at the top-most ancestor. */ - exceptpubids = GetRelationExcludedPublications(last_ancestor_relid); + except_pubids = GetRelationExcludedPublications(last_ancestor_relid); } else { @@ -2260,13 +2260,13 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) * For a regular table or a root partitioned table, check * exclusion on table itself. */ - exceptpubids = GetRelationExcludedPublications(pub_relid); + except_pubids = GetRelationExcludedPublications(pub_relid); } - if (!list_member_oid(exceptpubids, pub->oid)) + if (!list_member_oid(except_pubids, pub->oid)) publish = true; - list_free(exceptpubids); + list_free(except_pubids); if (!publish) continue; diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index 3ffe7c6e2e9..f2fcfca305c 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2379,6 +2379,21 @@ match_previous_words(int pattern_id, } else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) COMPLETE_WITH(")"); + /* After a single schema name in SET context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index f56b0524ae9..70715ce7e10 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -594,6 +594,92 @@ Except tables: "pub_test.testpub_tbl_s1" "pub_test.testpub_tbl_s2" +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s2" + +-- fail: table in EXCEPT clause also appears in the explicit table list +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot appear in both the table list and the EXCEPT clause +-- error: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 1: ...xcept SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.tes... + ^ +-- SET: unqualified name in EXCEPT is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- SET without EXCEPT clears the existing except list +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + +-- SET to a different schema removes old schema's EXCEPT entries +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA public; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "public" + +-- fail: nonexistent table in EXCEPT clause (SET path) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- SET: multiple schemas each with their own EXCEPT clause +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- error: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +ERROR: EXCEPT clause is not supported with DROP in ALTER PUBLICATION +-- DROP TABLES IN SCHEMA removes associated EXCEPT entries +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "public" +Except tables: + "public.testpub_tbl1" + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 072d50050cd..72bb2f7a028 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -296,6 +296,44 @@ ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (tes ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); \dRp+ testpub_alter_except +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + +-- fail: table in EXCEPT clause also appears in the explicit table list +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- error: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- SET: unqualified name in EXCEPT is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +\dRp+ testpub_alter_except + +-- SET without EXCEPT clears the existing except list +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + +-- SET to a different schema removes old schema's EXCEPT entries +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA public; +\dRp+ testpub_alter_except + +-- fail: nonexistent table in EXCEPT clause (SET path) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- SET: multiple schemas each with their own EXCEPT clause +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_alter_except + +-- error: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); + +-- DROP TABLES IN SCHEMA removes associated EXCEPT entries +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 0ba6d6f8bb2..1308b6e43ed 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -376,6 +376,61 @@ $result = is($result, qq(0), 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); +# SET: replace the except list; tab_excluded is now included and tab_published is excluded. +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_published)" +); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (7); + INSERT INTO sch1.tab_excluded VALUES (7); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT a FROM sch1.tab_excluded WHERE a = 7"); +is($result, qq(7), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: newly included table is replicated' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT a FROM sch1.tab_published WHERE a = 7"); +is($result, qq(), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: now-excluded table is not replicated' +); + +# SET without EXCEPT: clears the except list; both tables are now published. +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1"); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (8); + INSERT INTO sch1.tab_excluded VALUES (8); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT a FROM sch1.tab_published WHERE a = 8"); +is($result, qq(8), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_published replicated after except list cleared' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT a FROM sch1.tab_excluded WHERE a = 8"); +is($result, qq(8), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_excluded replicated after except list cleared' +); + $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); @@ -443,6 +498,36 @@ $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); +# OK when a table is excluded by a TABLES IN SCHEMA EXCEPT publication, +# but is included by another publication. +$node_publisher->safe_psql('postgres', 'TRUNCATE tab1'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE tab1'); + +$node_publisher->safe_psql( + 'postgres', qq( + CREATE PUBLICATION tap_pub1 FOR TABLES IN SCHEMA public EXCEPT (TABLE public.tab1); + CREATE PUBLICATION tap_pub2 FOR TABLE tab1; + INSERT INTO tab1 VALUES(1); +)); +$node_subscriber->psql('postgres', + "CREATE SUBSCRIPTION tap_sub CONNECTION '$publisher_connstr' PUBLICATION tap_pub1, tap_pub2" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'tap_sub'); + +$node_publisher->safe_psql('postgres', qq(INSERT INTO tab1 VALUES(2))); +$node_publisher->wait_for_catchup('tap_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT * FROM tab1 ORDER BY a"); +is( $result, qq(1 +2), + "TABLES IN SCHEMA EXCEPT: table excluded in schema pub but included by another pub is replicated" +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); + $node_publisher->stop('fast'); done_testing(); -- 2.50.1 (Apple Git-155)
^ permalink raw reply [nested|flat] 196+ messages in thread

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-05-30 04:32  Nisha Moond <nisha.moond412@gmail.com>
  parent: Peter Smith <smithpb2250@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: Nisha Moond @ 2026-05-30 04:32 UTC (permalink / raw)
  To: Peter Smith <smithpb2250@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Fri, May 29, 2026 at 1:54 PM Peter Smith <smithpb2250@gmail.com> wrote:
>
> Hi Nisha.
>
> Some review comments for patch v7-0002.
>

Thanks for the review. All comments are addressed in v8. Please find
responses below for a few of the comments.

> ======
> src/bin/pg_dump/t/002_pg_dump.pl
>
> 2.
> + 'CREATE PUBLICATION pub12' => {
> + create_order => 50,
> + create_sql =>
> +   'CREATE PUBLICATION pub12 FOR TABLES IN SCHEMA dump_test EXCEPT
> (TABLE test_table, dump_test.test_second_table);',
> + regexp => qr/^
> + \QCREATE PUBLICATION pub12 WITH (publish = 'insert, update, delete,
> truncate');\E
> + /xm,
> + like => { %full_runs, section_post_data => 1, },
> + },
> +
> + 'ALTER PUBLICATION pub12 ADD TABLES IN SCHEMA dump_test EXCEPT
> (TABLE test_table, dump_test.test_second_table)'
> +   => {
> + regexp => qr/^
> + \QALTER PUBLICATION pub12 ADD TABLES IN SCHEMA dump_test EXCEPT
> (TABLE ONLY test_table, TABLE ONLY test_second_table);\E
> + /xm,
> + like => { %full_runs, section_post_data => 1, },
> +   },
>
> I found those hard to read at first. How about just changing the test
> title of the ALTER parts
>
> BEFORE
> + 'ALTER PUBLICATION pub12 ADD TABLES IN SCHEMA dump_test EXCEPT
> (TABLE test_table, dump_test.test_second_table)'
> SUGGESTION
> + 'CREATE PUBLICATION pub12 test continues ...'
>
> (2 places like this)
>

I don't see any existing "..test continues..." pattern, so I changed it as -
'CREATE PUBLICATION pub11 - ADD TABLES IN SCHEMA EXCEPT dump'

Thoughts?

> ======
> src/test/regress/expected/publication.out
>
> 3.
> +-- DROP TABLES IN SCHEMA also removes associated EXCEPT entries
> +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test;
> +\dRp+ testpub_alter_except
> +                                                       Publication
> testpub_alter_except
> +          Owner           | All tables | All sequences | Inserts |
> Updates | Deletes | Truncates | Generated columns | Via root |
> Description
> +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+-------------
> + regress_publication_user | f          | f             | t       | t
>      | t       | t         | none              | f        |
> +Except tables:
> +    "pub_test.testpub_tbl_s1"
> +
>
> Isn't this showing a BUG, because after the DROP the "Except tables"
> are still listed.
>

DROP handling is part of Patch-0003, so the DROP-related tests belong
there. I had added the test here only to verify the ADD scenarios, but
I agree that it makes the coverage confusing and incorrect in its
current placement.

I’ve now corrected the tests accordingly.

--
Thanks,
Nisha





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-06-01 07:24  Peter Smith <smithpb2250@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  1 sibling, 1 reply; 196+ messages in thread

From: Peter Smith @ 2026-06-01 07:24 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Hi Nisha.

Review comments for v8-0001 and v8-0002.

======
git apply gives warnings.

1.
git apply ../patches_misc/v8-0001-Support-EXCEPT-clause-for-schema-level-publicatio.patch
../patches_misc/v8-0001-Support-EXCEPT-clause-for-schema-level-publicatio.patch:176:
space before tab in indent.
                                         errmsg("relation \"%s\" is
already member of publication \"%s\"",
warning: 1 line adds whitespace errors.

======
src/bin/psql/tab-complete.in.c

On Sat, May 30, 2026 at 2:32 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
>
...
> > 9.
> > BTW, the current code is not able to handle multiple schemas.
> >
> > So, this works:
> > test_pub=# CREATE PUBLICATION pub1 for TABLES IN SCHEMA myschema <TAB>
> > EXCEPT ( TABLE  WITH (
> >
> > but, this doesn't do anything:
> > test_pub=# CREATE PUBLICATION pub1 for TABLES IN SCHEMA public, myschema <TAB>
> >
>
> I think the above preserves the existing behavior. Currently, we do
> not suggest "WITH (" after the second schema onwards. To support this
> properly, we would also need to handle "WITH (" suggestions for
> subsequent schema entries.
>
> I’ve created a top-up patch (patch-002) for this. I can merge it if we
> want to change the current behavior. Let me know your thoughts.

2.
Some scenarios are improved, but others do not work (either newly
broken or maybe they have been?).

TBH, I am unsure if the added complexity of patch 0002 was worth it. I
am going to pass on this for now and wait for other opinions.

e.g.

Good: (suggests schemas to use)
test_pub=# CREATE PUBLICATION pub1 FOR TABLES IN SCHEMA
CURRENT_SCHEMA      information_schema  myschema            public

Bad: (does not suggest more schema to use)
test_pub=# CREATE PUBLICATION pub1 FOR TABLES IN SCHEMA public, <TAB HERE>

Good: (completes names of known schema)
test_pub=# CREATE PUBLICATION pub1 FOR TABLES IN SCHEMA my <TAB HERE>
becomes
test_pub=# CREATE PUBLICATION pub1 FOR TABLES IN SCHEMA myschema

Bad: (does not complete names of known schema)
test_pub=# CREATE PUBLICATION pub1 FOR TABLES IN SCHEMA public, my <TAB HERE>

Good: (suggest EXCEPT with single schema)
test_pub=# CREATE PUBLICATION pub1 FOR TABLES IN SCHEMA myschema
EXCEPT ( TABLE  WITH (

Good: (suggest EXCEPT with multi schema)
test_pub=# CREATE PUBLICATION pub1 for TABLES IN SCHEMA public, myschema
EXCEPT ( TABLE  WITH (

Bad: (doesn't work if the FOR TABLE precedes TABLES IN SCHEMA)
test_pub=# CREATE PUBLICATION pub1 FOR TABLE mytab, TABLES IN <TAB HERE>

======
Kind Regards,
Peter Smith.
Fujitsu Australia





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-06-01 07:26  Peter Smith <smithpb2250@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: Peter Smith @ 2026-06-01 07:26 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Hi Nisha.

Some review comments for patch v8-0003.

======
src/backend/commands/publicationcmds.c

AlterPublicationSchemaExceptTables:

1.
+ /*
+ * EXCEPT is not meaningful with DROP: dropping a schema from a
+ * publication already removes all its except entries via cascade, and
+ * there is no sensible interpretation of "drop only the except entry but
+ * keep the schema".
+ */

Is that backwards? I think you mean :

SUGGESTION
* Dropping a schema from a publication removes all its EXCEPT entries via
* cascade. The concept of "drop all schema tables from the publication EXCEPT
* these ones" is not supported.
======
src/bin/pg_dump/t/002_pg_dump.pl

2.
On Sat, May 30, 2026 at 2:32 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
...
> I don't see any existing "..test continues..." pattern, so I changed it as -
> 'CREATE PUBLICATION pub11 - ADD TABLES IN SCHEMA EXCEPT dump'
>
> Thoughts?

I've since found that there is a way to combine multiple regex within
a single test. Doing it like below is a cleaner way to write these
multi-statement tests.

SUGGESTION (note /xms instead of /xm)
    'CREATE PUBLICATION pub11' => {
        create_order => 50,
        create_sql =>
          'CREATE PUBLICATION pub11 FOR TABLES IN SCHEMA dump_test
EXCEPT (TABLE test_table);',
        regexp => qr/^
            \QCREATE PUBLICATION pub11 WITH (publish = 'insert,
update, delete, truncate');\E
            .*?
            \QALTER PUBLICATION pub11 ADD TABLES IN SCHEMA dump_test
EXCEPT (TABLE ONLY test_table);\E
            /xms,
        like => { %full_runs, section_post_data => 1, },
    },

(ditto for the pub12 test)

======
Kind Regards,
Peter Smith.
Fujitsu Australia





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-06-01 07:28  Peter Smith <smithpb2250@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  1 sibling, 1 reply; 196+ messages in thread

From: Peter Smith @ 2026-06-01 07:28 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Hi Nisha.

Some review comments for patch v8-0004.

======
src/backend/commands/publicationcmds.c

AlterPublicationSchemaExceptTables:

1.
+ /* Collect OIDs of the desired new EXCEPT list. */
+ foreach_ptr(PublicationRelInfo, pri, rels)
+ {
+ newexceptrelids = lappend_oid(newexceptrelids,
+   RelationGetRelid(pri->relation));
+ }

Block braces {} not needed.

~~~

2.
+ if (!OidIsValid(proid))
+ continue; /* already gone */
+
+ ObjectAddressSet(obj, PublicationRelRelationId, proid);
+ performDeletion(&obj, DROP_CASCADE, 0);

SUGGESTION
if (OidIsValid(proid))
{
  ObjectAddressSet(obj, PublicationRelRelationId, proid);
  performDeletion(&obj, DROP_CASCADE, 0);
}

======
src/test/subscription/t/037_except.pl

3.
I think you had used the SQL exactly as I previously suggested, but I
made a mistake:
It should say "SELECT count(*)" instead of "SELECT a".

So it returns either 0 or 1 row.

e.g. #1
$result =
  $node_subscriber->safe_psql('postgres',
    "SELECT count(*) FROM sch1.tab_excluded WHERE a = 7");
is($result, qq(1),
    'ALTER ... SET TABLES IN SCHEMA EXCEPT: newly included table is replicated'
);
$result =
  $node_subscriber->safe_psql('postgres',
    "SELECT count(*) FROM sch1.tab_published WHERE a = 7");
is($result, qq(0),
    'ALTER ... SET TABLES IN SCHEMA EXCEPT: now-excluded table is not
replicated'
);

e.g. #2
$result =
  $node_subscriber->safe_psql('postgres',
    "SELECT count(*) FROM sch1.tab_published WHERE a = 8");
is($result, qq(1),
    'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_published
replicated after except list cleared'
);
$result =
  $node_subscriber->safe_psql('postgres',
    "SELECT count(*) FROM sch1.tab_excluded WHERE a = 8");
is($result, qq(1),
    'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_excluded
replicated after except list cleared'
);

======
Kind Regards,
Peter Smith.
Fujitsu Australia





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-06-02 08:56  Nisha Moond <nisha.moond412@gmail.com>
  parent: Peter Smith <smithpb2250@gmail.com>
  0 siblings, 0 replies; 196+ messages in thread

From: Nisha Moond @ 2026-06-02 08:56 UTC (permalink / raw)
  To: Peter Smith <smithpb2250@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Mon, Jun 1, 2026 at 12:54 PM Peter Smith <smithpb2250@gmail.com> wrote:
>
> Hi Nisha.
>
> Review comments for v8-0001 and v8-0002.
>

Thanks for the review.

> ======
> git apply gives warnings.
>
> 1.
> git apply ../patches_misc/v8-0001-Support-EXCEPT-clause-for-schema-level-publicatio.patch
> ../patches_misc/v8-0001-Support-EXCEPT-clause-for-schema-level-publicatio.patch:176:
> space before tab in indent.
>                                          errmsg("relation \"%s\" is
> already member of publication \"%s\"",
> warning: 1 line adds whitespace errors.
>
> ======
> src/bin/psql/tab-complete.in.c
>
> On Sat, May 30, 2026 at 2:32 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
> >
> ...
> > > 9.
> > > BTW, the current code is not able to handle multiple schemas.
> > >
> > > So, this works:
> > > test_pub=# CREATE PUBLICATION pub1 for TABLES IN SCHEMA myschema <TAB>
> > > EXCEPT ( TABLE  WITH (
> > >
> > > but, this doesn't do anything:
> > > test_pub=# CREATE PUBLICATION pub1 for TABLES IN SCHEMA public, myschema <TAB>
> > >
> >
> > I think the above preserves the existing behavior. Currently, we do
> > not suggest "WITH (" after the second schema onwards. To support this
> > properly, we would also need to handle "WITH (" suggestions for
> > subsequent schema entries.
> >
> > I’ve created a top-up patch (patch-002) for this. I can merge it if we
> > want to change the current behavior. Let me know your thoughts.
>
> 2.
> Some scenarios are improved, but others do not work (either newly
> broken or maybe they have been?).
>

I tested these scenarios on HEAD (without this patch), and most of
them already exist today. (See inline below).

> TBH, I am unsure if the added complexity of patch 0002 was worth it. I
> am going to pass on this for now and wait for other opinions.
>
> e.g.
>
> Good: (suggests schemas to use)
> test_pub=# CREATE PUBLICATION pub1 FOR TABLES IN SCHEMA
> CURRENT_SCHEMA      information_schema  myschema            public
>

Not introduced by this patch; it is existing behavior.

> Bad: (does not suggest more schema to use)
> test_pub=# CREATE PUBLICATION pub1 FOR TABLES IN SCHEMA public, <TAB HERE>
>

Not introduced by this patch; it is existing behavior.

> Good: (completes names of known schema)
> test_pub=# CREATE PUBLICATION pub1 FOR TABLES IN SCHEMA my <TAB HERE>
> becomes
> test_pub=# CREATE PUBLICATION pub1 FOR TABLES IN SCHEMA myschema
>

Not introduced by this patch; it is existing behavior.

> Bad: (does not complete names of known schema)
> test_pub=# CREATE PUBLICATION pub1 FOR TABLES IN SCHEMA public, my <TAB HERE>
>

Not introduced by this patch; it is existing behavior.

> Good: (suggest EXCEPT with single schema)
> test_pub=# CREATE PUBLICATION pub1 FOR TABLES IN SCHEMA myschema
> EXCEPT ( TABLE  WITH (
>

This behavior is introduced by v8-0001.

> Good: (suggest EXCEPT with multi schema)
> test_pub=# CREATE PUBLICATION pub1 for TABLES IN SCHEMA public, myschema
> EXCEPT ( TABLE  WITH (
>

This behavior is introduced by v8-0002.

> Bad: (doesn't work if the FOR TABLE precedes TABLES IN SCHEMA)
> test_pub=# CREATE PUBLICATION pub1 FOR TABLE mytab, TABLES IN <TAB HERE>

Not introduced by this patch; it is existing behavior.
~~~

All of the above behavior is consistent with HEAD. Only the "EXCEPT
(TABLE" suggestions are introduced by patches 0001 and 0002.

I'm also not sure the added complexity is justified just for the
"EXCEPT (TABLE" suggestion, especially since suggestions after commas
are generally not supported in most existing cases.
I'll drop patch-0002 for now and we can revisit it later if others
have opinions on it.

--
Thanks,
Nisha





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-06-02 08:56  Nisha Moond <nisha.moond412@gmail.com>
  parent: Peter Smith <smithpb2250@gmail.com>
  0 siblings, 0 replies; 196+ messages in thread

From: Nisha Moond @ 2026-06-02 08:56 UTC (permalink / raw)
  To: Peter Smith <smithpb2250@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Mon, Jun 1, 2026 at 12:56 PM Peter Smith <smithpb2250@gmail.com> wrote:
>
> Hi Nisha.
>
> Some review comments for patch v8-0003.
>

Thanks for the

> ======
> src/backend/commands/publicationcmds.c
>
> AlterPublicationSchemaExceptTables:
>
> 1.
> + /*
> + * EXCEPT is not meaningful with DROP: dropping a schema from a
> + * publication already removes all its except entries via cascade, and
> + * there is no sensible interpretation of "drop only the except entry but
> + * keep the schema".
> + */
>
> Is that backwards? I think you mean :
>
> SUGGESTION
> * Dropping a schema from a publication removes all its EXCEPT entries via
> * cascade. The concept of "drop all schema tables from the publication EXCEPT
> * these ones" is not supported.

Fixed as suggested in v9.

> ======
> src/bin/pg_dump/t/002_pg_dump.pl
>
> 2.
> On Sat, May 30, 2026 at 2:32 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
> ...
> > I don't see any existing "..test continues..." pattern, so I changed it as -
> > 'CREATE PUBLICATION pub11 - ADD TABLES IN SCHEMA EXCEPT dump'
> >
> > Thoughts?
>
> I've since found that there is a way to combine multiple regex within
> a single test. Doing it like below is a cleaner way to write these
> multi-statement tests.
>
> SUGGESTION (note /xms instead of /xm)
>     'CREATE PUBLICATION pub11' => {
>         create_order => 50,
>         create_sql =>
>           'CREATE PUBLICATION pub11 FOR TABLES IN SCHEMA dump_test
> EXCEPT (TABLE test_table);',
>         regexp => qr/^
>             \QCREATE PUBLICATION pub11 WITH (publish = 'insert,
> update, delete, truncate');\E
>             .*?
>             \QALTER PUBLICATION pub11 ADD TABLES IN SCHEMA dump_test
> EXCEPT (TABLE ONLY test_table);\E
>             /xms,
>         like => { %full_runs, section_post_data => 1, },
>     },
>
> (ditto for the pub12 test)
>

Thanks for the suggestion. I've updated the test accordingly in v9.

--
Thanks,
Nisha





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-06-02 08:57  Nisha Moond <nisha.moond412@gmail.com>
  parent: Peter Smith <smithpb2250@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: Nisha Moond @ 2026-06-02 08:57 UTC (permalink / raw)
  To: Peter Smith <smithpb2250@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Mon, Jun 1, 2026 at 12:59 PM Peter Smith <smithpb2250@gmail.com> wrote:
>
> Hi Nisha.
>
> Some review comments for patch v8-0004.
>

Thanks for the review.

> ======
> src/backend/commands/publicationcmds.c
>
> AlterPublicationSchemaExceptTables:
>
> 1.
> + /* Collect OIDs of the desired new EXCEPT list. */
> + foreach_ptr(PublicationRelInfo, pri, rels)
> + {
> + newexceptrelids = lappend_oid(newexceptrelids,
> +   RelationGetRelid(pri->relation));
> + }
>
> Block braces {} not needed.
>

Fixed.

> ~~~
>
> 2.
> + if (!OidIsValid(proid))
> + continue; /* already gone */
> +
> + ObjectAddressSet(obj, PublicationRelRelationId, proid);
> + performDeletion(&obj, DROP_CASCADE, 0);
>
> SUGGESTION
> if (OidIsValid(proid))
> {
>   ObjectAddressSet(obj, PublicationRelRelationId, proid);
>   performDeletion(&obj, DROP_CASCADE, 0);
> }
>

Fixed. A similar pattern was also used in PublicationDropSchemas(),
and I have fixed that as well.

> ======
> src/test/subscription/t/037_except.pl
>
> 3.
> I think you had used the SQL exactly as I previously suggested, but I
> made a mistake:
> It should say "SELECT count(*)" instead of "SELECT a".
>
> So it returns either 0 or 1 row.
>
> e.g. #1
> $result =
>   $node_subscriber->safe_psql('postgres',
>     "SELECT count(*) FROM sch1.tab_excluded WHERE a = 7");
> is($result, qq(1),
>     'ALTER ... SET TABLES IN SCHEMA EXCEPT: newly included table is replicated'
> );
> $result =
>   $node_subscriber->safe_psql('postgres',
>     "SELECT count(*) FROM sch1.tab_published WHERE a = 7");
> is($result, qq(0),
>     'ALTER ... SET TABLES IN SCHEMA EXCEPT: now-excluded table is not
> replicated'
> );
>
> e.g. #2
> $result =
>   $node_subscriber->safe_psql('postgres',
>     "SELECT count(*) FROM sch1.tab_published WHERE a = 8");
> is($result, qq(1),
>     'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_published
> replicated after except list cleared'
> );
> $result =
>   $node_subscriber->safe_psql('postgres',
>     "SELECT count(*) FROM sch1.tab_excluded WHERE a = 8");
> is($result, qq(1),
>     'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_excluded
> replicated after except list cleared'
> );
>

Thanks for pointing that out; I overlooked your earlier suggestion.
I've now updated as suggested.

Attached is the updated v9 patch set.

--
Thanks,
Nisha

Attachments: download all (3 files, .tar.gz)

v9-0001-Support-EXCEPT-clause-for-schema-level-publicatio.patch (application/octet-stream, 46.8K) download From aee9ed557c233af906a559c2e30a4ae3f2960e66 Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Mon, 4 May 2026 12:49:27 +0530 Subject: [PATCH v9 1/3] Support EXCEPT clause for schema-level publications Extend table exclusion support in publications to allow specific tables to be excluded from schema-level publications using an EXCEPT clause in CREATE PUBLICATION. Supported syntax: CREATE PUBLICATION <pub> FOR TABLES IN SCHEMA s EXCEPT (TABLE t1,...); --- doc/src/sgml/logical-replication.sgml | 3 +- doc/src/sgml/ref/create_publication.sgml | 22 +++- src/backend/catalog/pg_publication.c | 102 ++++++++++++--- src/backend/commands/publicationcmds.c | 65 ++++++++-- src/backend/parser/gram.y | 52 +++++++- src/backend/replication/pgoutput/pgoutput.c | 30 ++++- src/bin/psql/describe.c | 18 +++ src/bin/psql/tab-complete.in.c | 24 +++- src/include/catalog/pg_publication.h | 3 +- src/include/nodes/parsenodes.h | 2 + src/test/regress/expected/publication.out | 104 ++++++++++++++- src/test/regress/sql/publication.sql | 69 +++++++++- src/test/subscription/t/037_except.pl | 133 +++++++++++++++++++- 13 files changed, 579 insertions(+), 48 deletions(-) diff --git a/doc/src/sgml/logical-replication.sgml b/doc/src/sgml/logical-replication.sgml index 9e7868487de..1433d2660fe 100644 --- a/doc/src/sgml/logical-replication.sgml +++ b/doc/src/sgml/logical-replication.sgml @@ -117,7 +117,8 @@ or <literal>FOR ALL SEQUENCES</literal>. Unlike tables, sequences can be synchronized at any time. For more information, see <xref linkend="logical-replication-sequences"/>. When a publication is - created with <literal>FOR ALL TABLES</literal>, a table or set of tables can + created with <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal>, a table or set of tables can be explicitly excluded from publication using the <link linkend="sql-createpublication-params-for-except-table"><literal>EXCEPT</literal></link> clause. diff --git a/doc/src/sgml/ref/create_publication.sgml b/doc/src/sgml/ref/create_publication.sgml index f82d640e6ca..7fa0bd11f7b 100644 --- a/doc/src/sgml/ref/create_publication.sgml +++ b/doc/src/sgml/ref/create_publication.sgml @@ -28,7 +28,7 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA <replaceable class="parameter">tables_in_schema</replaceable> [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -39,6 +39,10 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <replaceable class="parameter">table_object</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] [ WHERE ( <replaceable class="parameter">expression</replaceable> ) ] +<phrase>and <replaceable class="parameter">tables_in_schema</replaceable> is:</phrase> + + { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] + <phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> TABLE <replaceable class="parameter">table_object</replaceable> [, ... ] @@ -142,6 +146,8 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <para> Marks the publication as one that replicates changes for all tables in the specified list of schemas, including tables created in the future. + Tables listed in the <literal>EXCEPT</literal> clause for a given schema + are excluded from the publication. </para> <para> @@ -173,7 +179,7 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <para> Marks the publication as one that replicates changes for all tables in the database, including tables created in the future. Tables listed in - <literal>EXCEPT</literal> clause are excluded from the publication. + the <literal>EXCEPT</literal> clause are excluded from the publication. </para> </listitem> </varlistentry> @@ -198,7 +204,8 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <listitem> <para> This clause specifies a list of tables to be excluded from the - publication. + publication. It can be used with <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal>. </para> <para> For inherited tables, if <literal>ONLY</literal> is specified before the @@ -515,6 +522,15 @@ CREATE PUBLICATION production_publication FOR TABLE users, departments, TABLES I CREATE PUBLICATION sales_publication FOR TABLES IN SCHEMA marketing, sales; </programlisting></para> + <para> + Create a publication that publishes all changes for all the tables present in + the schema <structname>sales</structname>, except + <structname>internal</structname> and <structname>drafts</structname>: +<programlisting> +CREATE PUBLICATION sales_filtered FOR TABLES IN SCHEMA sales EXCEPT (TABLE internal, drafts); +</programlisting> + </para> + <para> Create a publication that publishes all changes for table <structname>users</structname>, but replicates only columns <structname>user_id</structname> and diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index 5c457d9aca8..3437a878f74 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -444,13 +444,19 @@ GetPubPartitionOptionRelations(List *result, PublicationPartOpt pub_partopt, * * Note that the list of ancestors should be ordered such that the topmost * ancestor is at the end of the list. + * + * except_pubids is a list of publication OIDs whose schema membership + * should be ignored for the ancestor (because the ancestor is in their + * EXCEPT clause). */ Oid -GetTopMostAncestorInPublication(Oid puboid, List *ancestors, int *ancestor_level) +GetTopMostAncestorInPublication(Oid puboid, List *ancestors, + int *ancestor_level, List *except_pubids) { ListCell *lc; Oid topmost_relid = InvalidOid; int level = 0; + bool check_schemas = !list_member_oid(except_pubids, puboid); /* * Find the "topmost" ancestor that is in this publication. @@ -470,7 +476,7 @@ GetTopMostAncestorInPublication(Oid puboid, List *ancestors, int *ancestor_level if (ancestor_level) *ancestor_level = level; } - else + else if (check_schemas) { aschemaPubids = GetSchemaPublications(get_rel_namespace(ancestor)); if (list_member_oid(aschemaPubids, puboid)) @@ -545,18 +551,30 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, * duplicates, it's here just to provide nicer error message in common * case. The real protection is the unique key on the catalog. */ - if (SearchSysCacheExists2(PUBLICATIONRELMAP, ObjectIdGetDatum(relid), - ObjectIdGetDatum(pubid))) + tup = SearchSysCache2(PUBLICATIONRELMAP, ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + + if (HeapTupleIsValid(tup)) { + bool is_except = ((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept; + + ReleaseSysCache(tup); table_close(rel, RowExclusiveLock); if (if_not_exists) return InvalidObjectAddress; - ereport(ERROR, - (errcode(ERRCODE_DUPLICATE_OBJECT), - errmsg("relation \"%s\" is already member of publication \"%s\"", - RelationGetRelationName(targetrel), pub->name))); + if (is_except) + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("table \"%s\" cannot be added because it is excluded from publication \"%s\"", + RelationGetQualifiedRelationName(targetrel), + pub->name))); + else + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("relation \"%s\" is already member of publication \"%s\"", + RelationGetRelationName(targetrel), pub->name))); } check_publication_add_relation(pri); @@ -982,12 +1000,13 @@ GetIncludedPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) * Gets list of table oids that were specified in the EXCEPT clause for a * publication. * - * This should only be used FOR ALL TABLES publications. + * This is used for FOR ALL TABLES and FOR TABLES IN SCHEMA publications, + * both of which support EXCEPT TABLE. */ List * GetExcludedPublicationTables(Oid pubid, PublicationPartOpt pub_partopt) { - Assert(GetPublication(pubid)->alltables); + Assert(GetPublication(pubid)->alltables || is_schema_publication(pubid)); return get_publication_relations(pubid, pub_partopt, true); } @@ -1049,15 +1068,15 @@ GetAllPublicationRelations(Oid pubid, char relkind, bool pubviaroot) TableScanDesc scan; HeapTuple tuple; List *result = NIL; - List *exceptlist = NIL; + List *except_relids = NIL; Assert(!(relkind == RELKIND_SEQUENCE && pubviaroot)); /* EXCEPT filtering applies only to relations, not sequences */ if (relkind == RELKIND_RELATION) - exceptlist = GetExcludedPublicationTables(pubid, pubviaroot ? - PUBLICATION_PART_ROOT : - PUBLICATION_PART_LEAF); + except_relids = GetExcludedPublicationTables(pubid, pubviaroot ? + PUBLICATION_PART_ROOT : + PUBLICATION_PART_LEAF); classRel = table_open(RelationRelationId, AccessShareLock); @@ -1075,7 +1094,7 @@ GetAllPublicationRelations(Oid pubid, char relkind, bool pubviaroot) if (is_publishable_class(relid, relForm) && !(relForm->relispartition && pubviaroot) && - !list_member_oid(exceptlist, relid)) + !list_member_oid(except_relids, relid)) result = lappend_oid(result, relid); } @@ -1097,7 +1116,7 @@ GetAllPublicationRelations(Oid pubid, char relkind, bool pubviaroot) if (is_publishable_class(relid, relForm) && !relForm->relispartition && - !list_member_oid(exceptlist, relid)) + !list_member_oid(except_relids, relid)) result = lappend_oid(result, relid); } @@ -1232,22 +1251,67 @@ GetSchemaPublicationRelations(Oid schemaid, PublicationPartOpt pub_partopt) /* * Gets the list of all relations published by FOR TABLES IN SCHEMA - * publication. + * publication, excluding any tables listed in the EXCEPT clause. */ List * GetAllSchemaPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) { List *result = NIL; List *pubschemalist = GetPublicationSchemas(pubid); + List *except_relids = NIL; ListCell *cell; + /* get the list of tables excluded via EXCEPT TABLE for this publication */ + if (pubschemalist != NIL) + except_relids = GetExcludedPublicationTables(pubid, pub_partopt); + foreach(cell, pubschemalist) { Oid schemaid = lfirst_oid(cell); List *schemaRels = NIL; schemaRels = GetSchemaPublicationRelations(schemaid, pub_partopt); - result = list_concat(result, schemaRels); + + if (except_relids != NIL) + { + /* filter out any tables that appear in the EXCEPT list */ + ListCell *rlc; + + foreach(rlc, schemaRels) + { + Oid relid = lfirst_oid(rlc); + bool excluded = list_member_oid(except_relids, relid); + + /* + * Also exclude any relation whose partition ancestor is in + * the EXCEPT list. This matters when pub_partopt is + * PUBLICATION_PART_ROOT: the except list holds only the root + * OID, but the schema scan may also return individual + * partition relations that live in the same schema. + */ + if (!excluded && get_rel_relispartition(relid)) + { + List *ancestors = get_partition_ancestors(relid); + ListCell *alc; + + foreach(alc, ancestors) + { + if (list_member_oid(except_relids, lfirst_oid(alc))) + { + excluded = true; + break; + } + } + list_free(ancestors); + } + + if (!excluded) + result = lappend_oid(result, relid); + } + list_free(schemaRels); + } + else + result = list_concat(result, schemaRels); } return result; @@ -1381,7 +1445,7 @@ is_table_publishable_in_publication(Oid relid, Publication *pub) * the publication, it should be included (return true). */ if (relispartition && - OidIsValid(GetTopMostAncestorInPublication(pub->oid, ancestors, NULL))) + OidIsValid(GetTopMostAncestorInPublication(pub->oid, ancestors, NULL, NIL))) return !pub->pubviaroot; /* diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 440adb356ad..cd39d6375cd 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -181,7 +181,7 @@ parse_publication_options(ParseState *pstate, */ static void ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, - List **rels, List **exceptrels, List **schemas) + List **rels, List **except_pubtables, List **schemas) { ListCell *cell; PublicationObjSpec *pubobj; @@ -200,7 +200,7 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, { case PUBLICATIONOBJ_EXCEPT_TABLE: pubobj->pubtable->except = true; - *exceptrels = lappend(*exceptrels, pubobj->pubtable); + *except_pubtables = lappend(*except_pubtables, pubobj->pubtable); break; case PUBLICATIONOBJ_TABLE: pubobj->pubtable->except = false; @@ -305,7 +305,7 @@ pub_rf_contains_invalid_column(Oid pubid, Relation relation, List *ancestors, if (pubviaroot && relation->rd_rel->relispartition) { publish_as_relid - = GetTopMostAncestorInPublication(pubid, ancestors, NULL); + = GetTopMostAncestorInPublication(pubid, ancestors, NULL, NIL); if (!OidIsValid(publish_as_relid)) publish_as_relid = relid; @@ -389,7 +389,7 @@ pub_contains_invalid_column(Oid pubid, Relation relation, List *ancestors, */ if (pubviaroot && relation->rd_rel->relispartition) { - publish_as_relid = GetTopMostAncestorInPublication(pubid, ancestors, NULL); + publish_as_relid = GetTopMostAncestorInPublication(pubid, ancestors, NULL, NIL); if (!OidIsValid(publish_as_relid)) publish_as_relid = relid; @@ -849,7 +849,7 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) char publish_generated_columns; AclResult aclresult; List *relations = NIL; - List *exceptrelations = NIL; + List *except_pubtables = NIL; List *schemaidlist = NIL; /* must have CREATE privilege on database */ @@ -936,16 +936,16 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) /* Associate objects with the publication. */ ObjectsInPublicationToOids(stmt->pubobjects, pstate, &relations, - &exceptrelations, &schemaidlist); + &except_pubtables, &schemaidlist); if (stmt->for_all_tables) { /* Process EXCEPT table list */ - if (exceptrelations != NIL) + if (except_pubtables != NIL) { List *rels; - rels = OpenTableList(exceptrelations); + rels = OpenTableList(except_pubtables); PublicationAddTables(puboid, rels, true, NULL); CloseTableList(rels); } @@ -959,6 +959,8 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) } else if (!stmt->for_all_sequences) { + List *explicitrelids = NIL; + /* FOR TABLES IN SCHEMA requires superuser */ if (schemaidlist != NIL && !superuser()) ereport(ERROR, @@ -977,6 +979,19 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) schemaidlist != NIL, publish_via_partition_root); + /* + * Collect explicit table OIDs now, before we close the relation + * list, so that except-table validation below can check for + * contradictions without relying on a catalog scan that might not + * yet see the just-inserted rows. + */ + if (except_pubtables != NIL) + { + foreach_ptr(PublicationRelInfo, pri, rels) + explicitrelids = lappend_oid(explicitrelids, + RelationGetRelid(pri->relation)); + } + PublicationAddTables(puboid, rels, true, NULL); CloseTableList(rels); } @@ -989,6 +1004,34 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) */ LockSchemaList(schemaidlist); PublicationAddSchemas(puboid, schemaidlist, true, NULL); + + if (except_pubtables != NIL) + { + List *except_rels; + + except_rels = OpenTableList(except_pubtables); + + /* + * Validate that each excluded table is not also in the + * explicit table list (which would be contradictory). Use the + * in-memory explicitrelids collected above rather than + * re-reading the catalog, which may not yet see the + * just-inserted rows. + */ + foreach_ptr(PublicationRelInfo, pri, except_rels) + { + Oid except_relid = RelationGetRelid(pri->relation); + + if (list_member_oid(explicitrelids, except_relid)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" cannot appear in both the table list and the EXCEPT clause", + RelationGetQualifiedRelationName(pri->relation))); + } + + PublicationAddTables(puboid, except_rels, true, NULL); + CloseTableList(except_rels); + } } } @@ -1683,12 +1726,12 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) else { List *relations = NIL; - List *exceptrelations = NIL; + List *except_pubtables = NIL; List *schemaidlist = NIL; Oid pubid = pubform->oid; ObjectsInPublicationToOids(stmt->pubobjects, pstate, &relations, - &exceptrelations, &schemaidlist); + &except_pubtables, &schemaidlist); CheckAlterPublication(stmt, tup, relations, schemaidlist); @@ -1711,7 +1754,7 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) errmsg("publication \"%s\" does not exist", stmt->pubname)); - relations = list_concat(relations, exceptrelations); + relations = list_concat(relations, except_pubtables); AlterPublicationTables(stmt, tup, relations, pstate->p_sourcetext, schemaidlist != NIL); AlterPublicationSchemas(stmt, tup, schemaidlist); diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y index ff4e1388c55..4514ef7f9c2 100644 --- a/src/backend/parser/gram.y +++ b/src/backend/parser/gram.y @@ -58,6 +58,7 @@ #include "nodes/makefuncs.h" #include "nodes/nodeFuncs.h" #include "parser/parser.h" +#include "utils/builtins.h" #include "utils/datetime.h" #include "utils/xml.h" @@ -11272,7 +11273,7 @@ AlterOwnerStmt: ALTER AGGREGATE aggregate_with_argtypes OWNER TO RoleSpec * pub_obj is one of: * * TABLE table [, ...] - * TABLES IN SCHEMA schema [, ...] + * TABLES IN SCHEMA schema [EXCEPT (TABLE table [, ...] )] [, ...] * *****************************************************************************/ @@ -11332,23 +11333,26 @@ PublicationObjSpec: $$->pubtable->columns = $3; $$->pubtable->whereClause = $4; } - | TABLES IN_P SCHEMA ColId + | TABLES IN_P SCHEMA ColId opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_SCHEMA; $$->name = $4; + $$->except_tables = $5; $$->location = @4; } - | TABLES IN_P SCHEMA CURRENT_SCHEMA + | TABLES IN_P SCHEMA CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_CUR_SCHEMA; + $$->except_tables = $5; $$->location = @4; } - | ColId opt_column_list OptWhereClause + | ColId opt_column_list OptWhereClause opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $4; /* * If either a row filter or column list is specified, create * a PublicationTable object. @@ -11392,10 +11396,11 @@ PublicationObjSpec: $$->pubtable->columns = $2; $$->pubtable->whereClause = $3; } - | CURRENT_SCHEMA + | CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $2; $$->location = @1; } ; @@ -20784,6 +20789,8 @@ preprocess_pub_all_objtype_list(List *all_objects_list, List **pubobjects, /* * Process pubobjspec_list to check for errors in any of the objects and * convert PUBLICATIONOBJ_CONTINUATION into appropriate PublicationObjSpecType. + * Also flattens except_tables from TABLES IN SCHEMA nodes into the list so + * that ObjectsInPublicationToOids() sees them as top-level EXCEPT_TABLE entries. */ static void preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) @@ -20812,6 +20819,13 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLE) { + /* EXCEPT is not valid for table objects */ + if (pubobj->except_tables != NIL) + ereport(ERROR, + errcode(ERRCODE_SYNTAX_ERROR), + errmsg("EXCEPT is not allowed for TABLE publication objects"), + parser_errposition(pubobj->location)); + /* relation name or pubtable must be set for this type of object */ if (!pubobj->name && !pubobj->pubtable) ereport(ERROR, @@ -20860,6 +20874,34 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) errcode(ERRCODE_SYNTAX_ERROR), errmsg("invalid schema name"), parser_errposition(pubobj->location)); + + /* Flatten EXCEPT entries into the top-level list */ + foreach_ptr(PublicationObjSpec, eobj, pubobj->except_tables) + { + /* + * Unqualified names are implicitly qualified with the parent + * schema. Qualified names must match the parent schema — + * each EXCEPT clause is bound to exactly one schema, so + * cross-schema entries are rejected at parse time. + */ + if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLES_IN_SCHEMA) + { + const char *eobj_schemaname = eobj->pubtable->relation->schemaname; + const char *eobj_relname = eobj->pubtable->relation->relname; + + if (eobj_schemaname == NULL) + eobj->pubtable->relation->schemaname = pubobj->name; + else if (strcmp(eobj_schemaname, pubobj->name) != 0) + ereport(ERROR, + errcode(ERRCODE_SYNTAX_ERROR), + errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", + quote_qualified_identifier(eobj_schemaname, eobj_relname), + pubobj->name), + parser_errposition(eobj->location)); + } + } + pubobjspec_list = list_concat(pubobjspec_list, pubobj->except_tables); + pubobj->except_tables = NIL; } prevobjtype = pubobj->pubobjtype; diff --git a/src/backend/replication/pgoutput/pgoutput.c b/src/backend/replication/pgoutput/pgoutput.c index 4ecfcbff7ab..7ee84ec1c83 100644 --- a/src/backend/replication/pgoutput/pgoutput.c +++ b/src/backend/replication/pgoutput/pgoutput.c @@ -2097,6 +2097,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) * are absorbed while decoding WAL. */ List *schemaPubids = GetSchemaPublications(schemaId); + List *except_pubids; ListCell *lc; Oid publish_as_relid = relid; int publish_ancestor_level = 0; @@ -2104,6 +2105,28 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) char relkind = get_rel_relkind(relid); List *rel_publications = NIL; + /* + * For the schema EXCEPT check, we must look up the top-most ancestor + * rather than the relation itself. check_publication_add_relation() + * prevents individual partitions from appearing in the EXCEPT clause, + * so only a root (non-partition) table can have prexcept = true. + * Using the partition's own OID would always return NIL and miss the + * exclusion. + */ + Oid root_relid; + + if (am_partition) + { + List *ancestors = get_partition_ancestors(relid); + + root_relid = llast_oid(ancestors); + list_free(ancestors); + } + else + root_relid = relid; + + except_pubids = GetRelationExcludedPublications(root_relid); + /* Reload publications if needed before use. */ if (!publications_valid) { @@ -2267,7 +2290,8 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) ancestor = GetTopMostAncestorInPublication(pub->oid, ancestors, - &level); + &level, + except_pubids); if (ancestor != InvalidOid) { @@ -2281,7 +2305,8 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) } if (list_member_oid(pubids, pub->oid) || - list_member_oid(schemaPubids, pub->oid) || + (list_member_oid(schemaPubids, pub->oid) && + !list_member_oid(except_pubids, pub->oid)) || ancestor_published) publish = true; } @@ -2360,6 +2385,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) list_free(pubids); list_free(schemaPubids); + list_free(except_pubids); list_free(rel_publications); entry->replicate_valid = true; diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c index e1449654f96..e5b1a70e05e 100644 --- a/src/bin/psql/describe.c +++ b/src/bin/psql/describe.c @@ -7038,6 +7038,24 @@ describePublications(const char *pattern) if (!addFooterToPublicationDesc(&buf, _("Tables from schemas:"), true, &cont)) goto error_return; + + if (pset.sversion >= 190000) + { + /* + * Get tables in the EXCEPT clause for this schema + * publication. + */ + printfPQExpBuffer(&buf, + "SELECT concat(c.relnamespace::regnamespace, '.', c.relname)\n" + "FROM pg_catalog.pg_class c\n" + " JOIN pg_catalog.pg_publication_rel pr ON c.oid = pr.prrelid\n" + "WHERE pr.prpubid = '%s'\n" + " AND pr.prexcept\n" + "ORDER BY 1", pubid); + if (!addFooterToPublicationDesc(&buf, _("Except tables:"), + true, &cont)) + goto error_return; + } } } else diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index de547a8cb37..fe11dc619ac 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -1065,6 +1065,15 @@ static const SchemaQuery Query_for_trigger_of_table = { "SELECT nspname FROM pg_catalog.pg_namespace "\ " WHERE nspname LIKE '%s'" +#define Query_for_list_of_tables_in_schema \ +"SELECT n.nspname || '.' || c.relname "\ +" FROM pg_catalog.pg_class c "\ +" JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "\ +" WHERE c.relkind IN (" CppAsString2(RELKIND_RELATION) ", " \ + CppAsString2(RELKIND_PARTITIONED_TABLE) ") "\ +" AND (n.nspname || '.' || c.relname) LIKE '%s' "\ +" AND n.nspname = '%s'" + /* Use COMPLETE_WITH_QUERY_VERBATIM with these queries for GUC names: */ #define Query_for_list_of_alter_system_set_vars \ "SELECT pg_catalog.lower(name) FROM pg_catalog.pg_settings "\ @@ -3787,8 +3796,19 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); - else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && (!ends_with(prev_wd, ','))) - COMPLETE_WITH("WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE", "WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* Complete "CREATE PUBLICATION <name> [...] WITH" */ else if (Matches("CREATE", "PUBLICATION", MatchAnyN, "WITH", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/include/catalog/pg_publication.h b/src/include/catalog/pg_publication.h index 89b4bb14f62..53e3d7c6f3d 100644 --- a/src/include/catalog/pg_publication.h +++ b/src/include/catalog/pg_publication.h @@ -191,7 +191,8 @@ extern List *GetPubPartitionOptionRelations(List *result, PublicationPartOpt pub_partopt, Oid relid); extern Oid GetTopMostAncestorInPublication(Oid puboid, List *ancestors, - int *ancestor_level); + int *ancestor_level, + List *except_pubids); extern bool is_publishable_relation(Relation rel); extern bool is_schema_publication(Oid pubid); diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h index 91377a6cde3..98a03c0eeda 100644 --- a/src/include/nodes/parsenodes.h +++ b/src/include/nodes/parsenodes.h @@ -4493,6 +4493,8 @@ typedef struct PublicationObjSpec PublicationObjSpecType pubobjtype; /* type of this publication object */ char *name; PublicationTable *pubtable; + List *except_tables; /* tables specified in the EXCEPT clause (for + * TABLES IN SCHEMA) */ ParseLoc location; /* token location, or -1 if unknown */ } PublicationObjSpec; diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 29e54b214a0..008c6cebaca 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -270,6 +270,12 @@ CREATE PUBLICATION testpub_foralltables_excepttable2 FOR ALL TABLES EXCEPT (test ERROR: syntax error at or near "testpub_tbl1" LINE 1: ..._foralltables_excepttable2 FOR ALL TABLES EXCEPT (testpub_tb... ^ +-- fail - EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testpub_tbl3); +ERROR: EXCEPT is not allowed for TABLE publication objects +LINE 2: FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testp... + ^ --------------------------------------------- -- SET ALL TABLES/SEQUENCES --------------------------------------------- @@ -470,7 +476,103 @@ HINT: Change the publication's EXCEPT clause using ALTER PUBLICATION ... SET AL RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Create same-named tables in public to verify unqualified EXCEPT entries +-- are qualified with the named schema, not public +CREATE TABLE testpub_nopk (foo int, bar int); +CREATE TABLE testpub_tbl_s1 (a int primary key, b text); +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + Publication testpub_schema_except1 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- Exclude multiple tables using unqualified names; same-named tables exist in +-- public to confirm unqualified names resolve to pub_test, not public +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + Publication testpub_schema_except2 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_nopk" + "pub_test.testpub_tbl_s1" + +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testp... + ^ +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); +ERROR: table "pub_test.testpub_tbl_s1" in EXCEPT clause does not belong to schema "public" +LINE 2: ...R TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.t... + ^ +-- Multiple schemas each with their own EXCEPT clause +CREATE PUBLICATION testpub_schema_except_multi + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_schema_except_multi + Publication testpub_schema_except_multi + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- fail: table appears in both the explicit table list and the EXCEPT clause +CREATE PUBLICATION testpub_except_conflict + FOR TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot appear in both the table list and the EXCEPT clause +-- fail: nonexistent table in EXCEPT clause +CREATE PUBLICATION testpub_except_norel + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- fail: partition cannot appear in EXCEPT clause; only root tables are allowed +CREATE TABLE pub_test.testpub_parted_s (a int) PARTITION BY LIST (a); +CREATE TABLE pub_test.testpub_part_s PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (1); +CREATE PUBLICATION testpub_except_partition + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); +ERROR: cannot specify relation "pub_test.testpub_part_s" in the publication EXCEPT clause +DETAIL: This operation is not supported for individual partitions. +-- fail: TABLE keyword is required for the first entry in the EXCEPT clause +CREATE PUBLICATION testpub_except_nokw + FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +ERROR: syntax error at or near "testpub_nopk" +LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + ^ +-- Cleanup +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP TABLE pub_test.testpub_parted_s CASCADE; +DROP TABLE testpub_nopk, testpub_tbl_s1; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +--------------------------------------------- +-- Tests for publications with SEQUENCES +--------------------------------------------- CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; -- FOR ALL SEQUENCES diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 041e14a4de6..9162d4d15a5 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -123,6 +123,9 @@ CREATE PUBLICATION testpub_foralltables_excepttable1 FOR ALL TABLES EXCEPT (TABL \d testpub_tbl1 -- fail - first table in the EXCEPT list should use TABLE keyword CREATE PUBLICATION testpub_foralltables_excepttable2 FOR ALL TABLES EXCEPT (testpub_tbl1, testpub_tbl2); +-- fail - EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testpub_tbl3); --------------------------------------------- -- SET ALL TABLES/SEQUENCES @@ -220,7 +223,71 @@ RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Create same-named tables in public to verify unqualified EXCEPT entries +-- are qualified with the named schema, not public +CREATE TABLE testpub_nopk (foo int, bar int); +CREATE TABLE testpub_tbl_s1 (a int primary key, b text); + +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + +-- Exclude multiple tables using unqualified names; same-named tables exist in +-- public to confirm unqualified names resolve to pub_test, not public +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); + +-- Multiple schemas each with their own EXCEPT clause +CREATE PUBLICATION testpub_schema_except_multi + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_schema_except_multi + +-- fail: table appears in both the explicit table list and the EXCEPT clause +CREATE PUBLICATION testpub_except_conflict + FOR TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: nonexistent table in EXCEPT clause +CREATE PUBLICATION testpub_except_norel + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- fail: partition cannot appear in EXCEPT clause; only root tables are allowed +CREATE TABLE pub_test.testpub_parted_s (a int) PARTITION BY LIST (a); +CREATE TABLE pub_test.testpub_part_s PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (1); +CREATE PUBLICATION testpub_except_partition + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); + +-- fail: TABLE keyword is required for the first entry in the EXCEPT clause +CREATE PUBLICATION testpub_except_nokw + FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + +-- Cleanup +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP TABLE pub_test.testpub_parted_s CASCADE; +DROP TABLE testpub_nopk, testpub_tbl_s1; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; + +--------------------------------------------- +-- Tests for publications with SEQUENCES +--------------------------------------------- CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 8c58d282eee..18c7b2c1fca 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -24,14 +24,17 @@ my $result; sub test_except_root_partition { - my ($pubviaroot) = @_; + my ($pubviaroot, $pubsql) = @_; + $pubsql //= + "CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1)"; + $pubsql .= " WITH (publish_via_partition_root = $pubviaroot)"; # If the root partitioned table is in the EXCEPT clause, all its # partitions are excluded from publication, regardless of the # publish_via_partition_root setting. $node_publisher->safe_psql( 'postgres', qq( - CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1) WITH (publish_via_partition_root = $pubviaroot); + $pubsql; INSERT INTO root1 VALUES (1), (101); )); $node_subscriber->safe_psql('postgres', @@ -223,6 +226,131 @@ $node_subscriber->safe_psql( test_except_root_partition('false'); test_except_root_partition('true'); +# Same validation using TABLES IN SCHEMA instead of FOR ALL TABLES. +my $schema_pub = + "CREATE PUBLICATION tap_pub_part FOR TABLES IN SCHEMA public EXCEPT (TABLE public.root1)"; +test_except_root_partition('false', $schema_pub); +test_except_root_partition('true', $schema_pub); + +# ============================================ +# EXCEPT test cases for TABLES IN SCHEMA +# ============================================ + +# Create a dedicated schema with two tables: one to be published and one to be +# excluded. Also create inherited tables to verify ONLY semantics. +$node_publisher->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_published AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.tab_excluded AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.parent (a int); + CREATE TABLE sch1.child (b int) INHERITS (sch1.parent); +)); + +$node_subscriber->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_published (a int); + CREATE TABLE sch1.tab_excluded (a int); + CREATE TABLE sch1.parent (a int); + CREATE TABLE sch1.child (b int) INHERITS (sch1.parent); +)); + +# Basic test: initial sync respects EXCEPT. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_excluded)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: initial sync copies included table'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: initial sync skips excluded table'); + +# DML: only the included table should be replicated. +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (6); + INSERT INTO sch1.tab_excluded VALUES (6); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(6), + 'TABLES IN SCHEMA EXCEPT: DML on included table is replicated'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: DML on excluded table is not replicated'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Inherited tables: excluding the parent (without ONLY) also excludes the child. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.parent)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.child VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.child"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: excluding parent (without ONLY) also excludes child' +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Test that EXCEPT (TABLE ONLY parent) excludes only the parent itself, not its +# child. Truncate child first so rows from the previous test are not copied by +# the initial table sync of the next subscription. +$node_publisher->safe_psql('postgres', 'TRUNCATE sch1.child'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE sch1.child'); +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE ONLY sch1.parent)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.child VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.child"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: ONLY parent in EXCEPT does not exclude child'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Cleanup schema tables before the multi-publication section. +$node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); +$node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); + # ============================================ # Test when a subscription is subscribing to multiple publications # ============================================ @@ -254,6 +382,7 @@ $node_publisher->safe_psql( DROP PUBLICATION tap_pub2; TRUNCATE tab1; )); +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_subscriber->safe_psql('postgres', qq(TRUNCATE tab1)); # OK when a table is excluded by pub1 EXCEPT clause, but it is included by pub2 -- 2.50.1 (Apple Git-155)
v9-0002-Add-EXCEPT-support-to-ALTER-PUBLICATION-ADD-TABLE.patch (application/octet-stream, 22.3K) download From 1e821e30b2f01ecf10c9f314ccecc762a4a4c84e Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Fri, 29 May 2026 20:04:57 +0530 Subject: [PATCH v9 2/3] Add EXCEPT support to ALTER PUBLICATION ADD TABLES IN SCHEMA Extend the EXCEPT clause support to allow tables to be excluded when adding a schema to a publication via ALTER PUBLICATION ... ADD. Syntax: ALTER PUBLICATION pub ADD TABLES IN SCHEMA s EXCEPT (TABLE s.t1); Since pg_dump uses ALTER PUBLICATION ... ADD, support for it is included in this patch. --- doc/src/sgml/ref/alter_publication.sgml | 40 +++++++- src/backend/catalog/pg_publication.c | 19 ++-- src/backend/commands/publicationcmds.c | 107 +++++++++++++++++++++- src/bin/pg_dump/pg_dump.c | 30 +++++- src/bin/pg_dump/t/002_pg_dump.pl | 24 +++++ src/bin/psql/tab-complete.in.c | 15 +++ src/test/regress/expected/publication.out | 32 ++++++- src/test/regress/sql/publication.sql | 20 +++- src/test/subscription/t/037_except.pl | 32 +++++++ 9 files changed, 304 insertions(+), 15 deletions(-) diff --git a/doc/src/sgml/ref/alter_publication.sgml b/doc/src/sgml/ref/alter_publication.sgml index aa32bb169e9..73f6375a66f 100644 --- a/doc/src/sgml/ref/alter_publication.sgml +++ b/doc/src/sgml/ref/alter_publication.sgml @@ -31,7 +31,7 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA <replaceable class="parameter">tables_in_schema</replaceable> [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -47,6 +47,10 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <replaceable class="parameter">table_object</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] [ WHERE ( <replaceable class="parameter">expression</replaceable> ) ] +<phrase>and <replaceable class="parameter">tables_in_schema</replaceable> is:</phrase> + + { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] + <phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> TABLE <replaceable class="parameter">table_object</replaceable> [, ... ] @@ -110,6 +114,14 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <literal>ADD TABLE</literal>. </para> + <para> + The <literal>EXCEPT</literal> clause can be used with + <literal>ADD TABLES IN SCHEMA</literal> to exclude specific tables from the + publication. Using <literal>DROP TABLES IN SCHEMA</literal> on a publication + will automatically also remove any associated <literal>EXCEPT</literal> + entries. + </para> + <para> The fourth variant of this command listed in the synopsis can change all of the publication properties specified in @@ -198,6 +210,22 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r </listitem> </varlistentry> + <varlistentry> + <term><literal>EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] )</literal></term> + <listitem> + <para> + When used with <literal>ADD TABLES IN SCHEMA</literal>, specifies + tables to be excluded from the publication. Each named + table must belong to the schema specified in the same + <literal>TABLES IN SCHEMA</literal> clause. Table names may be + schema-qualified or unqualified; unqualified names are implicitly + qualified with the schema named in the same clause. See + <xref linkend="sql-createpublication"/> for further details on the + semantics of <literal>EXCEPT</literal>. + </para> + </listitem> + </varlistentry> + <varlistentry> <term><literal>SET ( <replaceable class="parameter">publication_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] )</literal></term> <listitem> @@ -288,6 +316,16 @@ ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA marketing, sales; </programlisting> </para> + <para> + Add schema <structname>sales</structname> to the publication + <structname>sales_publication</structname>, excluding the + <structname>sales.internal</structname> and + <structname>sales.drafts</structname> tables: +<programlisting> +ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA sales EXCEPT (TABLE internal, drafts); +</programlisting> + </para> + <para> Add tables <structname>users</structname>, <structname>departments</structname> and schema diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index 3437a878f74..15e4ed0f8f4 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -649,15 +649,18 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, * here, as CreatePublication() function invalidates all relations as part * of defining a FOR ALL TABLES publication. * - * For ALTER PUBLICATION, invalidation is needed only when adding an - * EXCEPT table to a publication already marked as ALL TABLES. For - * publications that were originally empty or defined as ALL SEQUENCES and - * are being converted to ALL TABLES, invalidation is skipped here, as - * AlterPublicationAllFlags() function invalidates all relations while - * marking the publication as ALL TABLES publication. + * For ALTER PUBLICATION, invalidation is needed when adding an EXCEPT + * table to either a FOR ALL TABLES publication (pub->alltables is true) + * or a FOR TABLES IN SCHEMA publication (is_schema_publication is true). + * The exception: when a publication is being converted to FOR ALL TABLES + * (pub->alltables is still false at this point), + * AlterPublicationAllFlags() will perform a full invalidation, so we + * skip it here. */ - inval_except_table = (alter_stmt != NULL) && pub->alltables && - (alter_stmt->for_all_tables && pri->except); + inval_except_table = (alter_stmt != NULL) && pri->except && + (pub->alltables + ? alter_stmt->for_all_tables + : is_schema_publication(pubid)); if (!pri->except || inval_except_table) { diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index cd39d6375cd..09663579058 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -70,6 +70,13 @@ static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok); static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); +static void AlterPublicationSchemas(AlterPublicationStmt *stmt, + HeapTuple tup, List *schemaidlist, + List *except_pubtables); +static void AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, + List *except_pubtables, + List *schemaidlist); static char defGetGeneratedColsOption(DefElem *def); @@ -1468,7 +1475,8 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, */ static void AlterPublicationSchemas(AlterPublicationStmt *stmt, - HeapTuple tup, List *schemaidlist) + HeapTuple tup, List *schemaidlist, + List *except_pubtables) { Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); @@ -1545,6 +1553,97 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, */ PublicationAddSchemas(pubform->oid, schemaidlist, true, stmt); } + + /* + * Increment the command counter so that is_schema_publication() in + * GetExcludedPublicationTables() can see the just-inserted schema + * rows when AlterPublicationSchemaExceptTables runs next. + */ + if (stmt->action == AP_AddObjects || stmt->action == AP_SetObjects) + CommandCounterIncrement(); + + AlterPublicationSchemaExceptTables(stmt, tup, except_pubtables, schemaidlist); +} + +/* + * Alter the EXCEPT list of a schema-level publication. + * + * Adds, removes, or replaces except-table entries in pg_publication_rel + * (rows with prexcept = true). These entries suppress publication of the + * named tables that would otherwise be covered by a FOR TABLES IN SCHEMA + * clause. + */ +static void +AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, List *except_pubtables, + List *schemaidlist) +{ + Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); + Oid pubid = pubform->oid; + + /* + * Nothing to do if no EXCEPT entries. + */ + if (!except_pubtables) + return; + + /* + * This function handles EXCEPT entries for schema-level publications + * only. For FOR ALL TABLES publications, EXCEPT entries are already + * processed by AlterPublicationTables(). + */ + if (schemaidlist == NIL && !is_schema_publication(pubid)) + return; + + /* + * Dropping a schema from a publication removes all its EXCEPT entries via + * cascade. The concept of "drop all schema tables from the publication + * EXCEPT these ones" is not supported. + */ + if (stmt->action == AP_DropObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); + + /* + * XXX EXCEPT with SET is not currently implemented. Workaround: DROP and + * re-ADD the schema with the desired EXCEPT list. + */ + if (stmt->action == AP_SetObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"), + errhint("Drop and re-add the schema with the desired EXCEPT list."))); + + if (stmt->action == AP_AddObjects) + { + List *rels; + List *explicitrelids; + + rels = OpenTableList(except_pubtables); + + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + /* + * Validate that each excluded table is not also in the explicit table + * list (which would be contradictory). + */ + foreach_ptr(PublicationRelInfo, pri, rels) + { + Oid relid = RelationGetRelid(pri->relation); + + if (list_member_oid(explicitrelids, relid)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" cannot appear in both the table list and the EXCEPT clause", + RelationGetQualifiedRelationName(pri->relation))); + } + + PublicationAddTables(pubid, rels, false, stmt); + + CloseTableList(rels); + } } /* @@ -1754,10 +1853,12 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) errmsg("publication \"%s\" does not exist", stmt->pubname)); - relations = list_concat(relations, except_pubtables); + if (stmt->for_all_tables) + relations = list_concat(relations, except_pubtables); + AlterPublicationTables(stmt, tup, relations, pstate->p_sourcetext, schemaidlist != NIL); - AlterPublicationSchemas(stmt, tup, schemaidlist); + AlterPublicationSchemas(stmt, tup, schemaidlist, except_pubtables); AlterPublicationAllFlags(stmt, rel, tup); } diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c index d56dcc701ce..e62d74c8ca0 100644 --- a/src/bin/pg_dump/pg_dump.c +++ b/src/bin/pg_dump/pg_dump.c @@ -5019,6 +5019,7 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) PublicationInfo *pubinfo = pubsinfo->publication; PQExpBuffer query; char *tag; + bool has_except = false; /* Do nothing if not dumping schema */ if (!dopt->dumpSchema) @@ -5029,7 +5030,34 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) query = createPQExpBuffer(); appendPQExpBuffer(query, "ALTER PUBLICATION %s ", fmtId(pubinfo->dobj.name)); - appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s;\n", fmtId(schemainfo->dobj.name)); + appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s", fmtId(schemainfo->dobj.name)); + + /* + * Append EXCEPT clause for any tables that belong to this schema + * and are excluded from the publication. + */ + for (SimplePtrListCell *cell = pubinfo->except_tables.head; cell; cell = cell->next) + { + TableInfo *tbinfo = (TableInfo *) cell->ptr; + + if (strcmp(tbinfo->dobj.namespace->dobj.name, schemainfo->dobj.name) == 0) + { + if (!has_except) + { + appendPQExpBufferStr(query, " EXCEPT ("); + has_except = true; + } + else + appendPQExpBufferStr(query, ", "); + + appendPQExpBuffer(query, "TABLE ONLY %s", fmtId(tbinfo->dobj.name)); + } + } + + if (has_except) + appendPQExpBufferStr(query, ")"); + + appendPQExpBufferStr(query, ";\n"); /* * There is no point in creating drop query as the drop is done by schema diff --git a/src/bin/pg_dump/t/002_pg_dump.pl b/src/bin/pg_dump/t/002_pg_dump.pl index 3ee9fda50e4..b8f4aa769ec 100644 --- a/src/bin/pg_dump/t/002_pg_dump.pl +++ b/src/bin/pg_dump/t/002_pg_dump.pl @@ -3242,6 +3242,30 @@ my %tests = ( like => { %full_runs, section_post_data => 1, }, }, + 'CREATE PUBLICATION pub11' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub11 FOR TABLES IN SCHEMA dump_test EXCEPT (TABLE test_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub11 WITH (publish = 'insert, update, delete, truncate');\E + .*? + \QALTER PUBLICATION pub11 ADD TABLES IN SCHEMA dump_test EXCEPT (TABLE ONLY test_table);\E + /xms, + like => { %full_runs, section_post_data => 1, }, + }, + + 'CREATE PUBLICATION pub12' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub12 FOR TABLES IN SCHEMA dump_test EXCEPT (TABLE test_table, dump_test.test_second_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub12 WITH (publish = 'insert, update, delete, truncate');\E + .*? + \QALTER PUBLICATION pub12 ADD TABLES IN SCHEMA dump_test EXCEPT (TABLE ONLY test_table, TABLE ONLY test_second_table);\E + /xms, + like => { %full_runs, section_post_data => 1, }, + }, + 'CREATE SUBSCRIPTION sub1' => { create_order => 50, create_sql => 'CREATE SUBSCRIPTION sub1 diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index fe11dc619ac..8db3e129928 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2364,6 +2364,21 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); + /* After a single schema name in ADD context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 008c6cebaca..f56b0524ae9 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -564,12 +564,42 @@ CREATE PUBLICATION testpub_except_nokw ERROR: syntax error at or near "testpub_nopk" LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); ^ +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; +-- fail: non-existing table in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- fail: EXCEPT table belongs to a different schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 1: ...xcept ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.tes... + ^ +-- fail: TABLE keyword is required for the first entry in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +ERROR: syntax error at or near "testpub_nopk" +LINE 1: ...lter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_no... + ^ +-- ADD: qualified and unqualified names; unqualified is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + "pub_test.testpub_tbl_s2" + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP TABLE pub_test.testpub_parted_s CASCADE; DROP TABLE testpub_nopk, testpub_tbl_s1; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi, testpub_alter_except; --------------------------------------------- -- Tests for publications with SEQUENCES --------------------------------------------- diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 9162d4d15a5..072d50050cd 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -278,12 +278,30 @@ CREATE PUBLICATION testpub_except_partition CREATE PUBLICATION testpub_except_nokw FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; + +-- fail: non-existing table in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- fail: EXCEPT table belongs to a different schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- fail: TABLE keyword is required for the first entry in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + +-- ADD: qualified and unqualified names; unqualified is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); +\dRp+ testpub_alter_except + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP TABLE pub_test.testpub_parted_s CASCADE; DROP TABLE testpub_nopk, testpub_tbl_s1; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi, testpub_alter_except; --------------------------------------------- -- Tests for publications with SEQUENCES diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 18c7b2c1fca..0ba6d6f8bb2 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -347,6 +347,38 @@ is($result, qq(5), $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); +# ============================================ +# ALTER PUBLICATION EXCEPT for TABLES IN SCHEMA +# ============================================ + +# Truncate subscriber tables to remove data accumulated from previous tests. +$node_subscriber->safe_psql('postgres', + 'TRUNCATE sch1.tab_published, sch1.tab_excluded, sch1.parent, sch1.child'); + +# ADD: add a schema with an excepted table; verify the except entry takes effect. +$node_publisher->safe_psql('postgres', "CREATE PUBLICATION sch_pub"); +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub ADD TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_excluded)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(6), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: included table synced'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + # Cleanup schema tables before the multi-publication section. $node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); $node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); -- 2.50.1 (Apple Git-155)
v9-0003-Add-EXCEPT-support-to-ALTER-PUBLICATION-SET-TABLE.patch (application/octet-stream, 25.9K) download From 6b1bb0b7faa1b68d6507d1efcf158a753f79eed7 Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Tue, 2 Jun 2026 11:39:36 +0530 Subject: [PATCH v9 3/3] Add EXCEPT support to ALTER PUBLICATION SET TABLES IN SCHEMA Extend AlterPublicationExceptTables() with the AP_SetObjects case, which redefines the publication and replaces the entire EXCEPT list. Syntax: ALTER PUBLICATION pub SET TABLES IN SCHEMA s EXCEPT (TABLE t1); This patch also cleans up EXCEPT entries when a schema is dropped from the publication. --- doc/src/sgml/ref/alter_publication.sgml | 27 +++- src/backend/commands/publicationcmds.c | 135 +++++++++++++++++--- src/backend/replication/pgoutput/pgoutput.c | 10 +- src/bin/psql/tab-complete.in.c | 15 +++ src/test/regress/expected/publication.out | 86 +++++++++++++ src/test/regress/sql/publication.sql | 38 ++++++ src/test/subscription/t/037_except.pl | 85 ++++++++++++ 7 files changed, 369 insertions(+), 27 deletions(-) diff --git a/doc/src/sgml/ref/alter_publication.sgml b/doc/src/sgml/ref/alter_publication.sgml index 73f6375a66f..80b038e4b2e 100644 --- a/doc/src/sgml/ref/alter_publication.sgml +++ b/doc/src/sgml/ref/alter_publication.sgml @@ -97,7 +97,11 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r used with a publication defined with <literal>FOR TABLE</literal> or <literal>FOR TABLES IN SCHEMA</literal>, replaces the list of tables/schemas in the publication with the specified list; the existing tables or schemas - that were present in the publication will be removed. + that were present in the publication will be removed. When + <literal>SET TABLES IN SCHEMA</literal> is used with an + <literal>EXCEPT</literal> clause, the excluded tables for each schema are + replaced with the specified list; if <literal>EXCEPT</literal> is omitted + for a schema, any existing exclusions for that schema are cleared. </para> <para> @@ -116,10 +120,8 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <para> The <literal>EXCEPT</literal> clause can be used with - <literal>ADD TABLES IN SCHEMA</literal> to exclude specific tables from the - publication. Using <literal>DROP TABLES IN SCHEMA</literal> on a publication - will automatically also remove any associated <literal>EXCEPT</literal> - entries. + <literal>ADD TABLES IN SCHEMA</literal> to exclude specific tables from a + schema-level publication. </para> <para> @@ -214,7 +216,8 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <term><literal>EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] )</literal></term> <listitem> <para> - When used with <literal>ADD TABLES IN SCHEMA</literal>, specifies + When used with <literal>ADD TABLES IN SCHEMA</literal> + or <literal>SET TABLES IN SCHEMA</literal>, specifies tables to be excluded from the publication. Each named table must belong to the schema specified in the same <literal>TABLES IN SCHEMA</literal> clause. Table names may be @@ -326,6 +329,18 @@ ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA sales EXCEPT (TABLE int </programlisting> </para> + <para> + Replace the schema list of <structname>sales_publication</structname> with + <structname>sales</structname>, excluding only + <structname>sales.drafts</structname>. Other than + <structname>sales.drafts</structname>, any previously excluded tables for schema + <structname>sales</structname> are no longer excluded. Any schemas previously in + <structname>sales_publication</structname> are removed: +<programlisting> +ALTER PUBLICATION sales_publication SET TABLES IN SCHEMA sales EXCEPT (TABLE drafts); +</programlisting> + </para> + <para> Add tables <structname>users</structname>, <structname>departments</structname> and schema diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 09663579058..8bf71edcdaa 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -1556,8 +1556,8 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, /* * Increment the command counter so that is_schema_publication() in - * GetExcludedPublicationTables() can see the just-inserted schema - * rows when AlterPublicationSchemaExceptTables runs next. + * GetExcludedPublicationTables() can see the just-inserted schema rows + * when AlterPublicationSchemaExceptTables runs next. */ if (stmt->action == AP_AddObjects || stmt->action == AP_SetObjects) CommandCounterIncrement(); @@ -1575,16 +1575,18 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, */ static void AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, - HeapTuple tup, List *except_pubtables, - List *schemaidlist) + HeapTuple tup, List *except_pubtables, + List *schemaidlist) { Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); Oid pubid = pubform->oid; /* - * Nothing to do if no EXCEPT entries. + * Nothing to do if there are no EXCEPT entries, unless handling the SET + * command, because if the user has removed all exceptions we need to drop + * any existing ones. */ - if (!except_pubtables) + if (!except_pubtables && stmt->action != AP_SetObjects) return; /* @@ -1605,16 +1607,6 @@ AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); - /* - * XXX EXCEPT with SET is not currently implemented. Workaround: DROP and - * re-ADD the schema with the desired EXCEPT list. - */ - if (stmt->action == AP_SetObjects) - ereport(ERROR, - (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"), - errhint("Drop and re-add the schema with the desired EXCEPT list."))); - if (stmt->action == AP_AddObjects) { List *rels; @@ -1642,6 +1634,84 @@ AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, PublicationAddTables(pubid, rels, false, stmt); + CloseTableList(rels); + } + else /* AP_SetObjects */ + { + List *oldexceptrelids = NIL; + List *newexceptrelids = NIL; + List *delrelids = NIL; + List *rels; + List *explicitrelids; + + rels = OpenTableList(except_pubtables); + + /* Collect OIDs of the desired new EXCEPT list. */ + foreach_ptr(PublicationRelInfo, pri, rels) + newexceptrelids = lappend_oid(newexceptrelids, + RelationGetRelid(pri->relation)); + + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + /* + * Validate that each excluded table is not also in the explicit table + * list (which would be contradictory). + */ + foreach_ptr(PublicationRelInfo, pri, rels) + { + Oid relid = RelationGetRelid(pri->relation); + + if (list_member_oid(explicitrelids, relid)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" cannot appear in both the table list and the EXCEPT clause", + RelationGetQualifiedRelationName(pri->relation))); + } + + /* + * Get the current set of EXCEPT entries. Only FOR ALL TABLES and + * schema-level publications can have EXCEPT entries; for any other + * publication type oldexceptrelids stays NIL. + * + * Note: we check is_schema_publication() against the current catalog + * state (before AlterPublicationSchemas has run), so if the caller is + * doing SET TABLE t1 to convert a schema publication into a plain + * table publication, is_schema_publication() still returns true here. + * That is intentional: it lets us discover and clean up any stale + * EXCEPT entries that belong to the old schema definition. + */ + if (GetPublication(pubid)->alltables || is_schema_publication(pubid)) + oldexceptrelids = GetExcludedPublicationTables(pubid, + PUBLICATION_PART_ROOT); + + /* Build a list of old EXCEPT entries not present in the new list. */ + foreach_oid(oldrelid, oldexceptrelids) + { + if (!list_member_oid(newexceptrelids, oldrelid)) + delrelids = lappend_oid(delrelids, oldrelid); + } + + /* Drop old EXCEPT entries not present in the new list. */ + foreach_oid(relid, delrelids) + { + Oid proid; + ObjectAddress obj; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + /* Add new EXCEPT entries, skipping any already present. */ + PublicationAddTables(pubid, rels, true, stmt); + CloseTableList(rels); } } @@ -2291,6 +2361,7 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) foreach(lc, schemas) { Oid schemaid = lfirst_oid(lc); + List *except_relids; psid = GetSysCacheOid2(PUBLICATIONNAMESPACEMAP, Anum_pg_publication_namespace_oid, @@ -2307,8 +2378,40 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) get_namespace_name(schemaid)))); } + /* + * Collect EXCEPT entries for tables belonging to this schema before + * removing the schema entry. + */ + except_relids = GetExcludedPublicationTables(pubid, PUBLICATION_PART_ROOT); + ObjectAddressSet(obj, PublicationNamespaceRelationId, psid); performDeletion(&obj, DROP_CASCADE, 0); + + /* + * Drop any prexcept rows for tables belonging to this schema. These + * rows have no pg_depend entry pointing at the + * pg_publication_namespace row, so they are not cascaded by the + * performDeletion() call above and must be cleaned up explicitly. + */ + foreach_oid(relid, except_relids) + { + Oid proid; + + if (get_rel_namespace(relid) != schemaid) + continue; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + list_free(except_relids); } } diff --git a/src/backend/replication/pgoutput/pgoutput.c b/src/backend/replication/pgoutput/pgoutput.c index 7ee84ec1c83..9831be54b47 100644 --- a/src/backend/replication/pgoutput/pgoutput.c +++ b/src/backend/replication/pgoutput/pgoutput.c @@ -2229,7 +2229,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) */ if (pub->alltables) { - List *exceptpubids = NIL; + List *except_pubids = NIL; if (am_partition) { @@ -2252,7 +2252,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) * clause. Therefore, for a partition, exclusion must be * evaluated at the top-most ancestor. */ - exceptpubids = GetRelationExcludedPublications(last_ancestor_relid); + except_pubids = GetRelationExcludedPublications(last_ancestor_relid); } else { @@ -2260,13 +2260,13 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) * For a regular table or a root partitioned table, check * exclusion on table itself. */ - exceptpubids = GetRelationExcludedPublications(pub_relid); + except_pubids = GetRelationExcludedPublications(pub_relid); } - if (!list_member_oid(exceptpubids, pub->oid)) + if (!list_member_oid(except_pubids, pub->oid)) publish = true; - list_free(exceptpubids); + list_free(except_pubids); if (!publish) continue; diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index 8db3e129928..11c87b1b006 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2379,6 +2379,21 @@ match_previous_words(int pattern_id, } else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) COMPLETE_WITH(")"); + /* After a single schema name in SET context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index f56b0524ae9..70715ce7e10 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -594,6 +594,92 @@ Except tables: "pub_test.testpub_tbl_s1" "pub_test.testpub_tbl_s2" +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s2" + +-- fail: table in EXCEPT clause also appears in the explicit table list +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot appear in both the table list and the EXCEPT clause +-- error: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 1: ...xcept SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.tes... + ^ +-- SET: unqualified name in EXCEPT is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- SET without EXCEPT clears the existing except list +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + +-- SET to a different schema removes old schema's EXCEPT entries +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA public; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "public" + +-- fail: nonexistent table in EXCEPT clause (SET path) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- SET: multiple schemas each with their own EXCEPT clause +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- error: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +ERROR: EXCEPT clause is not supported with DROP in ALTER PUBLICATION +-- DROP TABLES IN SCHEMA removes associated EXCEPT entries +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "public" +Except tables: + "public.testpub_tbl1" + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 072d50050cd..72bb2f7a028 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -296,6 +296,44 @@ ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (tes ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); \dRp+ testpub_alter_except +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + +-- fail: table in EXCEPT clause also appears in the explicit table list +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- error: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- SET: unqualified name in EXCEPT is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +\dRp+ testpub_alter_except + +-- SET without EXCEPT clears the existing except list +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + +-- SET to a different schema removes old schema's EXCEPT entries +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA public; +\dRp+ testpub_alter_except + +-- fail: nonexistent table in EXCEPT clause (SET path) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- SET: multiple schemas each with their own EXCEPT clause +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_alter_except + +-- error: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); + +-- DROP TABLES IN SCHEMA removes associated EXCEPT entries +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 0ba6d6f8bb2..01eafb5b7c8 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -376,6 +376,61 @@ $result = is($result, qq(0), 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); +# SET: replace the except list; tab_excluded is now included and tab_published is excluded. +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_published)" +); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (7); + INSERT INTO sch1.tab_excluded VALUES (7); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded WHERE a = 7"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: newly included table is replicated' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published WHERE a = 7"); +is($result, qq(0), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: now-excluded table is not replicated' +); + +# SET without EXCEPT: clears the except list; both tables are now published. +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1"); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (8); + INSERT INTO sch1.tab_excluded VALUES (8); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published WHERE a = 8"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_published replicated after except list cleared' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded WHERE a = 8"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_excluded replicated after except list cleared' +); + $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); @@ -443,6 +498,36 @@ $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); +# OK when a table is excluded by a TABLES IN SCHEMA EXCEPT publication, +# but is included by another publication. +$node_publisher->safe_psql('postgres', 'TRUNCATE tab1'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE tab1'); + +$node_publisher->safe_psql( + 'postgres', qq( + CREATE PUBLICATION tap_pub1 FOR TABLES IN SCHEMA public EXCEPT (TABLE public.tab1); + CREATE PUBLICATION tap_pub2 FOR TABLE tab1; + INSERT INTO tab1 VALUES(1); +)); +$node_subscriber->psql('postgres', + "CREATE SUBSCRIPTION tap_sub CONNECTION '$publisher_connstr' PUBLICATION tap_pub1, tap_pub2" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'tap_sub'); + +$node_publisher->safe_psql('postgres', qq(INSERT INTO tab1 VALUES(2))); +$node_publisher->wait_for_catchup('tap_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT * FROM tab1 ORDER BY a"); +is( $result, qq(1 +2), + "TABLES IN SCHEMA EXCEPT: table excluded in schema pub but included by another pub is replicated" +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); + $node_publisher->stop('fast'); done_testing(); -- 2.50.1 (Apple Git-155)
^ permalink raw reply [nested|flat] 196+ messages in thread

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-06-02 21:21  Zsolt Parragi <zsolt.parragi@percona.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: Zsolt Parragi @ 2026-06-02 21:21 UTC (permalink / raw)
  To: pgsql-hackers@lists.postgresql.org

Hello

In this simple script:

CREATE SCHEMA s;
CREATE TABLE s.a(i int);
CREATE TABLE s.b(i int);
CREATE PUBLICATION p FOR TABLES IN SCHEMA s EXCEPT (TABLE s.b);

SELECT * FROM pg_publication_tables WHERE pubname = 'p';
SELECT * FROM pg_get_publication_tables(ARRAY['p'], 's.b'::regclass);

Shouldn't the second select return an empty list? Currently it returns
one row for s.b.

And I think there's also a bug with CREATE PUBLICATION with IN SCHEMA
CURRENT_SCHEMA:

CREATE SCHEMA s1;
CREATE TABLE s1.a(i int);
CREATE TABLE public.x(i int);
CREATE TABLE public.onlypub(i int);   -- exists only in public, not in s1

CREATE PUBLICATION pn FOR TABLES IN SCHEMA s1 EXCEPT (TABLE public.x);
-- error out, good
SET search_path = s1, public;
CREATE PUBLICATION pn2 FOR TABLES IN SCHEMA s1 EXCEPT (TABLE onlypub);
-- error out, good
SET search_path = s1, public;
SELECT current_schema(); -- s1
CREATE PUBLICATION pc FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT
(TABLE public.x); -- doesn't error out
CREATE PUBLICATION pc4 FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT
(TABLE onlypub); -- also doesn't error out





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-06-05 11:41  Nisha Moond <nisha.moond412@gmail.com>
  parent: Zsolt Parragi <zsolt.parragi@percona.com>
  0 siblings, 1 reply; 196+ messages in thread

From: Nisha Moond @ 2026-06-05 11:41 UTC (permalink / raw)
  To: Zsolt Parragi <zsolt.parragi@percona.com>; +Cc: pgsql-hackers@lists.postgresql.org

On Wed, Jun 3, 2026 at 2:51 AM Zsolt Parragi <zsolt.parragi@percona.com> wrote:
>
> Hello
>

Hi, thanks for the tests.

> In this simple script:
>
> CREATE SCHEMA s;
> CREATE TABLE s.a(i int);
> CREATE TABLE s.b(i int);
> CREATE PUBLICATION p FOR TABLES IN SCHEMA s EXCEPT (TABLE s.b);
>
> SELECT * FROM pg_publication_tables WHERE pubname = 'p';
> SELECT * FROM pg_get_publication_tables(ARRAY['p'], 's.b'::regclass);
>
> Shouldn't the second select return an empty list? Currently it returns
> one row for s.b.
>

Yes, it is a bug.
The issue was that pg_get_publication_tables() could not distinguish
between prexcept=true and prexcept=false.

A reference note: This worked fine for FOR ALL TABLES publications
because entries in pg_publication_rel always had prexcept=false, so
the presence of an entry implied the table was not published. With
non-ALL TABLES publications, a table can now have both prexcept=true
(explicitly excluded) and prexcept=false (excluded from a schema
publication).

Fixed.

> And I think there's also a bug with CREATE PUBLICATION with IN SCHEMA
> CURRENT_SCHEMA:
>
> CREATE SCHEMA s1;
> CREATE TABLE s1.a(i int);
> CREATE TABLE public.x(i int);
> CREATE TABLE public.onlypub(i int);   -- exists only in public, not in s1
>
> CREATE PUBLICATION pn FOR TABLES IN SCHEMA s1 EXCEPT (TABLE public.x);
> -- error out, good
> SET search_path = s1, public;
> CREATE PUBLICATION pn2 FOR TABLES IN SCHEMA s1 EXCEPT (TABLE onlypub);
> -- error out, good
> SET search_path = s1, public;
> SELECT current_schema(); -- s1
> CREATE PUBLICATION pc FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT
> (TABLE public.x); -- doesn't error out
> CREATE PUBLICATION pc4 FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT
> (TABLE onlypub); -- also doesn't error out
>

Yes, this is a bug. The CURRENT_SCHEMA case was missed when the patch
was updated to allow only immediate schema tables in the EXCEPT
clause.

Attached are v10 patches with fixes for both issues. I also added the
missing tab-completion for CURRENT_SCHEMA and added regression tests
in publication.sql covering both scenarios.

--
Thanks,
Nisha

Attachments: download all (3 files, .tar.gz)

v10-0001-Support-EXCEPT-clause-for-schema-level-publicati.patch (application/octet-stream, 59.2K) download From cfcad088676a8d4c988dd1b87bcc278af1d6903d Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Mon, 4 May 2026 12:49:27 +0530 Subject: [PATCH v10 1/3] Support EXCEPT clause for schema-level publications Extend table exclusion support in publications to allow specific tables to be excluded from schema-level publications using an EXCEPT clause in CREATE PUBLICATION. Supported syntax: CREATE PUBLICATION <pub> FOR TABLES IN SCHEMA s EXCEPT (TABLE t1,...); --- doc/src/sgml/logical-replication.sgml | 3 +- doc/src/sgml/ref/create_publication.sgml | 22 ++- src/backend/catalog/pg_publication.c | 161 ++++++++++++++++---- src/backend/commands/publicationcmds.c | 97 ++++++++++-- src/backend/parser/gram.y | 55 ++++++- src/backend/replication/pgoutput/pgoutput.c | 30 +++- src/bin/psql/describe.c | 18 +++ src/bin/psql/tab-complete.in.c | 35 ++++- src/include/catalog/pg_publication.h | 3 +- src/include/nodes/parsenodes.h | 2 + src/test/regress/expected/publication.out | 144 ++++++++++++++++- src/test/regress/sql/publication.sql | 88 ++++++++++- src/test/subscription/t/037_except.pl | 133 +++++++++++++++- 13 files changed, 734 insertions(+), 57 deletions(-) diff --git a/doc/src/sgml/logical-replication.sgml b/doc/src/sgml/logical-replication.sgml index 9e7868487de..1433d2660fe 100644 --- a/doc/src/sgml/logical-replication.sgml +++ b/doc/src/sgml/logical-replication.sgml @@ -117,7 +117,8 @@ or <literal>FOR ALL SEQUENCES</literal>. Unlike tables, sequences can be synchronized at any time. For more information, see <xref linkend="logical-replication-sequences"/>. When a publication is - created with <literal>FOR ALL TABLES</literal>, a table or set of tables can + created with <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal>, a table or set of tables can be explicitly excluded from publication using the <link linkend="sql-createpublication-params-for-except-table"><literal>EXCEPT</literal></link> clause. diff --git a/doc/src/sgml/ref/create_publication.sgml b/doc/src/sgml/ref/create_publication.sgml index f82d640e6ca..7fa0bd11f7b 100644 --- a/doc/src/sgml/ref/create_publication.sgml +++ b/doc/src/sgml/ref/create_publication.sgml @@ -28,7 +28,7 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA <replaceable class="parameter">tables_in_schema</replaceable> [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -39,6 +39,10 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <replaceable class="parameter">table_object</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] [ WHERE ( <replaceable class="parameter">expression</replaceable> ) ] +<phrase>and <replaceable class="parameter">tables_in_schema</replaceable> is:</phrase> + + { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] + <phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> TABLE <replaceable class="parameter">table_object</replaceable> [, ... ] @@ -142,6 +146,8 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <para> Marks the publication as one that replicates changes for all tables in the specified list of schemas, including tables created in the future. + Tables listed in the <literal>EXCEPT</literal> clause for a given schema + are excluded from the publication. </para> <para> @@ -173,7 +179,7 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <para> Marks the publication as one that replicates changes for all tables in the database, including tables created in the future. Tables listed in - <literal>EXCEPT</literal> clause are excluded from the publication. + the <literal>EXCEPT</literal> clause are excluded from the publication. </para> </listitem> </varlistentry> @@ -198,7 +204,8 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <listitem> <para> This clause specifies a list of tables to be excluded from the - publication. + publication. It can be used with <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal>. </para> <para> For inherited tables, if <literal>ONLY</literal> is specified before the @@ -515,6 +522,15 @@ CREATE PUBLICATION production_publication FOR TABLE users, departments, TABLES I CREATE PUBLICATION sales_publication FOR TABLES IN SCHEMA marketing, sales; </programlisting></para> + <para> + Create a publication that publishes all changes for all the tables present in + the schema <structname>sales</structname>, except + <structname>internal</structname> and <structname>drafts</structname>: +<programlisting> +CREATE PUBLICATION sales_filtered FOR TABLES IN SCHEMA sales EXCEPT (TABLE internal, drafts); +</programlisting> + </para> + <para> Create a publication that publishes all changes for table <structname>users</structname>, but replicates only columns <structname>user_id</structname> and diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index 5c457d9aca8..4089b505f89 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -444,13 +444,19 @@ GetPubPartitionOptionRelations(List *result, PublicationPartOpt pub_partopt, * * Note that the list of ancestors should be ordered such that the topmost * ancestor is at the end of the list. + * + * except_pubids is a list of publication OIDs whose schema membership + * should be ignored for the ancestor (because the ancestor is in their + * EXCEPT clause). */ Oid -GetTopMostAncestorInPublication(Oid puboid, List *ancestors, int *ancestor_level) +GetTopMostAncestorInPublication(Oid puboid, List *ancestors, + int *ancestor_level, List *except_pubids) { ListCell *lc; Oid topmost_relid = InvalidOid; int level = 0; + bool check_schemas = !list_member_oid(except_pubids, puboid); /* * Find the "topmost" ancestor that is in this publication. @@ -470,7 +476,7 @@ GetTopMostAncestorInPublication(Oid puboid, List *ancestors, int *ancestor_level if (ancestor_level) *ancestor_level = level; } - else + else if (check_schemas) { aschemaPubids = GetSchemaPublications(get_rel_namespace(ancestor)); if (list_member_oid(aschemaPubids, puboid)) @@ -545,18 +551,30 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, * duplicates, it's here just to provide nicer error message in common * case. The real protection is the unique key on the catalog. */ - if (SearchSysCacheExists2(PUBLICATIONRELMAP, ObjectIdGetDatum(relid), - ObjectIdGetDatum(pubid))) + tup = SearchSysCache2(PUBLICATIONRELMAP, ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + + if (HeapTupleIsValid(tup)) { + bool is_except = ((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept; + + ReleaseSysCache(tup); table_close(rel, RowExclusiveLock); if (if_not_exists) return InvalidObjectAddress; - ereport(ERROR, - (errcode(ERRCODE_DUPLICATE_OBJECT), - errmsg("relation \"%s\" is already member of publication \"%s\"", - RelationGetRelationName(targetrel), pub->name))); + if (is_except) + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("table \"%s\" cannot be added because it is excluded from publication \"%s\"", + RelationGetQualifiedRelationName(targetrel), + pub->name))); + else + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("relation \"%s\" is already member of publication \"%s\"", + RelationGetRelationName(targetrel), pub->name))); } check_publication_add_relation(pri); @@ -982,12 +1000,13 @@ GetIncludedPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) * Gets list of table oids that were specified in the EXCEPT clause for a * publication. * - * This should only be used FOR ALL TABLES publications. + * This is used for FOR ALL TABLES and FOR TABLES IN SCHEMA publications, + * both of which support EXCEPT TABLE. */ List * GetExcludedPublicationTables(Oid pubid, PublicationPartOpt pub_partopt) { - Assert(GetPublication(pubid)->alltables); + Assert(GetPublication(pubid)->alltables || is_schema_publication(pubid)); return get_publication_relations(pubid, pub_partopt, true); } @@ -1049,15 +1068,15 @@ GetAllPublicationRelations(Oid pubid, char relkind, bool pubviaroot) TableScanDesc scan; HeapTuple tuple; List *result = NIL; - List *exceptlist = NIL; + List *except_relids = NIL; Assert(!(relkind == RELKIND_SEQUENCE && pubviaroot)); /* EXCEPT filtering applies only to relations, not sequences */ if (relkind == RELKIND_RELATION) - exceptlist = GetExcludedPublicationTables(pubid, pubviaroot ? - PUBLICATION_PART_ROOT : - PUBLICATION_PART_LEAF); + except_relids = GetExcludedPublicationTables(pubid, pubviaroot ? + PUBLICATION_PART_ROOT : + PUBLICATION_PART_LEAF); classRel = table_open(RelationRelationId, AccessShareLock); @@ -1075,7 +1094,7 @@ GetAllPublicationRelations(Oid pubid, char relkind, bool pubviaroot) if (is_publishable_class(relid, relForm) && !(relForm->relispartition && pubviaroot) && - !list_member_oid(exceptlist, relid)) + !list_member_oid(except_relids, relid)) result = lappend_oid(result, relid); } @@ -1097,7 +1116,7 @@ GetAllPublicationRelations(Oid pubid, char relkind, bool pubviaroot) if (is_publishable_class(relid, relForm) && !relForm->relispartition && - !list_member_oid(exceptlist, relid)) + !list_member_oid(except_relids, relid)) result = lappend_oid(result, relid); } @@ -1232,22 +1251,67 @@ GetSchemaPublicationRelations(Oid schemaid, PublicationPartOpt pub_partopt) /* * Gets the list of all relations published by FOR TABLES IN SCHEMA - * publication. + * publication, excluding any tables listed in the EXCEPT clause. */ List * GetAllSchemaPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) { List *result = NIL; List *pubschemalist = GetPublicationSchemas(pubid); + List *except_relids = NIL; ListCell *cell; + /* get the list of tables excluded via EXCEPT TABLE for this publication */ + if (pubschemalist != NIL) + except_relids = GetExcludedPublicationTables(pubid, pub_partopt); + foreach(cell, pubschemalist) { Oid schemaid = lfirst_oid(cell); List *schemaRels = NIL; schemaRels = GetSchemaPublicationRelations(schemaid, pub_partopt); - result = list_concat(result, schemaRels); + + if (except_relids != NIL) + { + /* filter out any tables that appear in the EXCEPT list */ + ListCell *rlc; + + foreach(rlc, schemaRels) + { + Oid relid = lfirst_oid(rlc); + bool excluded = list_member_oid(except_relids, relid); + + /* + * Also exclude any relation whose partition ancestor is in + * the EXCEPT list. This matters when pub_partopt is + * PUBLICATION_PART_ROOT: the except list holds only the root + * OID, but the schema scan may also return individual + * partition relations that live in the same schema. + */ + if (!excluded && get_rel_relispartition(relid)) + { + List *ancestors = get_partition_ancestors(relid); + ListCell *alc; + + foreach(alc, ancestors) + { + if (list_member_oid(except_relids, lfirst_oid(alc))) + { + excluded = true; + break; + } + } + list_free(ancestors); + } + + if (!excluded) + result = lappend_oid(result, relid); + } + list_free(schemaRels); + } + else + result = list_concat(result, schemaRels); } return result; @@ -1324,6 +1388,7 @@ is_table_publishable_in_publication(Oid relid, Publication *pub) { bool relispartition; List *ancestors = NIL; + HeapTuple tup; /* * For non-pubviaroot publications, a partitioned table is never the @@ -1380,20 +1445,62 @@ is_table_publishable_in_publication(Oid relid, Publication *pub) * If it's false, the partition is covered by its ancestor's presence in * the publication, it should be included (return true). */ - if (relispartition && - OidIsValid(GetTopMostAncestorInPublication(pub->oid, ancestors, NULL))) - return !pub->pubviaroot; + if (relispartition) + { + Oid ancestor_oid; + + ancestor_oid = GetTopMostAncestorInPublication(pub->oid, ancestors, NULL, NIL); + if (OidIsValid(ancestor_oid)) + { + /* + * The ancestor was found in the publication (via explicit + * membership or schema membership), but it may be excluded. Check + * for a prexcept row before concluding the partition is + * published. + */ + tup = SearchSysCache2(PUBLICATIONRELMAP, + ObjectIdGetDatum(ancestor_oid), + ObjectIdGetDatum(pub->oid)); + if (HeapTupleIsValid(tup)) + { + bool is_except; + + is_except = ((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept; + ReleaseSysCache(tup); + if (is_except) + return false; + } + return !pub->pubviaroot; + } + } /* * Check whether the table is explicitly published via pg_publication_rel * or pg_publication_namespace. + * + * A pg_publication_rel row with prexcept=true means the table is + * explicitly excluded via EXCEPT and must not be reported as published, + * even if its schema is otherwise included. A row with prexcept=false + * means it is explicitly included. If no pg_publication_rel row exists, + * the table is published iff its schema appears in + * pg_publication_namespace. */ - return (SearchSysCacheExists2(PUBLICATIONRELMAP, - ObjectIdGetDatum(relid), - ObjectIdGetDatum(pub->oid)) || - SearchSysCacheExists2(PUBLICATIONNAMESPACEMAP, - ObjectIdGetDatum(get_rel_namespace(relid)), - ObjectIdGetDatum(pub->oid))); + + tup = SearchSysCache2(PUBLICATIONRELMAP, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pub->oid)); + if (HeapTupleIsValid(tup)) + { + bool is_except; + + is_except = ((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept; + ReleaseSysCache(tup); + return !is_except; + } + + return SearchSysCacheExists2(PUBLICATIONNAMESPACEMAP, + ObjectIdGetDatum(get_rel_namespace(relid)), + ObjectIdGetDatum(pub->oid)); } /* diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 440adb356ad..b8d2d8e03f2 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -181,7 +181,7 @@ parse_publication_options(ParseState *pstate, */ static void ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, - List **rels, List **exceptrels, List **schemas) + List **rels, List **except_pubtables, List **schemas) { ListCell *cell; PublicationObjSpec *pubobj; @@ -200,7 +200,7 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, { case PUBLICATIONOBJ_EXCEPT_TABLE: pubobj->pubtable->except = true; - *exceptrels = lappend(*exceptrels, pubobj->pubtable); + *except_pubtables = lappend(*except_pubtables, pubobj->pubtable); break; case PUBLICATIONOBJ_TABLE: pubobj->pubtable->except = false; @@ -224,6 +224,38 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, /* Filter out duplicates if user specifies "sch1, sch1" */ *schemas = list_append_unique_oid(*schemas, schemaid); + + /* + * Qualify unqualified EXCEPT table names with the resolved + * current schema and reject any explicitly cross-schema + * entries. This mirrors the parse-time handling done for + * TABLES_IN_SCHEMA in preprocess_pubobj_list(), deferred here + * because CURRENT_SCHEMA is not known until execution time. + */ + if (pubobj->except_tables != NIL) + { + char *cur_schema_name = get_namespace_name(schemaid); + + foreach_ptr(PublicationObjSpec, eobj, pubobj->except_tables) + { + const char *eobj_schemaname = + eobj->pubtable->relation->schemaname; + const char *eobj_relname = + eobj->pubtable->relation->relname; + + if (eobj_schemaname == NULL) + eobj->pubtable->relation->schemaname = cur_schema_name; + else if (strcmp(eobj_schemaname, cur_schema_name) != 0) + ereport(ERROR, + errcode(ERRCODE_INVALID_OBJECT_DEFINITION), + errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", + quote_qualified_identifier(eobj_schemaname, eobj_relname), + cur_schema_name)); + + *except_pubtables = lappend(*except_pubtables, + eobj->pubtable); + } + } break; default: /* shouldn't happen */ @@ -305,7 +337,7 @@ pub_rf_contains_invalid_column(Oid pubid, Relation relation, List *ancestors, if (pubviaroot && relation->rd_rel->relispartition) { publish_as_relid - = GetTopMostAncestorInPublication(pubid, ancestors, NULL); + = GetTopMostAncestorInPublication(pubid, ancestors, NULL, NIL); if (!OidIsValid(publish_as_relid)) publish_as_relid = relid; @@ -389,7 +421,7 @@ pub_contains_invalid_column(Oid pubid, Relation relation, List *ancestors, */ if (pubviaroot && relation->rd_rel->relispartition) { - publish_as_relid = GetTopMostAncestorInPublication(pubid, ancestors, NULL); + publish_as_relid = GetTopMostAncestorInPublication(pubid, ancestors, NULL, NIL); if (!OidIsValid(publish_as_relid)) publish_as_relid = relid; @@ -849,7 +881,7 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) char publish_generated_columns; AclResult aclresult; List *relations = NIL; - List *exceptrelations = NIL; + List *except_pubtables = NIL; List *schemaidlist = NIL; /* must have CREATE privilege on database */ @@ -936,16 +968,16 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) /* Associate objects with the publication. */ ObjectsInPublicationToOids(stmt->pubobjects, pstate, &relations, - &exceptrelations, &schemaidlist); + &except_pubtables, &schemaidlist); if (stmt->for_all_tables) { /* Process EXCEPT table list */ - if (exceptrelations != NIL) + if (except_pubtables != NIL) { List *rels; - rels = OpenTableList(exceptrelations); + rels = OpenTableList(except_pubtables); PublicationAddTables(puboid, rels, true, NULL); CloseTableList(rels); } @@ -959,6 +991,8 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) } else if (!stmt->for_all_sequences) { + List *explicitrelids = NIL; + /* FOR TABLES IN SCHEMA requires superuser */ if (schemaidlist != NIL && !superuser()) ereport(ERROR, @@ -977,6 +1011,19 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) schemaidlist != NIL, publish_via_partition_root); + /* + * Collect explicit table OIDs now, before we close the relation + * list, so that except-table validation below can check for + * contradictions without relying on a catalog scan that might not + * yet see the just-inserted rows. + */ + if (except_pubtables != NIL) + { + foreach_ptr(PublicationRelInfo, pri, rels) + explicitrelids = lappend_oid(explicitrelids, + RelationGetRelid(pri->relation)); + } + PublicationAddTables(puboid, rels, true, NULL); CloseTableList(rels); } @@ -989,6 +1036,34 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) */ LockSchemaList(schemaidlist); PublicationAddSchemas(puboid, schemaidlist, true, NULL); + + if (except_pubtables != NIL) + { + List *except_rels; + + except_rels = OpenTableList(except_pubtables); + + /* + * Validate that each excluded table is not also in the + * explicit table list (which would be contradictory). Use the + * in-memory explicitrelids collected above rather than + * re-reading the catalog, which may not yet see the + * just-inserted rows. + */ + foreach_ptr(PublicationRelInfo, pri, except_rels) + { + Oid except_relid = RelationGetRelid(pri->relation); + + if (list_member_oid(explicitrelids, except_relid)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" cannot appear in both the table list and the EXCEPT clause", + RelationGetQualifiedRelationName(pri->relation))); + } + + PublicationAddTables(puboid, except_rels, true, NULL); + CloseTableList(except_rels); + } } } @@ -1683,12 +1758,12 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) else { List *relations = NIL; - List *exceptrelations = NIL; + List *except_pubtables = NIL; List *schemaidlist = NIL; Oid pubid = pubform->oid; ObjectsInPublicationToOids(stmt->pubobjects, pstate, &relations, - &exceptrelations, &schemaidlist); + &except_pubtables, &schemaidlist); CheckAlterPublication(stmt, tup, relations, schemaidlist); @@ -1711,7 +1786,7 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) errmsg("publication \"%s\" does not exist", stmt->pubname)); - relations = list_concat(relations, exceptrelations); + relations = list_concat(relations, except_pubtables); AlterPublicationTables(stmt, tup, relations, pstate->p_sourcetext, schemaidlist != NIL); AlterPublicationSchemas(stmt, tup, schemaidlist); diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y index ff4e1388c55..717e03aac7c 100644 --- a/src/backend/parser/gram.y +++ b/src/backend/parser/gram.y @@ -58,6 +58,7 @@ #include "nodes/makefuncs.h" #include "nodes/nodeFuncs.h" #include "parser/parser.h" +#include "utils/builtins.h" #include "utils/datetime.h" #include "utils/xml.h" @@ -11272,7 +11273,7 @@ AlterOwnerStmt: ALTER AGGREGATE aggregate_with_argtypes OWNER TO RoleSpec * pub_obj is one of: * * TABLE table [, ...] - * TABLES IN SCHEMA schema [, ...] + * TABLES IN SCHEMA schema [EXCEPT (TABLE table [, ...] )] [, ...] * *****************************************************************************/ @@ -11332,23 +11333,26 @@ PublicationObjSpec: $$->pubtable->columns = $3; $$->pubtable->whereClause = $4; } - | TABLES IN_P SCHEMA ColId + | TABLES IN_P SCHEMA ColId opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_SCHEMA; $$->name = $4; + $$->except_tables = $5; $$->location = @4; } - | TABLES IN_P SCHEMA CURRENT_SCHEMA + | TABLES IN_P SCHEMA CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_CUR_SCHEMA; + $$->except_tables = $5; $$->location = @4; } - | ColId opt_column_list OptWhereClause + | ColId opt_column_list OptWhereClause opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $4; /* * If either a row filter or column list is specified, create * a PublicationTable object. @@ -11392,10 +11396,11 @@ PublicationObjSpec: $$->pubtable->columns = $2; $$->pubtable->whereClause = $3; } - | CURRENT_SCHEMA + | CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $2; $$->location = @1; } ; @@ -20784,6 +20789,8 @@ preprocess_pub_all_objtype_list(List *all_objects_list, List **pubobjects, /* * Process pubobjspec_list to check for errors in any of the objects and * convert PUBLICATIONOBJ_CONTINUATION into appropriate PublicationObjSpecType. + * Also flattens except_tables from TABLES IN SCHEMA nodes into the list so + * that ObjectsInPublicationToOids() sees them as top-level EXCEPT_TABLE entries. */ static void preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) @@ -20812,6 +20819,13 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLE) { + /* EXCEPT is not valid for table objects */ + if (pubobj->except_tables != NIL) + ereport(ERROR, + errcode(ERRCODE_SYNTAX_ERROR), + errmsg("EXCEPT is not allowed for TABLE publication objects"), + parser_errposition(pubobj->location)); + /* relation name or pubtable must be set for this type of object */ if (!pubobj->name && !pubobj->pubtable) ereport(ERROR, @@ -20860,6 +20874,37 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) errcode(ERRCODE_SYNTAX_ERROR), errmsg("invalid schema name"), parser_errposition(pubobj->location)); + + /* + * For TABLES_IN_SCHEMA, qualify unqualified EXCEPT table names + * with the parent schema and reject cross-schema entries at parse + * time, then flatten into the top-level list. + * + * For TABLES_IN_CUR_SCHEMA the schema name is not yet known, so + * skip both steps here; ObjectsInPublicationToOids() will + * qualify names and validate schema membership at execution time. + */ + if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLES_IN_SCHEMA) + { + foreach_ptr(PublicationObjSpec, eobj, pubobj->except_tables) + { + const char *eobj_schemaname = eobj->pubtable->relation->schemaname; + const char *eobj_relname = eobj->pubtable->relation->relname; + + if (eobj_schemaname == NULL) + eobj->pubtable->relation->schemaname = pubobj->name; + else if (strcmp(eobj_schemaname, pubobj->name) != 0) + ereport(ERROR, + errcode(ERRCODE_INVALID_OBJECT_DEFINITION), + errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", + quote_qualified_identifier(eobj_schemaname, eobj_relname), + pubobj->name), + parser_errposition(eobj->location)); + } + pubobjspec_list = list_concat(pubobjspec_list, pubobj->except_tables); + pubobj->except_tables = NIL; + } + /* For TABLES_IN_CUR_SCHEMA: leave except_tables for execution time */ } prevobjtype = pubobj->pubobjtype; diff --git a/src/backend/replication/pgoutput/pgoutput.c b/src/backend/replication/pgoutput/pgoutput.c index 4ecfcbff7ab..7ee84ec1c83 100644 --- a/src/backend/replication/pgoutput/pgoutput.c +++ b/src/backend/replication/pgoutput/pgoutput.c @@ -2097,6 +2097,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) * are absorbed while decoding WAL. */ List *schemaPubids = GetSchemaPublications(schemaId); + List *except_pubids; ListCell *lc; Oid publish_as_relid = relid; int publish_ancestor_level = 0; @@ -2104,6 +2105,28 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) char relkind = get_rel_relkind(relid); List *rel_publications = NIL; + /* + * For the schema EXCEPT check, we must look up the top-most ancestor + * rather than the relation itself. check_publication_add_relation() + * prevents individual partitions from appearing in the EXCEPT clause, + * so only a root (non-partition) table can have prexcept = true. + * Using the partition's own OID would always return NIL and miss the + * exclusion. + */ + Oid root_relid; + + if (am_partition) + { + List *ancestors = get_partition_ancestors(relid); + + root_relid = llast_oid(ancestors); + list_free(ancestors); + } + else + root_relid = relid; + + except_pubids = GetRelationExcludedPublications(root_relid); + /* Reload publications if needed before use. */ if (!publications_valid) { @@ -2267,7 +2290,8 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) ancestor = GetTopMostAncestorInPublication(pub->oid, ancestors, - &level); + &level, + except_pubids); if (ancestor != InvalidOid) { @@ -2281,7 +2305,8 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) } if (list_member_oid(pubids, pub->oid) || - list_member_oid(schemaPubids, pub->oid) || + (list_member_oid(schemaPubids, pub->oid) && + !list_member_oid(except_pubids, pub->oid)) || ancestor_published) publish = true; } @@ -2360,6 +2385,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) list_free(pubids); list_free(schemaPubids); + list_free(except_pubids); list_free(rel_publications); entry->replicate_valid = true; diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c index e1449654f96..e5b1a70e05e 100644 --- a/src/bin/psql/describe.c +++ b/src/bin/psql/describe.c @@ -7038,6 +7038,24 @@ describePublications(const char *pattern) if (!addFooterToPublicationDesc(&buf, _("Tables from schemas:"), true, &cont)) goto error_return; + + if (pset.sversion >= 190000) + { + /* + * Get tables in the EXCEPT clause for this schema + * publication. + */ + printfPQExpBuffer(&buf, + "SELECT concat(c.relnamespace::regnamespace, '.', c.relname)\n" + "FROM pg_catalog.pg_class c\n" + " JOIN pg_catalog.pg_publication_rel pr ON c.oid = pr.prrelid\n" + "WHERE pr.prpubid = '%s'\n" + " AND pr.prexcept\n" + "ORDER BY 1", pubid); + if (!addFooterToPublicationDesc(&buf, _("Except tables:"), + true, &cont)) + goto error_return; + } } } else diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index de547a8cb37..53bb7c8679b 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -1065,6 +1065,24 @@ static const SchemaQuery Query_for_trigger_of_table = { "SELECT nspname FROM pg_catalog.pg_namespace "\ " WHERE nspname LIKE '%s'" +#define Query_for_list_of_tables_in_schema \ +"SELECT n.nspname || '.' || c.relname "\ +" FROM pg_catalog.pg_class c "\ +" JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "\ +" WHERE c.relkind IN (" CppAsString2(RELKIND_RELATION) ", " \ + CppAsString2(RELKIND_PARTITIONED_TABLE) ") "\ +" AND (n.nspname || '.' || c.relname) LIKE '%s' "\ +" AND n.nspname = '%s'" + +#define Query_for_list_of_tables_in_current_schema \ +"SELECT c.relname "\ +" FROM pg_catalog.pg_class c "\ +" JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "\ +" WHERE c.relkind IN (" CppAsString2(RELKIND_RELATION) ", " \ + CppAsString2(RELKIND_PARTITIONED_TABLE) ") "\ +" AND c.relname LIKE '%s' "\ +" AND n.nspname = pg_catalog.current_schema()" + /* Use COMPLETE_WITH_QUERY_VERBATIM with these queries for GUC names: */ #define Query_for_list_of_alter_system_set_vars \ "SELECT pg_catalog.lower(name) FROM pg_catalog.pg_settings "\ @@ -3787,8 +3805,21 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); - else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && (!ends_with(prev_wd, ','))) - COMPLETE_WITH("WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE", "WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* Complete "CREATE PUBLICATION <name> [...] WITH" */ else if (Matches("CREATE", "PUBLICATION", MatchAnyN, "WITH", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/include/catalog/pg_publication.h b/src/include/catalog/pg_publication.h index 89b4bb14f62..53e3d7c6f3d 100644 --- a/src/include/catalog/pg_publication.h +++ b/src/include/catalog/pg_publication.h @@ -191,7 +191,8 @@ extern List *GetPubPartitionOptionRelations(List *result, PublicationPartOpt pub_partopt, Oid relid); extern Oid GetTopMostAncestorInPublication(Oid puboid, List *ancestors, - int *ancestor_level); + int *ancestor_level, + List *except_pubids); extern bool is_publishable_relation(Relation rel); extern bool is_schema_publication(Oid pubid); diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h index 91377a6cde3..98a03c0eeda 100644 --- a/src/include/nodes/parsenodes.h +++ b/src/include/nodes/parsenodes.h @@ -4493,6 +4493,8 @@ typedef struct PublicationObjSpec PublicationObjSpecType pubobjtype; /* type of this publication object */ char *name; PublicationTable *pubtable; + List *except_tables; /* tables specified in the EXCEPT clause (for + * TABLES IN SCHEMA) */ ParseLoc location; /* token location, or -1 if unknown */ } PublicationObjSpec; diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 29e54b214a0..6df42a60f9c 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -270,6 +270,12 @@ CREATE PUBLICATION testpub_foralltables_excepttable2 FOR ALL TABLES EXCEPT (test ERROR: syntax error at or near "testpub_tbl1" LINE 1: ..._foralltables_excepttable2 FOR ALL TABLES EXCEPT (testpub_tb... ^ +-- fail - EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testpub_tbl3); +ERROR: EXCEPT is not allowed for TABLE publication objects +LINE 2: FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testp... + ^ --------------------------------------------- -- SET ALL TABLES/SEQUENCES --------------------------------------------- @@ -470,7 +476,103 @@ HINT: Change the publication's EXCEPT clause using ALTER PUBLICATION ... SET AL RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Create same-named tables in public to verify unqualified EXCEPT entries +-- are qualified with the named schema, not public +CREATE TABLE testpub_nopk (foo int, bar int); +CREATE TABLE testpub_tbl_s1 (a int primary key, b text); +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + Publication testpub_schema_except1 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- Exclude multiple tables using unqualified names; same-named tables exist in +-- public to confirm unqualified names resolve to pub_test, not public +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + Publication testpub_schema_except2 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_nopk" + "pub_test.testpub_tbl_s1" + +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testp... + ^ +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); +ERROR: table "pub_test.testpub_tbl_s1" in EXCEPT clause does not belong to schema "public" +LINE 2: ...R TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.t... + ^ +-- Multiple schemas each with their own EXCEPT clause +CREATE PUBLICATION testpub_schema_except_multi + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_schema_except_multi + Publication testpub_schema_except_multi + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- fail: table appears in both the explicit table list and the EXCEPT clause +CREATE PUBLICATION testpub_except_conflict + FOR TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot appear in both the table list and the EXCEPT clause +-- fail: nonexistent table in EXCEPT clause +CREATE PUBLICATION testpub_except_norel + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- fail: partition cannot appear in EXCEPT clause; only root tables are allowed +CREATE TABLE pub_test.testpub_parted_s (a int) PARTITION BY LIST (a); +CREATE TABLE pub_test.testpub_part_s PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (1); +CREATE PUBLICATION testpub_except_partition + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); +ERROR: cannot specify relation "pub_test.testpub_part_s" in the publication EXCEPT clause +DETAIL: This operation is not supported for individual partitions. +-- fail: TABLE keyword is required for the first entry in the EXCEPT clause +CREATE PUBLICATION testpub_except_nokw + FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +ERROR: syntax error at or near "testpub_nopk" +LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + ^ +-- Cleanup +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP TABLE pub_test.testpub_parted_s CASCADE; +DROP TABLE testpub_nopk, testpub_tbl_s1; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +--------------------------------------------- +-- Tests for publications with SEQUENCES +--------------------------------------------- CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; -- FOR ALL SEQUENCES @@ -1953,6 +2055,27 @@ ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b); ERROR: column specification not allowed for schema LINE 1: ...TION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b)... ^ +-- EXCEPT clause with CURRENT_SCHEMA: cross-schema entry must be rejected +SET search_path = pub_test1; +-- qualified name from wrong schema -> error +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.tbl1); +ERROR: table "pub_test2.tbl1" in EXCEPT clause does not belong to schema "pub_test1" +-- unqualified name implicitly qualified with current schema (pub_test1.tbl) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl); +RESET client_min_messages; +\dRp+ testpub_cursch_except + Publication testpub_cursch_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test1" +Except tables: + "pub_test1.tbl" + +DROP PUBLICATION testpub_cursch_except; +RESET search_path; -- cleanup pub_test1 schema for invalidation tests ALTER PUBLICATION testpub2_forschema DROP TABLES IN SCHEMA pub_test1; DROP PUBLICATION testpub3_forschema, testpub4_forschema, testpub5_forschema, testpub6_forschema, testpub_fortable; @@ -2304,6 +2427,7 @@ DROP ROLE regress_publication_user_dummy; -- Test pg_get_publication_tables(text[], oid) function CREATE SCHEMA gpt_test_sch; CREATE TABLE gpt_test_sch.tbl_sch (id int); +CREATE TABLE gpt_test_sch.tbl_sch2 (id int); CREATE TABLE tbl_normal (id int); CREATE TABLE tbl_parent (id1 int, id2 int, id3 int) PARTITION BY RANGE (id1); CREATE TABLE tbl_part1 PARTITION OF tbl_parent FOR VALUES FROM (1) TO (10); @@ -2314,6 +2438,7 @@ CREATE PUBLICATION pub_all_no_viaroot FOR ALL TABLES WITH (publish_via_partition CREATE PUBLICATION pub_all_except FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = true); CREATE PUBLICATION pub_all_except_no_viaroot FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_schema FOR TABLES IN SCHEMA gpt_test_sch; +CREATE PUBLICATION pub_schema_except FOR TABLES IN SCHEMA gpt_test_sch EXCEPT (TABLE gpt_test_sch.tbl_sch); CREATE PUBLICATION pub_normal FOR TABLE tbl_normal WHERE (id < 10); CREATE PUBLICATION pub_part_leaf FOR TABLE tbl_part1 WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_part_parent FOR TABLE tbl_parent (id1, id2) WHERE (id1 = 10) WITH (publish_via_partition_root = true); @@ -2465,6 +2590,18 @@ SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_part1'); -- no r ---------+---------+-------+------ (0 rows) +-- test for EXCEPT clause with schema publication (bug: excluded table was incorrectly returned) +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch'); -- no result (excluded) + pubname | relname | attrs | qual +---------+---------+-------+------ +(0 rows) + +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch2'); -- one row (included via schema) + pubname | relname | attrs | qual +-------------------+----------+-------+------ + pub_schema_except | tbl_sch2 | 1 | +(1 row) + -- two rows with different row filter SELECT * FROM test_gpt(ARRAY['pub_all', 'pub_normal'], 'tbl_normal'); pubname | relname | attrs | qual @@ -2517,6 +2654,7 @@ DROP PUBLICATION pub_all_no_viaroot; DROP PUBLICATION pub_all_except; DROP PUBLICATION pub_all_except_no_viaroot; DROP PUBLICATION pub_schema; +DROP PUBLICATION pub_schema_except; DROP PUBLICATION pub_normal; DROP PUBLICATION pub_part_leaf; DROP PUBLICATION pub_part_parent; @@ -2525,7 +2663,9 @@ DROP PUBLICATION pub_part_parent_child; DROP VIEW gpt_test_view; DROP TABLE tbl_normal, tbl_parent, tbl_part1; DROP SCHEMA gpt_test_sch CASCADE; -NOTICE: drop cascades to table gpt_test_sch.tbl_sch +NOTICE: drop cascades to 2 other objects +DETAIL: drop cascades to table gpt_test_sch.tbl_sch +drop cascades to table gpt_test_sch.tbl_sch2 -- stage objects for pg_dump tests CREATE SCHEMA pubme CREATE TABLE t0 (c int, d int) CREATE TABLE t1 (c int); CREATE SCHEMA pubme2 CREATE TABLE t0 (c int, d int); diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 041e14a4de6..bd523e376b2 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -123,6 +123,9 @@ CREATE PUBLICATION testpub_foralltables_excepttable1 FOR ALL TABLES EXCEPT (TABL \d testpub_tbl1 -- fail - first table in the EXCEPT list should use TABLE keyword CREATE PUBLICATION testpub_foralltables_excepttable2 FOR ALL TABLES EXCEPT (testpub_tbl1, testpub_tbl2); +-- fail - EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testpub_tbl3); --------------------------------------------- -- SET ALL TABLES/SEQUENCES @@ -220,7 +223,71 @@ RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Create same-named tables in public to verify unqualified EXCEPT entries +-- are qualified with the named schema, not public +CREATE TABLE testpub_nopk (foo int, bar int); +CREATE TABLE testpub_tbl_s1 (a int primary key, b text); + +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + +-- Exclude multiple tables using unqualified names; same-named tables exist in +-- public to confirm unqualified names resolve to pub_test, not public +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); + +-- Multiple schemas each with their own EXCEPT clause +CREATE PUBLICATION testpub_schema_except_multi + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_schema_except_multi + +-- fail: table appears in both the explicit table list and the EXCEPT clause +CREATE PUBLICATION testpub_except_conflict + FOR TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: nonexistent table in EXCEPT clause +CREATE PUBLICATION testpub_except_norel + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- fail: partition cannot appear in EXCEPT clause; only root tables are allowed +CREATE TABLE pub_test.testpub_parted_s (a int) PARTITION BY LIST (a); +CREATE TABLE pub_test.testpub_part_s PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (1); +CREATE PUBLICATION testpub_except_partition + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); + +-- fail: TABLE keyword is required for the first entry in the EXCEPT clause +CREATE PUBLICATION testpub_except_nokw + FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + +-- Cleanup +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP TABLE pub_test.testpub_parted_s CASCADE; +DROP TABLE testpub_nopk, testpub_tbl_s1; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; + +--------------------------------------------- +-- Tests for publications with SEQUENCES +--------------------------------------------- CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; @@ -1189,6 +1256,18 @@ ALTER PUBLICATION testpub1_forschema SET TABLES IN SCHEMA pub_test1, pub_test1; ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo (a, b); ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b); +-- EXCEPT clause with CURRENT_SCHEMA: cross-schema entry must be rejected +SET search_path = pub_test1; +-- qualified name from wrong schema -> error +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.tbl1); +-- unqualified name implicitly qualified with current schema (pub_test1.tbl) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl); +RESET client_min_messages; +\dRp+ testpub_cursch_except +DROP PUBLICATION testpub_cursch_except; +RESET search_path; + -- cleanup pub_test1 schema for invalidation tests ALTER PUBLICATION testpub2_forschema DROP TABLES IN SCHEMA pub_test1; DROP PUBLICATION testpub3_forschema, testpub4_forschema, testpub5_forschema, testpub6_forschema, testpub_fortable; @@ -1443,6 +1522,7 @@ DROP ROLE regress_publication_user_dummy; -- Test pg_get_publication_tables(text[], oid) function CREATE SCHEMA gpt_test_sch; CREATE TABLE gpt_test_sch.tbl_sch (id int); +CREATE TABLE gpt_test_sch.tbl_sch2 (id int); CREATE TABLE tbl_normal (id int); CREATE TABLE tbl_parent (id1 int, id2 int, id3 int) PARTITION BY RANGE (id1); CREATE TABLE tbl_part1 PARTITION OF tbl_parent FOR VALUES FROM (1) TO (10); @@ -1454,6 +1534,7 @@ CREATE PUBLICATION pub_all_no_viaroot FOR ALL TABLES WITH (publish_via_partition CREATE PUBLICATION pub_all_except FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = true); CREATE PUBLICATION pub_all_except_no_viaroot FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_schema FOR TABLES IN SCHEMA gpt_test_sch; +CREATE PUBLICATION pub_schema_except FOR TABLES IN SCHEMA gpt_test_sch EXCEPT (TABLE gpt_test_sch.tbl_sch); CREATE PUBLICATION pub_normal FOR TABLE tbl_normal WHERE (id < 10); CREATE PUBLICATION pub_part_leaf FOR TABLE tbl_part1 WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_part_parent FOR TABLE tbl_parent (id1, id2) WHERE (id1 = 10) WITH (publish_via_partition_root = true); @@ -1510,6 +1591,10 @@ SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'gpt_test_sch.tbl_sch SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_parent'); -- no result (excluded) SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_part1'); -- no result +-- test for EXCEPT clause with schema publication (bug: excluded table was incorrectly returned) +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch'); -- no result (excluded) +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch2'); -- one row (included via schema) + -- two rows with different row filter SELECT * FROM test_gpt(ARRAY['pub_all', 'pub_normal'], 'tbl_normal'); @@ -1538,6 +1623,7 @@ DROP PUBLICATION pub_all_no_viaroot; DROP PUBLICATION pub_all_except; DROP PUBLICATION pub_all_except_no_viaroot; DROP PUBLICATION pub_schema; +DROP PUBLICATION pub_schema_except; DROP PUBLICATION pub_normal; DROP PUBLICATION pub_part_leaf; DROP PUBLICATION pub_part_parent; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 8c58d282eee..18c7b2c1fca 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -24,14 +24,17 @@ my $result; sub test_except_root_partition { - my ($pubviaroot) = @_; + my ($pubviaroot, $pubsql) = @_; + $pubsql //= + "CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1)"; + $pubsql .= " WITH (publish_via_partition_root = $pubviaroot)"; # If the root partitioned table is in the EXCEPT clause, all its # partitions are excluded from publication, regardless of the # publish_via_partition_root setting. $node_publisher->safe_psql( 'postgres', qq( - CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1) WITH (publish_via_partition_root = $pubviaroot); + $pubsql; INSERT INTO root1 VALUES (1), (101); )); $node_subscriber->safe_psql('postgres', @@ -223,6 +226,131 @@ $node_subscriber->safe_psql( test_except_root_partition('false'); test_except_root_partition('true'); +# Same validation using TABLES IN SCHEMA instead of FOR ALL TABLES. +my $schema_pub = + "CREATE PUBLICATION tap_pub_part FOR TABLES IN SCHEMA public EXCEPT (TABLE public.root1)"; +test_except_root_partition('false', $schema_pub); +test_except_root_partition('true', $schema_pub); + +# ============================================ +# EXCEPT test cases for TABLES IN SCHEMA +# ============================================ + +# Create a dedicated schema with two tables: one to be published and one to be +# excluded. Also create inherited tables to verify ONLY semantics. +$node_publisher->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_published AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.tab_excluded AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.parent (a int); + CREATE TABLE sch1.child (b int) INHERITS (sch1.parent); +)); + +$node_subscriber->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_published (a int); + CREATE TABLE sch1.tab_excluded (a int); + CREATE TABLE sch1.parent (a int); + CREATE TABLE sch1.child (b int) INHERITS (sch1.parent); +)); + +# Basic test: initial sync respects EXCEPT. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_excluded)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: initial sync copies included table'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: initial sync skips excluded table'); + +# DML: only the included table should be replicated. +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (6); + INSERT INTO sch1.tab_excluded VALUES (6); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(6), + 'TABLES IN SCHEMA EXCEPT: DML on included table is replicated'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: DML on excluded table is not replicated'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Inherited tables: excluding the parent (without ONLY) also excludes the child. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.parent)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.child VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.child"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: excluding parent (without ONLY) also excludes child' +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Test that EXCEPT (TABLE ONLY parent) excludes only the parent itself, not its +# child. Truncate child first so rows from the previous test are not copied by +# the initial table sync of the next subscription. +$node_publisher->safe_psql('postgres', 'TRUNCATE sch1.child'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE sch1.child'); +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE ONLY sch1.parent)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.child VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.child"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: ONLY parent in EXCEPT does not exclude child'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Cleanup schema tables before the multi-publication section. +$node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); +$node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); + # ============================================ # Test when a subscription is subscribing to multiple publications # ============================================ @@ -254,6 +382,7 @@ $node_publisher->safe_psql( DROP PUBLICATION tap_pub2; TRUNCATE tab1; )); +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_subscriber->safe_psql('postgres', qq(TRUNCATE tab1)); # OK when a table is excluded by pub1 EXCEPT clause, but it is included by pub2 -- 2.50.1 (Apple Git-155)
v10-0002-Add-EXCEPT-support-to-ALTER-PUBLICATION-ADD-TABL.patch (application/octet-stream, 22.5K) download From a34e8a0ac377fbe27aeb40ccd6d50041eb19365e Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Fri, 29 May 2026 20:04:57 +0530 Subject: [PATCH v10 2/3] Add EXCEPT support to ALTER PUBLICATION ADD TABLES IN SCHEMA Extend the EXCEPT clause support to allow tables to be excluded when adding a schema to a publication via ALTER PUBLICATION ... ADD. Syntax: ALTER PUBLICATION pub ADD TABLES IN SCHEMA s EXCEPT (TABLE s.t1); Since pg_dump uses ALTER PUBLICATION ... ADD, support for it is included in this patch. --- doc/src/sgml/ref/alter_publication.sgml | 40 +++++++- src/backend/catalog/pg_publication.c | 19 ++-- src/backend/commands/publicationcmds.c | 107 +++++++++++++++++++++- src/bin/pg_dump/pg_dump.c | 30 +++++- src/bin/pg_dump/t/002_pg_dump.pl | 24 +++++ src/bin/psql/tab-complete.in.c | 17 ++++ src/test/regress/expected/publication.out | 32 ++++++- src/test/regress/sql/publication.sql | 20 +++- src/test/subscription/t/037_except.pl | 32 +++++++ 9 files changed, 306 insertions(+), 15 deletions(-) diff --git a/doc/src/sgml/ref/alter_publication.sgml b/doc/src/sgml/ref/alter_publication.sgml index aa32bb169e9..73f6375a66f 100644 --- a/doc/src/sgml/ref/alter_publication.sgml +++ b/doc/src/sgml/ref/alter_publication.sgml @@ -31,7 +31,7 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA <replaceable class="parameter">tables_in_schema</replaceable> [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -47,6 +47,10 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <replaceable class="parameter">table_object</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] [ WHERE ( <replaceable class="parameter">expression</replaceable> ) ] +<phrase>and <replaceable class="parameter">tables_in_schema</replaceable> is:</phrase> + + { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] + <phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> TABLE <replaceable class="parameter">table_object</replaceable> [, ... ] @@ -110,6 +114,14 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <literal>ADD TABLE</literal>. </para> + <para> + The <literal>EXCEPT</literal> clause can be used with + <literal>ADD TABLES IN SCHEMA</literal> to exclude specific tables from the + publication. Using <literal>DROP TABLES IN SCHEMA</literal> on a publication + will automatically also remove any associated <literal>EXCEPT</literal> + entries. + </para> + <para> The fourth variant of this command listed in the synopsis can change all of the publication properties specified in @@ -198,6 +210,22 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r </listitem> </varlistentry> + <varlistentry> + <term><literal>EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] )</literal></term> + <listitem> + <para> + When used with <literal>ADD TABLES IN SCHEMA</literal>, specifies + tables to be excluded from the publication. Each named + table must belong to the schema specified in the same + <literal>TABLES IN SCHEMA</literal> clause. Table names may be + schema-qualified or unqualified; unqualified names are implicitly + qualified with the schema named in the same clause. See + <xref linkend="sql-createpublication"/> for further details on the + semantics of <literal>EXCEPT</literal>. + </para> + </listitem> + </varlistentry> + <varlistentry> <term><literal>SET ( <replaceable class="parameter">publication_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] )</literal></term> <listitem> @@ -288,6 +316,16 @@ ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA marketing, sales; </programlisting> </para> + <para> + Add schema <structname>sales</structname> to the publication + <structname>sales_publication</structname>, excluding the + <structname>sales.internal</structname> and + <structname>sales.drafts</structname> tables: +<programlisting> +ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA sales EXCEPT (TABLE internal, drafts); +</programlisting> + </para> + <para> Add tables <structname>users</structname>, <structname>departments</structname> and schema diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index 4089b505f89..d1ff8839037 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -649,15 +649,18 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, * here, as CreatePublication() function invalidates all relations as part * of defining a FOR ALL TABLES publication. * - * For ALTER PUBLICATION, invalidation is needed only when adding an - * EXCEPT table to a publication already marked as ALL TABLES. For - * publications that were originally empty or defined as ALL SEQUENCES and - * are being converted to ALL TABLES, invalidation is skipped here, as - * AlterPublicationAllFlags() function invalidates all relations while - * marking the publication as ALL TABLES publication. + * For ALTER PUBLICATION, invalidation is needed when adding an EXCEPT + * table to either a FOR ALL TABLES publication (pub->alltables is true) + * or a FOR TABLES IN SCHEMA publication (is_schema_publication is true). + * The exception: when a publication is being converted to FOR ALL TABLES + * (pub->alltables is still false at this point), + * AlterPublicationAllFlags() will perform a full invalidation, so we skip + * it here. */ - inval_except_table = (alter_stmt != NULL) && pub->alltables && - (alter_stmt->for_all_tables && pri->except); + inval_except_table = (alter_stmt != NULL) && pri->except && + (pub->alltables + ? alter_stmt->for_all_tables + : is_schema_publication(pubid)); if (!pri->except || inval_except_table) { diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index b8d2d8e03f2..f6d57f3eb76 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -70,6 +70,13 @@ static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok); static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); +static void AlterPublicationSchemas(AlterPublicationStmt *stmt, + HeapTuple tup, List *schemaidlist, + List *except_pubtables); +static void AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, + List *except_pubtables, + List *schemaidlist); static char defGetGeneratedColsOption(DefElem *def); @@ -1500,7 +1507,8 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, */ static void AlterPublicationSchemas(AlterPublicationStmt *stmt, - HeapTuple tup, List *schemaidlist) + HeapTuple tup, List *schemaidlist, + List *except_pubtables) { Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); @@ -1577,6 +1585,97 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, */ PublicationAddSchemas(pubform->oid, schemaidlist, true, stmt); } + + /* + * Increment the command counter so that is_schema_publication() in + * GetExcludedPublicationTables() can see the just-inserted schema + * rows when AlterPublicationSchemaExceptTables runs next. + */ + if (stmt->action == AP_AddObjects || stmt->action == AP_SetObjects) + CommandCounterIncrement(); + + AlterPublicationSchemaExceptTables(stmt, tup, except_pubtables, schemaidlist); +} + +/* + * Alter the EXCEPT list of a schema-level publication. + * + * Adds, removes, or replaces except-table entries in pg_publication_rel + * (rows with prexcept = true). These entries suppress publication of the + * named tables that would otherwise be covered by a FOR TABLES IN SCHEMA + * clause. + */ +static void +AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, List *except_pubtables, + List *schemaidlist) +{ + Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); + Oid pubid = pubform->oid; + + /* + * Nothing to do if no EXCEPT entries. + */ + if (!except_pubtables) + return; + + /* + * This function handles EXCEPT entries for schema-level publications + * only. For FOR ALL TABLES publications, EXCEPT entries are already + * processed by AlterPublicationTables(). + */ + if (schemaidlist == NIL && !is_schema_publication(pubid)) + return; + + /* + * Dropping a schema from a publication removes all its EXCEPT entries via + * cascade. The concept of "drop all schema tables from the publication + * EXCEPT these ones" is not supported. + */ + if (stmt->action == AP_DropObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); + + /* + * XXX EXCEPT with SET is not currently implemented. Workaround: DROP and + * re-ADD the schema with the desired EXCEPT list. + */ + if (stmt->action == AP_SetObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"), + errhint("Drop and re-add the schema with the desired EXCEPT list."))); + + if (stmt->action == AP_AddObjects) + { + List *rels; + List *explicitrelids; + + rels = OpenTableList(except_pubtables); + + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + /* + * Validate that each excluded table is not also in the explicit table + * list (which would be contradictory). + */ + foreach_ptr(PublicationRelInfo, pri, rels) + { + Oid relid = RelationGetRelid(pri->relation); + + if (list_member_oid(explicitrelids, relid)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" cannot appear in both the table list and the EXCEPT clause", + RelationGetQualifiedRelationName(pri->relation))); + } + + PublicationAddTables(pubid, rels, false, stmt); + + CloseTableList(rels); + } } /* @@ -1786,10 +1885,12 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) errmsg("publication \"%s\" does not exist", stmt->pubname)); - relations = list_concat(relations, except_pubtables); + if (stmt->for_all_tables) + relations = list_concat(relations, except_pubtables); + AlterPublicationTables(stmt, tup, relations, pstate->p_sourcetext, schemaidlist != NIL); - AlterPublicationSchemas(stmt, tup, schemaidlist); + AlterPublicationSchemas(stmt, tup, schemaidlist, except_pubtables); AlterPublicationAllFlags(stmt, rel, tup); } diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c index a0f7f8e2168..85ab3b00875 100644 --- a/src/bin/pg_dump/pg_dump.c +++ b/src/bin/pg_dump/pg_dump.c @@ -5019,6 +5019,7 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) PublicationInfo *pubinfo = pubsinfo->publication; PQExpBuffer query; char *tag; + bool has_except = false; /* Do nothing if not dumping schema */ if (!dopt->dumpSchema) @@ -5029,7 +5030,34 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) query = createPQExpBuffer(); appendPQExpBuffer(query, "ALTER PUBLICATION %s ", fmtId(pubinfo->dobj.name)); - appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s;\n", fmtId(schemainfo->dobj.name)); + appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s", fmtId(schemainfo->dobj.name)); + + /* + * Append EXCEPT clause for any tables that belong to this schema + * and are excluded from the publication. + */ + for (SimplePtrListCell *cell = pubinfo->except_tables.head; cell; cell = cell->next) + { + TableInfo *tbinfo = (TableInfo *) cell->ptr; + + if (strcmp(tbinfo->dobj.namespace->dobj.name, schemainfo->dobj.name) == 0) + { + if (!has_except) + { + appendPQExpBufferStr(query, " EXCEPT ("); + has_except = true; + } + else + appendPQExpBufferStr(query, ", "); + + appendPQExpBuffer(query, "TABLE ONLY %s", fmtId(tbinfo->dobj.name)); + } + } + + if (has_except) + appendPQExpBufferStr(query, ")"); + + appendPQExpBufferStr(query, ";\n"); /* * There is no point in creating drop query as the drop is done by schema diff --git a/src/bin/pg_dump/t/002_pg_dump.pl b/src/bin/pg_dump/t/002_pg_dump.pl index 3ee9fda50e4..b8f4aa769ec 100644 --- a/src/bin/pg_dump/t/002_pg_dump.pl +++ b/src/bin/pg_dump/t/002_pg_dump.pl @@ -3242,6 +3242,30 @@ my %tests = ( like => { %full_runs, section_post_data => 1, }, }, + 'CREATE PUBLICATION pub11' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub11 FOR TABLES IN SCHEMA dump_test EXCEPT (TABLE test_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub11 WITH (publish = 'insert, update, delete, truncate');\E + .*? + \QALTER PUBLICATION pub11 ADD TABLES IN SCHEMA dump_test EXCEPT (TABLE ONLY test_table);\E + /xms, + like => { %full_runs, section_post_data => 1, }, + }, + + 'CREATE PUBLICATION pub12' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub12 FOR TABLES IN SCHEMA dump_test EXCEPT (TABLE test_table, dump_test.test_second_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub12 WITH (publish = 'insert, update, delete, truncate');\E + .*? + \QALTER PUBLICATION pub12 ADD TABLES IN SCHEMA dump_test EXCEPT (TABLE ONLY test_table, TABLE ONLY test_second_table);\E + /xms, + like => { %full_runs, section_post_data => 1, }, + }, + 'CREATE SUBSCRIPTION sub1' => { create_order => 50, create_sql => 'CREATE SUBSCRIPTION sub1 diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index 53bb7c8679b..a290902d61e 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2373,6 +2373,23 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); + /* After a single schema name in ADD context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 6df42a60f9c..8b49239b574 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -564,12 +564,42 @@ CREATE PUBLICATION testpub_except_nokw ERROR: syntax error at or near "testpub_nopk" LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); ^ +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; +-- fail: non-existing table in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- fail: EXCEPT table belongs to a different schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 1: ...xcept ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.tes... + ^ +-- fail: TABLE keyword is required for the first entry in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +ERROR: syntax error at or near "testpub_nopk" +LINE 1: ...lter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_no... + ^ +-- ADD: qualified and unqualified names; unqualified is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + "pub_test.testpub_tbl_s2" + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP TABLE pub_test.testpub_parted_s CASCADE; DROP TABLE testpub_nopk, testpub_tbl_s1; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi, testpub_alter_except; --------------------------------------------- -- Tests for publications with SEQUENCES --------------------------------------------- diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index bd523e376b2..e9387418904 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -278,12 +278,30 @@ CREATE PUBLICATION testpub_except_partition CREATE PUBLICATION testpub_except_nokw FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; + +-- fail: non-existing table in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- fail: EXCEPT table belongs to a different schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- fail: TABLE keyword is required for the first entry in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + +-- ADD: qualified and unqualified names; unqualified is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); +\dRp+ testpub_alter_except + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP TABLE pub_test.testpub_parted_s CASCADE; DROP TABLE testpub_nopk, testpub_tbl_s1; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi, testpub_alter_except; --------------------------------------------- -- Tests for publications with SEQUENCES diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 18c7b2c1fca..0ba6d6f8bb2 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -347,6 +347,38 @@ is($result, qq(5), $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); +# ============================================ +# ALTER PUBLICATION EXCEPT for TABLES IN SCHEMA +# ============================================ + +# Truncate subscriber tables to remove data accumulated from previous tests. +$node_subscriber->safe_psql('postgres', + 'TRUNCATE sch1.tab_published, sch1.tab_excluded, sch1.parent, sch1.child'); + +# ADD: add a schema with an excepted table; verify the except entry takes effect. +$node_publisher->safe_psql('postgres', "CREATE PUBLICATION sch_pub"); +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub ADD TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_excluded)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(6), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: included table synced'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + # Cleanup schema tables before the multi-publication section. $node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); $node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); -- 2.50.1 (Apple Git-155)
v10-0003-Add-EXCEPT-support-to-ALTER-PUBLICATION-SET-TABL.patch (application/octet-stream, 26.1K) download From 4b35cf5641b05d0fac9580d77178ada3a5ead8fd Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Tue, 2 Jun 2026 11:39:36 +0530 Subject: [PATCH v10 3/3] Add EXCEPT support to ALTER PUBLICATION SET TABLES IN SCHEMA Extend AlterPublicationExceptTables() with the AP_SetObjects case, which redefines the publication and replaces the entire EXCEPT list. Syntax: ALTER PUBLICATION pub SET TABLES IN SCHEMA s EXCEPT (TABLE t1); This patch also cleans up EXCEPT entries when a schema is dropped from the publication. --- doc/src/sgml/ref/alter_publication.sgml | 27 +++- src/backend/commands/publicationcmds.c | 135 +++++++++++++++++--- src/backend/replication/pgoutput/pgoutput.c | 10 +- src/bin/psql/tab-complete.in.c | 17 +++ src/test/regress/expected/publication.out | 86 +++++++++++++ src/test/regress/sql/publication.sql | 38 ++++++ src/test/subscription/t/037_except.pl | 85 ++++++++++++ 7 files changed, 371 insertions(+), 27 deletions(-) diff --git a/doc/src/sgml/ref/alter_publication.sgml b/doc/src/sgml/ref/alter_publication.sgml index 73f6375a66f..80b038e4b2e 100644 --- a/doc/src/sgml/ref/alter_publication.sgml +++ b/doc/src/sgml/ref/alter_publication.sgml @@ -97,7 +97,11 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r used with a publication defined with <literal>FOR TABLE</literal> or <literal>FOR TABLES IN SCHEMA</literal>, replaces the list of tables/schemas in the publication with the specified list; the existing tables or schemas - that were present in the publication will be removed. + that were present in the publication will be removed. When + <literal>SET TABLES IN SCHEMA</literal> is used with an + <literal>EXCEPT</literal> clause, the excluded tables for each schema are + replaced with the specified list; if <literal>EXCEPT</literal> is omitted + for a schema, any existing exclusions for that schema are cleared. </para> <para> @@ -116,10 +120,8 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <para> The <literal>EXCEPT</literal> clause can be used with - <literal>ADD TABLES IN SCHEMA</literal> to exclude specific tables from the - publication. Using <literal>DROP TABLES IN SCHEMA</literal> on a publication - will automatically also remove any associated <literal>EXCEPT</literal> - entries. + <literal>ADD TABLES IN SCHEMA</literal> to exclude specific tables from a + schema-level publication. </para> <para> @@ -214,7 +216,8 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <term><literal>EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] )</literal></term> <listitem> <para> - When used with <literal>ADD TABLES IN SCHEMA</literal>, specifies + When used with <literal>ADD TABLES IN SCHEMA</literal> + or <literal>SET TABLES IN SCHEMA</literal>, specifies tables to be excluded from the publication. Each named table must belong to the schema specified in the same <literal>TABLES IN SCHEMA</literal> clause. Table names may be @@ -326,6 +329,18 @@ ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA sales EXCEPT (TABLE int </programlisting> </para> + <para> + Replace the schema list of <structname>sales_publication</structname> with + <structname>sales</structname>, excluding only + <structname>sales.drafts</structname>. Other than + <structname>sales.drafts</structname>, any previously excluded tables for schema + <structname>sales</structname> are no longer excluded. Any schemas previously in + <structname>sales_publication</structname> are removed: +<programlisting> +ALTER PUBLICATION sales_publication SET TABLES IN SCHEMA sales EXCEPT (TABLE drafts); +</programlisting> + </para> + <para> Add tables <structname>users</structname>, <structname>departments</structname> and schema diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index f6d57f3eb76..c899c8c0e06 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -1588,8 +1588,8 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, /* * Increment the command counter so that is_schema_publication() in - * GetExcludedPublicationTables() can see the just-inserted schema - * rows when AlterPublicationSchemaExceptTables runs next. + * GetExcludedPublicationTables() can see the just-inserted schema rows + * when AlterPublicationSchemaExceptTables runs next. */ if (stmt->action == AP_AddObjects || stmt->action == AP_SetObjects) CommandCounterIncrement(); @@ -1607,16 +1607,18 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, */ static void AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, - HeapTuple tup, List *except_pubtables, - List *schemaidlist) + HeapTuple tup, List *except_pubtables, + List *schemaidlist) { Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); Oid pubid = pubform->oid; /* - * Nothing to do if no EXCEPT entries. + * Nothing to do if there are no EXCEPT entries, unless handling the SET + * command, because if the user has removed all exceptions we need to drop + * any existing ones. */ - if (!except_pubtables) + if (!except_pubtables && stmt->action != AP_SetObjects) return; /* @@ -1637,16 +1639,6 @@ AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); - /* - * XXX EXCEPT with SET is not currently implemented. Workaround: DROP and - * re-ADD the schema with the desired EXCEPT list. - */ - if (stmt->action == AP_SetObjects) - ereport(ERROR, - (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"), - errhint("Drop and re-add the schema with the desired EXCEPT list."))); - if (stmt->action == AP_AddObjects) { List *rels; @@ -1674,6 +1666,84 @@ AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, PublicationAddTables(pubid, rels, false, stmt); + CloseTableList(rels); + } + else /* AP_SetObjects */ + { + List *oldexceptrelids = NIL; + List *newexceptrelids = NIL; + List *delrelids = NIL; + List *rels; + List *explicitrelids; + + rels = OpenTableList(except_pubtables); + + /* Collect OIDs of the desired new EXCEPT list. */ + foreach_ptr(PublicationRelInfo, pri, rels) + newexceptrelids = lappend_oid(newexceptrelids, + RelationGetRelid(pri->relation)); + + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + /* + * Validate that each excluded table is not also in the explicit table + * list (which would be contradictory). + */ + foreach_ptr(PublicationRelInfo, pri, rels) + { + Oid relid = RelationGetRelid(pri->relation); + + if (list_member_oid(explicitrelids, relid)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" cannot appear in both the table list and the EXCEPT clause", + RelationGetQualifiedRelationName(pri->relation))); + } + + /* + * Get the current set of EXCEPT entries. Only FOR ALL TABLES and + * schema-level publications can have EXCEPT entries; for any other + * publication type oldexceptrelids stays NIL. + * + * Note: we check is_schema_publication() against the current catalog + * state (before AlterPublicationSchemas has run), so if the caller is + * doing SET TABLE t1 to convert a schema publication into a plain + * table publication, is_schema_publication() still returns true here. + * That is intentional: it lets us discover and clean up any stale + * EXCEPT entries that belong to the old schema definition. + */ + if (GetPublication(pubid)->alltables || is_schema_publication(pubid)) + oldexceptrelids = GetExcludedPublicationTables(pubid, + PUBLICATION_PART_ROOT); + + /* Build a list of old EXCEPT entries not present in the new list. */ + foreach_oid(oldrelid, oldexceptrelids) + { + if (!list_member_oid(newexceptrelids, oldrelid)) + delrelids = lappend_oid(delrelids, oldrelid); + } + + /* Drop old EXCEPT entries not present in the new list. */ + foreach_oid(relid, delrelids) + { + Oid proid; + ObjectAddress obj; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + /* Add new EXCEPT entries, skipping any already present. */ + PublicationAddTables(pubid, rels, true, stmt); + CloseTableList(rels); } } @@ -2323,6 +2393,7 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) foreach(lc, schemas) { Oid schemaid = lfirst_oid(lc); + List *except_relids; psid = GetSysCacheOid2(PUBLICATIONNAMESPACEMAP, Anum_pg_publication_namespace_oid, @@ -2339,8 +2410,40 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) get_namespace_name(schemaid)))); } + /* + * Collect EXCEPT entries for tables belonging to this schema before + * removing the schema entry. + */ + except_relids = GetExcludedPublicationTables(pubid, PUBLICATION_PART_ROOT); + ObjectAddressSet(obj, PublicationNamespaceRelationId, psid); performDeletion(&obj, DROP_CASCADE, 0); + + /* + * Drop any prexcept rows for tables belonging to this schema. These + * rows have no pg_depend entry pointing at the + * pg_publication_namespace row, so they are not cascaded by the + * performDeletion() call above and must be cleaned up explicitly. + */ + foreach_oid(relid, except_relids) + { + Oid proid; + + if (get_rel_namespace(relid) != schemaid) + continue; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + list_free(except_relids); } } diff --git a/src/backend/replication/pgoutput/pgoutput.c b/src/backend/replication/pgoutput/pgoutput.c index 7ee84ec1c83..9831be54b47 100644 --- a/src/backend/replication/pgoutput/pgoutput.c +++ b/src/backend/replication/pgoutput/pgoutput.c @@ -2229,7 +2229,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) */ if (pub->alltables) { - List *exceptpubids = NIL; + List *except_pubids = NIL; if (am_partition) { @@ -2252,7 +2252,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) * clause. Therefore, for a partition, exclusion must be * evaluated at the top-most ancestor. */ - exceptpubids = GetRelationExcludedPublications(last_ancestor_relid); + except_pubids = GetRelationExcludedPublications(last_ancestor_relid); } else { @@ -2260,13 +2260,13 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) * For a regular table or a root partitioned table, check * exclusion on table itself. */ - exceptpubids = GetRelationExcludedPublications(pub_relid); + except_pubids = GetRelationExcludedPublications(pub_relid); } - if (!list_member_oid(exceptpubids, pub->oid)) + if (!list_member_oid(except_pubids, pub->oid)) publish = true; - list_free(exceptpubids); + list_free(except_pubids); if (!publish) continue; diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index a290902d61e..e8bfb36cb1c 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2390,6 +2390,23 @@ match_previous_words(int pattern_id, } else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) COMPLETE_WITH(")"); + /* After a single schema name in SET context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 8b49239b574..35db7e1ff6d 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -594,6 +594,92 @@ Except tables: "pub_test.testpub_tbl_s1" "pub_test.testpub_tbl_s2" +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s2" + +-- fail: table in EXCEPT clause also appears in the explicit table list +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot appear in both the table list and the EXCEPT clause +-- error: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 1: ...xcept SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.tes... + ^ +-- SET: unqualified name in EXCEPT is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- SET without EXCEPT clears the existing except list +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + +-- SET to a different schema removes old schema's EXCEPT entries +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA public; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "public" + +-- fail: nonexistent table in EXCEPT clause (SET path) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- SET: multiple schemas each with their own EXCEPT clause +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- error: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +ERROR: EXCEPT clause is not supported with DROP in ALTER PUBLICATION +-- DROP TABLES IN SCHEMA removes associated EXCEPT entries +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "public" +Except tables: + "public.testpub_tbl1" + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index e9387418904..9b714639c75 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -296,6 +296,44 @@ ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (tes ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); \dRp+ testpub_alter_except +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + +-- fail: table in EXCEPT clause also appears in the explicit table list +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- error: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- SET: unqualified name in EXCEPT is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +\dRp+ testpub_alter_except + +-- SET without EXCEPT clears the existing except list +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + +-- SET to a different schema removes old schema's EXCEPT entries +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA public; +\dRp+ testpub_alter_except + +-- fail: nonexistent table in EXCEPT clause (SET path) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- SET: multiple schemas each with their own EXCEPT clause +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_alter_except + +-- error: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); + +-- DROP TABLES IN SCHEMA removes associated EXCEPT entries +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 0ba6d6f8bb2..01eafb5b7c8 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -376,6 +376,61 @@ $result = is($result, qq(0), 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); +# SET: replace the except list; tab_excluded is now included and tab_published is excluded. +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_published)" +); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (7); + INSERT INTO sch1.tab_excluded VALUES (7); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded WHERE a = 7"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: newly included table is replicated' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published WHERE a = 7"); +is($result, qq(0), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: now-excluded table is not replicated' +); + +# SET without EXCEPT: clears the except list; both tables are now published. +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1"); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (8); + INSERT INTO sch1.tab_excluded VALUES (8); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published WHERE a = 8"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_published replicated after except list cleared' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded WHERE a = 8"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_excluded replicated after except list cleared' +); + $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); @@ -443,6 +498,36 @@ $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); +# OK when a table is excluded by a TABLES IN SCHEMA EXCEPT publication, +# but is included by another publication. +$node_publisher->safe_psql('postgres', 'TRUNCATE tab1'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE tab1'); + +$node_publisher->safe_psql( + 'postgres', qq( + CREATE PUBLICATION tap_pub1 FOR TABLES IN SCHEMA public EXCEPT (TABLE public.tab1); + CREATE PUBLICATION tap_pub2 FOR TABLE tab1; + INSERT INTO tab1 VALUES(1); +)); +$node_subscriber->psql('postgres', + "CREATE SUBSCRIPTION tap_sub CONNECTION '$publisher_connstr' PUBLICATION tap_pub1, tap_pub2" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'tap_sub'); + +$node_publisher->safe_psql('postgres', qq(INSERT INTO tab1 VALUES(2))); +$node_publisher->wait_for_catchup('tap_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT * FROM tab1 ORDER BY a"); +is( $result, qq(1 +2), + "TABLES IN SCHEMA EXCEPT: table excluded in schema pub but included by another pub is replicated" +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); + $node_publisher->stop('fast'); done_testing(); -- 2.50.1 (Apple Git-155)
^ permalink raw reply [nested|flat] 196+ messages in thread

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-06-06 20:39  Zsolt Parragi <zsolt.parragi@percona.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: Zsolt Parragi @ 2026-06-06 20:39 UTC (permalink / raw)
  To: pgsql-hackers@lists.postgresql.org

Hello!

Thanks, I can confirm the fixes work.

I did some more testing. I think I see two problems with ALTER TABLE
... SET SCHEMA:

1.

CREATE SCHEMA s;
CREATE SCHEMA other;
CREATE TABLE s.t(i int);
CREATE PUBLICATION p FOR TABLES IN SCHEMA s EXCEPT (TABLE s.t);
ALTER TABLE s.t SET SCHEMA other;
ALTER PUBLICATION p ADD TABLES IN SCHEMA other;
-- shouldn't s.t be there?
SELECT schemaname, tablename FROM pg_publication_tables WHERE
pubname='p' ORDER BY 1,2;


2.

CREATE SCHEMA s;
CREATE SCHEMA other;
CREATE TABLE s.t(i int);
CREATE PUBLICATION p FOR TABLES IN SCHEMA s EXCEPT (TABLE s.t);
ALTER TABLE s.t SET SCHEMA other;
ALTER PUBLICATION p DROP TABLES IN SCHEMA s;
-- should it still be there? it isn't without the alter set schema
SELECT pr.prrelid::regclass AS rel, pub.pubname, pr.prexcept
FROM pg_publication_rel pr JOIN pg_publication pub ON pub.oid=pr.prpubid;





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-06-09 16:21  Nisha Moond <nisha.moond412@gmail.com>
  parent: Zsolt Parragi <zsolt.parragi@percona.com>
  0 siblings, 2 replies; 196+ messages in thread

From: Nisha Moond @ 2026-06-09 16:21 UTC (permalink / raw)
  To: Zsolt Parragi <zsolt.parragi@percona.com>; +Cc: pgsql-hackers@lists.postgresql.org

 On Sun, Jun 7, 2026 at 2:09 AM Zsolt Parragi <zsolt.parragi@percona.com> wrote:
>
> Hello!
>
> Thanks, I can confirm the fixes work.
>
> I did some more testing. I think I see two problems with ALTER TABLE
> ... SET SCHEMA:
>

Thanks for reporting this case.

The current patches did not handle schema changes for excluded tables.
Hou-san also reported the same design issue off-list to me.

After considering, I chose to follow behavior similar to existing FOR
ALL TABLES publications to handle schema-switch cases. Today, if a
table excluded via EXCEPT is dropped, the corresponding prexcept entry
is removed, and recreating a table with the same name does not
automatically restore the exclusion.

I applied the same principle to schema changes: once an excluded table
moves out of the schema, the exclusion is removed.

For example, consider the following cases:
CREATE PUBLICATION p FOR TABLES IN SCHEMA s1 EXCEPT (TABLE s1.t);

case-1: Table moves from s1 to s2:  ALTER TABLE s1.t SET SCHEMA s2;
-- The exclusion entry s1.t is removed.

case-2: Table moves back from s2 to s1:  ALTER TABLE s2.t SET SCHEMA s1;
-- The table is published again. The exclusion is not restored
automatically; the user must specify it again.

case-3: If s2 is also part of publication p
 -- The behavior remains the same. Moving the table between schemas
does not recreate the exclusion entry.

IOW, once the exclusion is broken by a schema move (similar to a
drop), it must be re-established explicitly by the user.

The attached patch implements this behavior. I've also updated the
docs to describe it.

I also considered two alternatives:
1) Reject the schema change: Error out if a table with a prexcept
entry is moved between schemas. This feels overly restrictive.
2) Make exclusions schema-aware: Add a prexceptschema column and store
the schema OID along with the exclusion entry. The exclusion would
only apply while the table remains in that schema, allowing it to be
restored automatically if the table moves back later. IMO it
complicates the design.

Thoughts?

> 1.
>
> CREATE SCHEMA s;
> CREATE SCHEMA other;
> CREATE TABLE s.t(i int);
> CREATE PUBLICATION p FOR TABLES IN SCHEMA s EXCEPT (TABLE s.t);
> ALTER TABLE s.t SET SCHEMA other;
> ALTER PUBLICATION p ADD TABLES IN SCHEMA other;
> -- shouldn't s.t be there?
> SELECT schemaname, tablename FROM pg_publication_tables WHERE
> pubname='p' ORDER BY 1,2;
>

Do you mean other.t should be there?
This is now fixed. When t is moved to schema other, the exclusion is
removed and the table is published through p.

postgres=# SELECT schemaname, tablename FROM pg_publication_tables
WHERE pubname='p' ORDER BY 1,2;
 schemaname | tablename
------------+-----------
 other      | t

>
> 2.
>
> CREATE SCHEMA s;
> CREATE SCHEMA other;
> CREATE TABLE s.t(i int);
> CREATE PUBLICATION p FOR TABLES IN SCHEMA s EXCEPT (TABLE s.t);
> ALTER TABLE s.t SET SCHEMA other;
> ALTER PUBLICATION p DROP TABLES IN SCHEMA s;
> -- should it still be there? it isn't without the alter set schema
> SELECT pr.prrelid::regclass AS rel, pub.pubname, pr.prexcept
> FROM pg_publication_rel pr JOIN pg_publication pub ON pub.oid=pr.prpubid;
>

Fixed.
Now, when s.t is moved out of schema s, it is removed from publication
p's exclusion list. Later, if schema s is dropped from publication p,
the exclusion entries associated with s are removed as well, and s.t
is no longer present there.

Attached are the updated v11 patches.
Patch 001 has the changes discussed above; patches 002 and 003 are unchanged.

--
Thanks,
Nisha

Attachments: download all (3 files, .tar.gz)

v11-0001-Support-EXCEPT-clause-for-schema-level-publicati.patch (application/octet-stream, 63.3K) download From a0e1315820ca7f62f9b78c1f5e121d8f22d0310f Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Mon, 4 May 2026 12:49:27 +0530 Subject: [PATCH v11 1/3] Support EXCEPT clause for schema-level publications Extend table exclusion support in publications to allow specific tables to be excluded from schema-level publications using an EXCEPT clause in CREATE PUBLICATION. Supported syntax: CREATE PUBLICATION <pub> FOR TABLES IN SCHEMA s EXCEPT (TABLE t1,...); --- doc/src/sgml/logical-replication.sgml | 3 +- doc/src/sgml/ref/create_publication.sgml | 35 ++++- src/backend/catalog/pg_publication.c | 161 ++++++++++++++++---- src/backend/commands/publicationcmds.c | 136 +++++++++++++++-- src/backend/commands/tablecmds.c | 10 ++ src/backend/parser/gram.y | 55 ++++++- src/backend/replication/pgoutput/pgoutput.c | 30 +++- src/bin/psql/describe.c | 18 +++ src/bin/psql/tab-complete.in.c | 35 ++++- src/include/catalog/pg_publication.h | 3 +- src/include/commands/publicationcmds.h | 1 + src/include/nodes/parsenodes.h | 2 + src/test/regress/expected/publication.out | 144 ++++++++++++++++- src/test/regress/sql/publication.sql | 88 ++++++++++- src/test/subscription/t/037_except.pl | 133 +++++++++++++++- 15 files changed, 797 insertions(+), 57 deletions(-) diff --git a/doc/src/sgml/logical-replication.sgml b/doc/src/sgml/logical-replication.sgml index 9e7868487de..1433d2660fe 100644 --- a/doc/src/sgml/logical-replication.sgml +++ b/doc/src/sgml/logical-replication.sgml @@ -117,7 +117,8 @@ or <literal>FOR ALL SEQUENCES</literal>. Unlike tables, sequences can be synchronized at any time. For more information, see <xref linkend="logical-replication-sequences"/>. When a publication is - created with <literal>FOR ALL TABLES</literal>, a table or set of tables can + created with <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal>, a table or set of tables can be explicitly excluded from publication using the <link linkend="sql-createpublication-params-for-except-table"><literal>EXCEPT</literal></link> clause. diff --git a/doc/src/sgml/ref/create_publication.sgml b/doc/src/sgml/ref/create_publication.sgml index f82d640e6ca..199460c3bb6 100644 --- a/doc/src/sgml/ref/create_publication.sgml +++ b/doc/src/sgml/ref/create_publication.sgml @@ -28,7 +28,7 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA <replaceable class="parameter">tables_in_schema</replaceable> [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -39,6 +39,10 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <replaceable class="parameter">table_object</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] [ WHERE ( <replaceable class="parameter">expression</replaceable> ) ] +<phrase>and <replaceable class="parameter">tables_in_schema</replaceable> is:</phrase> + + { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] + <phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> TABLE <replaceable class="parameter">table_object</replaceable> [, ... ] @@ -142,6 +146,8 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <para> Marks the publication as one that replicates changes for all tables in the specified list of schemas, including tables created in the future. + Tables listed in the <literal>EXCEPT</literal> clause for a given schema + are excluded from the publication. </para> <para> @@ -173,7 +179,7 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <para> Marks the publication as one that replicates changes for all tables in the database, including tables created in the future. Tables listed in - <literal>EXCEPT</literal> clause are excluded from the publication. + the <literal>EXCEPT</literal> clause are excluded from the publication. </para> </listitem> </varlistentry> @@ -198,7 +204,8 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <listitem> <para> This clause specifies a list of tables to be excluded from the - publication. + publication. It can be used with <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal>. </para> <para> For inherited tables, if <literal>ONLY</literal> is specified before the @@ -221,6 +228,19 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> but excluded (explicitly or implicitly) by the <literal>EXCEPT</literal> clause of another is considered included for replication. </para> + <para> + For <literal>FOR TABLES IN SCHEMA</literal> publications, the + <literal>EXCEPT</literal> clause is schema-scoped: the exclusion applies + only in the context of the schema to which it was attached. If a table + listed in the <literal>EXCEPT</literal> clause is later moved to a + different schema using <command>ALTER TABLE ... SET SCHEMA</command>, + the exclusion is removed. The table will then be published if its new + schema is part of a publication. If the table is moved back to + the original schema, the exclusion is not restored; the user must + re-establish it explicitly using <command>ALTER PUBLICATION</command>. + Dropping a table always removes it from the <literal>EXCEPT</literal> + list regardless of publication type. + </para> </listitem> </varlistentry> @@ -515,6 +535,15 @@ CREATE PUBLICATION production_publication FOR TABLE users, departments, TABLES I CREATE PUBLICATION sales_publication FOR TABLES IN SCHEMA marketing, sales; </programlisting></para> + <para> + Create a publication that publishes all changes for all the tables present in + the schema <structname>sales</structname>, except + <structname>internal</structname> and <structname>drafts</structname>: +<programlisting> +CREATE PUBLICATION sales_filtered FOR TABLES IN SCHEMA sales EXCEPT (TABLE internal, drafts); +</programlisting> + </para> + <para> Create a publication that publishes all changes for table <structname>users</structname>, but replicates only columns <structname>user_id</structname> and diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index 5c457d9aca8..4089b505f89 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -444,13 +444,19 @@ GetPubPartitionOptionRelations(List *result, PublicationPartOpt pub_partopt, * * Note that the list of ancestors should be ordered such that the topmost * ancestor is at the end of the list. + * + * except_pubids is a list of publication OIDs whose schema membership + * should be ignored for the ancestor (because the ancestor is in their + * EXCEPT clause). */ Oid -GetTopMostAncestorInPublication(Oid puboid, List *ancestors, int *ancestor_level) +GetTopMostAncestorInPublication(Oid puboid, List *ancestors, + int *ancestor_level, List *except_pubids) { ListCell *lc; Oid topmost_relid = InvalidOid; int level = 0; + bool check_schemas = !list_member_oid(except_pubids, puboid); /* * Find the "topmost" ancestor that is in this publication. @@ -470,7 +476,7 @@ GetTopMostAncestorInPublication(Oid puboid, List *ancestors, int *ancestor_level if (ancestor_level) *ancestor_level = level; } - else + else if (check_schemas) { aschemaPubids = GetSchemaPublications(get_rel_namespace(ancestor)); if (list_member_oid(aschemaPubids, puboid)) @@ -545,18 +551,30 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, * duplicates, it's here just to provide nicer error message in common * case. The real protection is the unique key on the catalog. */ - if (SearchSysCacheExists2(PUBLICATIONRELMAP, ObjectIdGetDatum(relid), - ObjectIdGetDatum(pubid))) + tup = SearchSysCache2(PUBLICATIONRELMAP, ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + + if (HeapTupleIsValid(tup)) { + bool is_except = ((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept; + + ReleaseSysCache(tup); table_close(rel, RowExclusiveLock); if (if_not_exists) return InvalidObjectAddress; - ereport(ERROR, - (errcode(ERRCODE_DUPLICATE_OBJECT), - errmsg("relation \"%s\" is already member of publication \"%s\"", - RelationGetRelationName(targetrel), pub->name))); + if (is_except) + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("table \"%s\" cannot be added because it is excluded from publication \"%s\"", + RelationGetQualifiedRelationName(targetrel), + pub->name))); + else + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("relation \"%s\" is already member of publication \"%s\"", + RelationGetRelationName(targetrel), pub->name))); } check_publication_add_relation(pri); @@ -982,12 +1000,13 @@ GetIncludedPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) * Gets list of table oids that were specified in the EXCEPT clause for a * publication. * - * This should only be used FOR ALL TABLES publications. + * This is used for FOR ALL TABLES and FOR TABLES IN SCHEMA publications, + * both of which support EXCEPT TABLE. */ List * GetExcludedPublicationTables(Oid pubid, PublicationPartOpt pub_partopt) { - Assert(GetPublication(pubid)->alltables); + Assert(GetPublication(pubid)->alltables || is_schema_publication(pubid)); return get_publication_relations(pubid, pub_partopt, true); } @@ -1049,15 +1068,15 @@ GetAllPublicationRelations(Oid pubid, char relkind, bool pubviaroot) TableScanDesc scan; HeapTuple tuple; List *result = NIL; - List *exceptlist = NIL; + List *except_relids = NIL; Assert(!(relkind == RELKIND_SEQUENCE && pubviaroot)); /* EXCEPT filtering applies only to relations, not sequences */ if (relkind == RELKIND_RELATION) - exceptlist = GetExcludedPublicationTables(pubid, pubviaroot ? - PUBLICATION_PART_ROOT : - PUBLICATION_PART_LEAF); + except_relids = GetExcludedPublicationTables(pubid, pubviaroot ? + PUBLICATION_PART_ROOT : + PUBLICATION_PART_LEAF); classRel = table_open(RelationRelationId, AccessShareLock); @@ -1075,7 +1094,7 @@ GetAllPublicationRelations(Oid pubid, char relkind, bool pubviaroot) if (is_publishable_class(relid, relForm) && !(relForm->relispartition && pubviaroot) && - !list_member_oid(exceptlist, relid)) + !list_member_oid(except_relids, relid)) result = lappend_oid(result, relid); } @@ -1097,7 +1116,7 @@ GetAllPublicationRelations(Oid pubid, char relkind, bool pubviaroot) if (is_publishable_class(relid, relForm) && !relForm->relispartition && - !list_member_oid(exceptlist, relid)) + !list_member_oid(except_relids, relid)) result = lappend_oid(result, relid); } @@ -1232,22 +1251,67 @@ GetSchemaPublicationRelations(Oid schemaid, PublicationPartOpt pub_partopt) /* * Gets the list of all relations published by FOR TABLES IN SCHEMA - * publication. + * publication, excluding any tables listed in the EXCEPT clause. */ List * GetAllSchemaPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) { List *result = NIL; List *pubschemalist = GetPublicationSchemas(pubid); + List *except_relids = NIL; ListCell *cell; + /* get the list of tables excluded via EXCEPT TABLE for this publication */ + if (pubschemalist != NIL) + except_relids = GetExcludedPublicationTables(pubid, pub_partopt); + foreach(cell, pubschemalist) { Oid schemaid = lfirst_oid(cell); List *schemaRels = NIL; schemaRels = GetSchemaPublicationRelations(schemaid, pub_partopt); - result = list_concat(result, schemaRels); + + if (except_relids != NIL) + { + /* filter out any tables that appear in the EXCEPT list */ + ListCell *rlc; + + foreach(rlc, schemaRels) + { + Oid relid = lfirst_oid(rlc); + bool excluded = list_member_oid(except_relids, relid); + + /* + * Also exclude any relation whose partition ancestor is in + * the EXCEPT list. This matters when pub_partopt is + * PUBLICATION_PART_ROOT: the except list holds only the root + * OID, but the schema scan may also return individual + * partition relations that live in the same schema. + */ + if (!excluded && get_rel_relispartition(relid)) + { + List *ancestors = get_partition_ancestors(relid); + ListCell *alc; + + foreach(alc, ancestors) + { + if (list_member_oid(except_relids, lfirst_oid(alc))) + { + excluded = true; + break; + } + } + list_free(ancestors); + } + + if (!excluded) + result = lappend_oid(result, relid); + } + list_free(schemaRels); + } + else + result = list_concat(result, schemaRels); } return result; @@ -1324,6 +1388,7 @@ is_table_publishable_in_publication(Oid relid, Publication *pub) { bool relispartition; List *ancestors = NIL; + HeapTuple tup; /* * For non-pubviaroot publications, a partitioned table is never the @@ -1380,20 +1445,62 @@ is_table_publishable_in_publication(Oid relid, Publication *pub) * If it's false, the partition is covered by its ancestor's presence in * the publication, it should be included (return true). */ - if (relispartition && - OidIsValid(GetTopMostAncestorInPublication(pub->oid, ancestors, NULL))) - return !pub->pubviaroot; + if (relispartition) + { + Oid ancestor_oid; + + ancestor_oid = GetTopMostAncestorInPublication(pub->oid, ancestors, NULL, NIL); + if (OidIsValid(ancestor_oid)) + { + /* + * The ancestor was found in the publication (via explicit + * membership or schema membership), but it may be excluded. Check + * for a prexcept row before concluding the partition is + * published. + */ + tup = SearchSysCache2(PUBLICATIONRELMAP, + ObjectIdGetDatum(ancestor_oid), + ObjectIdGetDatum(pub->oid)); + if (HeapTupleIsValid(tup)) + { + bool is_except; + + is_except = ((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept; + ReleaseSysCache(tup); + if (is_except) + return false; + } + return !pub->pubviaroot; + } + } /* * Check whether the table is explicitly published via pg_publication_rel * or pg_publication_namespace. + * + * A pg_publication_rel row with prexcept=true means the table is + * explicitly excluded via EXCEPT and must not be reported as published, + * even if its schema is otherwise included. A row with prexcept=false + * means it is explicitly included. If no pg_publication_rel row exists, + * the table is published iff its schema appears in + * pg_publication_namespace. */ - return (SearchSysCacheExists2(PUBLICATIONRELMAP, - ObjectIdGetDatum(relid), - ObjectIdGetDatum(pub->oid)) || - SearchSysCacheExists2(PUBLICATIONNAMESPACEMAP, - ObjectIdGetDatum(get_rel_namespace(relid)), - ObjectIdGetDatum(pub->oid))); + + tup = SearchSysCache2(PUBLICATIONRELMAP, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pub->oid)); + if (HeapTupleIsValid(tup)) + { + bool is_except; + + is_except = ((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept; + ReleaseSysCache(tup); + return !is_except; + } + + return SearchSysCacheExists2(PUBLICATIONNAMESPACEMAP, + ObjectIdGetDatum(get_rel_namespace(relid)), + ObjectIdGetDatum(pub->oid)); } /* diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 440adb356ad..876898aa487 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -181,7 +181,7 @@ parse_publication_options(ParseState *pstate, */ static void ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, - List **rels, List **exceptrels, List **schemas) + List **rels, List **except_pubtables, List **schemas) { ListCell *cell; PublicationObjSpec *pubobj; @@ -200,7 +200,7 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, { case PUBLICATIONOBJ_EXCEPT_TABLE: pubobj->pubtable->except = true; - *exceptrels = lappend(*exceptrels, pubobj->pubtable); + *except_pubtables = lappend(*except_pubtables, pubobj->pubtable); break; case PUBLICATIONOBJ_TABLE: pubobj->pubtable->except = false; @@ -224,6 +224,38 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, /* Filter out duplicates if user specifies "sch1, sch1" */ *schemas = list_append_unique_oid(*schemas, schemaid); + + /* + * Qualify unqualified EXCEPT table names with the resolved + * current schema and reject any explicitly cross-schema + * entries. This mirrors the parse-time handling done for + * TABLES_IN_SCHEMA in preprocess_pubobj_list(), deferred here + * because CURRENT_SCHEMA is not known until execution time. + */ + if (pubobj->except_tables != NIL) + { + char *cur_schema_name = get_namespace_name(schemaid); + + foreach_ptr(PublicationObjSpec, eobj, pubobj->except_tables) + { + const char *eobj_schemaname = + eobj->pubtable->relation->schemaname; + const char *eobj_relname = + eobj->pubtable->relation->relname; + + if (eobj_schemaname == NULL) + eobj->pubtable->relation->schemaname = cur_schema_name; + else if (strcmp(eobj_schemaname, cur_schema_name) != 0) + ereport(ERROR, + errcode(ERRCODE_INVALID_OBJECT_DEFINITION), + errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", + quote_qualified_identifier(eobj_schemaname, eobj_relname), + cur_schema_name)); + + *except_pubtables = lappend(*except_pubtables, + eobj->pubtable); + } + } break; default: /* shouldn't happen */ @@ -305,7 +337,7 @@ pub_rf_contains_invalid_column(Oid pubid, Relation relation, List *ancestors, if (pubviaroot && relation->rd_rel->relispartition) { publish_as_relid - = GetTopMostAncestorInPublication(pubid, ancestors, NULL); + = GetTopMostAncestorInPublication(pubid, ancestors, NULL, NIL); if (!OidIsValid(publish_as_relid)) publish_as_relid = relid; @@ -389,7 +421,7 @@ pub_contains_invalid_column(Oid pubid, Relation relation, List *ancestors, */ if (pubviaroot && relation->rd_rel->relispartition) { - publish_as_relid = GetTopMostAncestorInPublication(pubid, ancestors, NULL); + publish_as_relid = GetTopMostAncestorInPublication(pubid, ancestors, NULL, NIL); if (!OidIsValid(publish_as_relid)) publish_as_relid = relid; @@ -849,7 +881,7 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) char publish_generated_columns; AclResult aclresult; List *relations = NIL; - List *exceptrelations = NIL; + List *except_pubtables = NIL; List *schemaidlist = NIL; /* must have CREATE privilege on database */ @@ -936,16 +968,16 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) /* Associate objects with the publication. */ ObjectsInPublicationToOids(stmt->pubobjects, pstate, &relations, - &exceptrelations, &schemaidlist); + &except_pubtables, &schemaidlist); if (stmt->for_all_tables) { /* Process EXCEPT table list */ - if (exceptrelations != NIL) + if (except_pubtables != NIL) { List *rels; - rels = OpenTableList(exceptrelations); + rels = OpenTableList(except_pubtables); PublicationAddTables(puboid, rels, true, NULL); CloseTableList(rels); } @@ -959,6 +991,8 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) } else if (!stmt->for_all_sequences) { + List *explicitrelids = NIL; + /* FOR TABLES IN SCHEMA requires superuser */ if (schemaidlist != NIL && !superuser()) ereport(ERROR, @@ -977,6 +1011,19 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) schemaidlist != NIL, publish_via_partition_root); + /* + * Collect explicit table OIDs now, before we close the relation + * list, so that except-table validation below can check for + * contradictions without relying on a catalog scan that might not + * yet see the just-inserted rows. + */ + if (except_pubtables != NIL) + { + foreach_ptr(PublicationRelInfo, pri, rels) + explicitrelids = lappend_oid(explicitrelids, + RelationGetRelid(pri->relation)); + } + PublicationAddTables(puboid, rels, true, NULL); CloseTableList(rels); } @@ -989,6 +1036,34 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) */ LockSchemaList(schemaidlist); PublicationAddSchemas(puboid, schemaidlist, true, NULL); + + if (except_pubtables != NIL) + { + List *except_rels; + + except_rels = OpenTableList(except_pubtables); + + /* + * Validate that each excluded table is not also in the + * explicit table list (which would be contradictory). Use the + * in-memory explicitrelids collected above rather than + * re-reading the catalog, which may not yet see the + * just-inserted rows. + */ + foreach_ptr(PublicationRelInfo, pri, except_rels) + { + Oid except_relid = RelationGetRelid(pri->relation); + + if (list_member_oid(explicitrelids, except_relid)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" cannot appear in both the table list and the EXCEPT clause", + RelationGetQualifiedRelationName(pri->relation))); + } + + PublicationAddTables(puboid, except_rels, true, NULL); + CloseTableList(except_rels); + } } } @@ -1683,12 +1758,12 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) else { List *relations = NIL; - List *exceptrelations = NIL; + List *except_pubtables = NIL; List *schemaidlist = NIL; Oid pubid = pubform->oid; ObjectsInPublicationToOids(stmt->pubobjects, pstate, &relations, - &exceptrelations, &schemaidlist); + &except_pubtables, &schemaidlist); CheckAlterPublication(stmt, tup, relations, schemaidlist); @@ -1711,7 +1786,7 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) errmsg("publication \"%s\" does not exist", stmt->pubname)); - relations = list_concat(relations, exceptrelations); + relations = list_concat(relations, except_pubtables); AlterPublicationTables(stmt, tup, relations, pstate->p_sourcetext, schemaidlist != NIL); AlterPublicationSchemas(stmt, tup, schemaidlist); @@ -1829,6 +1904,45 @@ RemovePublicationSchemaById(Oid psoid) table_close(rel, RowExclusiveLock); } +/* + * Remove any EXCEPT clause entries for a relation from schema publications. + * Called when a table changes schema (ALTER TABLE ... SET SCHEMA), so that + * a schema-scoped exclusion does not silently follow the table to its new + * schema. FOR ALL TABLES publications are skipped because their EXCEPT + * clause is publication-scoped, not schema-scoped, so that exclusion should + * persist regardless of what schema the table is in. + */ +void +RemovePublicationExceptForRelation(Oid relid) +{ + List *pubids; + ListCell *lc; + ObjectAddress obj; + + pubids = GetRelationExcludedPublications(relid); + + foreach(lc, pubids) + { + Oid pubid = lfirst_oid(lc); + Oid proid; + + if (!is_schema_publication(pubid)) + continue; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + list_free(pubids); +} + /* * Open relations specified by a PublicationTable list. * The returned tables are locked in ShareUpdateExclusiveLock mode in order to diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index a33e22e8e61..3ae518fa1e3 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -63,6 +63,7 @@ #include "commands/event_trigger.h" #include "commands/extension.h" #include "commands/repack.h" +#include "commands/publicationcmds.h" #include "commands/sequence.h" #include "commands/tablecmds.h" #include "commands/tablespace.h" @@ -19291,6 +19292,15 @@ AlterTableNamespaceInternal(Relation rel, Oid oldNspOid, Oid nspOid, false, objsMoved); table_close(classRel, RowExclusiveLock); + + /* + * Remove any EXCEPT clause entries for this relation from schema + * publications. A schema-scoped exclusion is no longer meaningful once + * the table moves to a different schema. + */ + if (rel->rd_rel->relkind == RELKIND_RELATION || + rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE) + RemovePublicationExceptForRelation(RelationGetRelid(rel)); } /* diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y index ff4e1388c55..717e03aac7c 100644 --- a/src/backend/parser/gram.y +++ b/src/backend/parser/gram.y @@ -58,6 +58,7 @@ #include "nodes/makefuncs.h" #include "nodes/nodeFuncs.h" #include "parser/parser.h" +#include "utils/builtins.h" #include "utils/datetime.h" #include "utils/xml.h" @@ -11272,7 +11273,7 @@ AlterOwnerStmt: ALTER AGGREGATE aggregate_with_argtypes OWNER TO RoleSpec * pub_obj is one of: * * TABLE table [, ...] - * TABLES IN SCHEMA schema [, ...] + * TABLES IN SCHEMA schema [EXCEPT (TABLE table [, ...] )] [, ...] * *****************************************************************************/ @@ -11332,23 +11333,26 @@ PublicationObjSpec: $$->pubtable->columns = $3; $$->pubtable->whereClause = $4; } - | TABLES IN_P SCHEMA ColId + | TABLES IN_P SCHEMA ColId opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_SCHEMA; $$->name = $4; + $$->except_tables = $5; $$->location = @4; } - | TABLES IN_P SCHEMA CURRENT_SCHEMA + | TABLES IN_P SCHEMA CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_CUR_SCHEMA; + $$->except_tables = $5; $$->location = @4; } - | ColId opt_column_list OptWhereClause + | ColId opt_column_list OptWhereClause opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $4; /* * If either a row filter or column list is specified, create * a PublicationTable object. @@ -11392,10 +11396,11 @@ PublicationObjSpec: $$->pubtable->columns = $2; $$->pubtable->whereClause = $3; } - | CURRENT_SCHEMA + | CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $2; $$->location = @1; } ; @@ -20784,6 +20789,8 @@ preprocess_pub_all_objtype_list(List *all_objects_list, List **pubobjects, /* * Process pubobjspec_list to check for errors in any of the objects and * convert PUBLICATIONOBJ_CONTINUATION into appropriate PublicationObjSpecType. + * Also flattens except_tables from TABLES IN SCHEMA nodes into the list so + * that ObjectsInPublicationToOids() sees them as top-level EXCEPT_TABLE entries. */ static void preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) @@ -20812,6 +20819,13 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLE) { + /* EXCEPT is not valid for table objects */ + if (pubobj->except_tables != NIL) + ereport(ERROR, + errcode(ERRCODE_SYNTAX_ERROR), + errmsg("EXCEPT is not allowed for TABLE publication objects"), + parser_errposition(pubobj->location)); + /* relation name or pubtable must be set for this type of object */ if (!pubobj->name && !pubobj->pubtable) ereport(ERROR, @@ -20860,6 +20874,37 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) errcode(ERRCODE_SYNTAX_ERROR), errmsg("invalid schema name"), parser_errposition(pubobj->location)); + + /* + * For TABLES_IN_SCHEMA, qualify unqualified EXCEPT table names + * with the parent schema and reject cross-schema entries at parse + * time, then flatten into the top-level list. + * + * For TABLES_IN_CUR_SCHEMA the schema name is not yet known, so + * skip both steps here; ObjectsInPublicationToOids() will + * qualify names and validate schema membership at execution time. + */ + if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLES_IN_SCHEMA) + { + foreach_ptr(PublicationObjSpec, eobj, pubobj->except_tables) + { + const char *eobj_schemaname = eobj->pubtable->relation->schemaname; + const char *eobj_relname = eobj->pubtable->relation->relname; + + if (eobj_schemaname == NULL) + eobj->pubtable->relation->schemaname = pubobj->name; + else if (strcmp(eobj_schemaname, pubobj->name) != 0) + ereport(ERROR, + errcode(ERRCODE_INVALID_OBJECT_DEFINITION), + errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", + quote_qualified_identifier(eobj_schemaname, eobj_relname), + pubobj->name), + parser_errposition(eobj->location)); + } + pubobjspec_list = list_concat(pubobjspec_list, pubobj->except_tables); + pubobj->except_tables = NIL; + } + /* For TABLES_IN_CUR_SCHEMA: leave except_tables for execution time */ } prevobjtype = pubobj->pubobjtype; diff --git a/src/backend/replication/pgoutput/pgoutput.c b/src/backend/replication/pgoutput/pgoutput.c index 4ecfcbff7ab..7ee84ec1c83 100644 --- a/src/backend/replication/pgoutput/pgoutput.c +++ b/src/backend/replication/pgoutput/pgoutput.c @@ -2097,6 +2097,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) * are absorbed while decoding WAL. */ List *schemaPubids = GetSchemaPublications(schemaId); + List *except_pubids; ListCell *lc; Oid publish_as_relid = relid; int publish_ancestor_level = 0; @@ -2104,6 +2105,28 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) char relkind = get_rel_relkind(relid); List *rel_publications = NIL; + /* + * For the schema EXCEPT check, we must look up the top-most ancestor + * rather than the relation itself. check_publication_add_relation() + * prevents individual partitions from appearing in the EXCEPT clause, + * so only a root (non-partition) table can have prexcept = true. + * Using the partition's own OID would always return NIL and miss the + * exclusion. + */ + Oid root_relid; + + if (am_partition) + { + List *ancestors = get_partition_ancestors(relid); + + root_relid = llast_oid(ancestors); + list_free(ancestors); + } + else + root_relid = relid; + + except_pubids = GetRelationExcludedPublications(root_relid); + /* Reload publications if needed before use. */ if (!publications_valid) { @@ -2267,7 +2290,8 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) ancestor = GetTopMostAncestorInPublication(pub->oid, ancestors, - &level); + &level, + except_pubids); if (ancestor != InvalidOid) { @@ -2281,7 +2305,8 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) } if (list_member_oid(pubids, pub->oid) || - list_member_oid(schemaPubids, pub->oid) || + (list_member_oid(schemaPubids, pub->oid) && + !list_member_oid(except_pubids, pub->oid)) || ancestor_published) publish = true; } @@ -2360,6 +2385,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) list_free(pubids); list_free(schemaPubids); + list_free(except_pubids); list_free(rel_publications); entry->replicate_valid = true; diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c index e1449654f96..e5b1a70e05e 100644 --- a/src/bin/psql/describe.c +++ b/src/bin/psql/describe.c @@ -7038,6 +7038,24 @@ describePublications(const char *pattern) if (!addFooterToPublicationDesc(&buf, _("Tables from schemas:"), true, &cont)) goto error_return; + + if (pset.sversion >= 190000) + { + /* + * Get tables in the EXCEPT clause for this schema + * publication. + */ + printfPQExpBuffer(&buf, + "SELECT concat(c.relnamespace::regnamespace, '.', c.relname)\n" + "FROM pg_catalog.pg_class c\n" + " JOIN pg_catalog.pg_publication_rel pr ON c.oid = pr.prrelid\n" + "WHERE pr.prpubid = '%s'\n" + " AND pr.prexcept\n" + "ORDER BY 1", pubid); + if (!addFooterToPublicationDesc(&buf, _("Except tables:"), + true, &cont)) + goto error_return; + } } } else diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index de547a8cb37..53bb7c8679b 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -1065,6 +1065,24 @@ static const SchemaQuery Query_for_trigger_of_table = { "SELECT nspname FROM pg_catalog.pg_namespace "\ " WHERE nspname LIKE '%s'" +#define Query_for_list_of_tables_in_schema \ +"SELECT n.nspname || '.' || c.relname "\ +" FROM pg_catalog.pg_class c "\ +" JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "\ +" WHERE c.relkind IN (" CppAsString2(RELKIND_RELATION) ", " \ + CppAsString2(RELKIND_PARTITIONED_TABLE) ") "\ +" AND (n.nspname || '.' || c.relname) LIKE '%s' "\ +" AND n.nspname = '%s'" + +#define Query_for_list_of_tables_in_current_schema \ +"SELECT c.relname "\ +" FROM pg_catalog.pg_class c "\ +" JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "\ +" WHERE c.relkind IN (" CppAsString2(RELKIND_RELATION) ", " \ + CppAsString2(RELKIND_PARTITIONED_TABLE) ") "\ +" AND c.relname LIKE '%s' "\ +" AND n.nspname = pg_catalog.current_schema()" + /* Use COMPLETE_WITH_QUERY_VERBATIM with these queries for GUC names: */ #define Query_for_list_of_alter_system_set_vars \ "SELECT pg_catalog.lower(name) FROM pg_catalog.pg_settings "\ @@ -3787,8 +3805,21 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); - else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && (!ends_with(prev_wd, ','))) - COMPLETE_WITH("WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE", "WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* Complete "CREATE PUBLICATION <name> [...] WITH" */ else if (Matches("CREATE", "PUBLICATION", MatchAnyN, "WITH", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/include/catalog/pg_publication.h b/src/include/catalog/pg_publication.h index 89b4bb14f62..53e3d7c6f3d 100644 --- a/src/include/catalog/pg_publication.h +++ b/src/include/catalog/pg_publication.h @@ -191,7 +191,8 @@ extern List *GetPubPartitionOptionRelations(List *result, PublicationPartOpt pub_partopt, Oid relid); extern Oid GetTopMostAncestorInPublication(Oid puboid, List *ancestors, - int *ancestor_level); + int *ancestor_level, + List *except_pubids); extern bool is_publishable_relation(Relation rel); extern bool is_schema_publication(Oid pubid); diff --git a/src/include/commands/publicationcmds.h b/src/include/commands/publicationcmds.h index 4cf45c17cc5..93c77331437 100644 --- a/src/include/commands/publicationcmds.h +++ b/src/include/commands/publicationcmds.h @@ -27,6 +27,7 @@ extern void AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt); extern void RemovePublicationById(Oid pubid); extern void RemovePublicationRelById(Oid proid); extern void RemovePublicationSchemaById(Oid psoid); +extern void RemovePublicationExceptForRelation(Oid relid); extern ObjectAddress AlterPublicationOwner(const char *name, Oid newOwnerId); extern void AlterPublicationOwner_oid(Oid pubid, Oid newOwnerId); diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h index 91377a6cde3..98a03c0eeda 100644 --- a/src/include/nodes/parsenodes.h +++ b/src/include/nodes/parsenodes.h @@ -4493,6 +4493,8 @@ typedef struct PublicationObjSpec PublicationObjSpecType pubobjtype; /* type of this publication object */ char *name; PublicationTable *pubtable; + List *except_tables; /* tables specified in the EXCEPT clause (for + * TABLES IN SCHEMA) */ ParseLoc location; /* token location, or -1 if unknown */ } PublicationObjSpec; diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 29e54b214a0..6df42a60f9c 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -270,6 +270,12 @@ CREATE PUBLICATION testpub_foralltables_excepttable2 FOR ALL TABLES EXCEPT (test ERROR: syntax error at or near "testpub_tbl1" LINE 1: ..._foralltables_excepttable2 FOR ALL TABLES EXCEPT (testpub_tb... ^ +-- fail - EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testpub_tbl3); +ERROR: EXCEPT is not allowed for TABLE publication objects +LINE 2: FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testp... + ^ --------------------------------------------- -- SET ALL TABLES/SEQUENCES --------------------------------------------- @@ -470,7 +476,103 @@ HINT: Change the publication's EXCEPT clause using ALTER PUBLICATION ... SET AL RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Create same-named tables in public to verify unqualified EXCEPT entries +-- are qualified with the named schema, not public +CREATE TABLE testpub_nopk (foo int, bar int); +CREATE TABLE testpub_tbl_s1 (a int primary key, b text); +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + Publication testpub_schema_except1 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- Exclude multiple tables using unqualified names; same-named tables exist in +-- public to confirm unqualified names resolve to pub_test, not public +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + Publication testpub_schema_except2 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_nopk" + "pub_test.testpub_tbl_s1" + +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testp... + ^ +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); +ERROR: table "pub_test.testpub_tbl_s1" in EXCEPT clause does not belong to schema "public" +LINE 2: ...R TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.t... + ^ +-- Multiple schemas each with their own EXCEPT clause +CREATE PUBLICATION testpub_schema_except_multi + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_schema_except_multi + Publication testpub_schema_except_multi + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- fail: table appears in both the explicit table list and the EXCEPT clause +CREATE PUBLICATION testpub_except_conflict + FOR TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot appear in both the table list and the EXCEPT clause +-- fail: nonexistent table in EXCEPT clause +CREATE PUBLICATION testpub_except_norel + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- fail: partition cannot appear in EXCEPT clause; only root tables are allowed +CREATE TABLE pub_test.testpub_parted_s (a int) PARTITION BY LIST (a); +CREATE TABLE pub_test.testpub_part_s PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (1); +CREATE PUBLICATION testpub_except_partition + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); +ERROR: cannot specify relation "pub_test.testpub_part_s" in the publication EXCEPT clause +DETAIL: This operation is not supported for individual partitions. +-- fail: TABLE keyword is required for the first entry in the EXCEPT clause +CREATE PUBLICATION testpub_except_nokw + FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +ERROR: syntax error at or near "testpub_nopk" +LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + ^ +-- Cleanup +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP TABLE pub_test.testpub_parted_s CASCADE; +DROP TABLE testpub_nopk, testpub_tbl_s1; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +--------------------------------------------- +-- Tests for publications with SEQUENCES +--------------------------------------------- CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; -- FOR ALL SEQUENCES @@ -1953,6 +2055,27 @@ ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b); ERROR: column specification not allowed for schema LINE 1: ...TION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b)... ^ +-- EXCEPT clause with CURRENT_SCHEMA: cross-schema entry must be rejected +SET search_path = pub_test1; +-- qualified name from wrong schema -> error +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.tbl1); +ERROR: table "pub_test2.tbl1" in EXCEPT clause does not belong to schema "pub_test1" +-- unqualified name implicitly qualified with current schema (pub_test1.tbl) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl); +RESET client_min_messages; +\dRp+ testpub_cursch_except + Publication testpub_cursch_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test1" +Except tables: + "pub_test1.tbl" + +DROP PUBLICATION testpub_cursch_except; +RESET search_path; -- cleanup pub_test1 schema for invalidation tests ALTER PUBLICATION testpub2_forschema DROP TABLES IN SCHEMA pub_test1; DROP PUBLICATION testpub3_forschema, testpub4_forschema, testpub5_forschema, testpub6_forschema, testpub_fortable; @@ -2304,6 +2427,7 @@ DROP ROLE regress_publication_user_dummy; -- Test pg_get_publication_tables(text[], oid) function CREATE SCHEMA gpt_test_sch; CREATE TABLE gpt_test_sch.tbl_sch (id int); +CREATE TABLE gpt_test_sch.tbl_sch2 (id int); CREATE TABLE tbl_normal (id int); CREATE TABLE tbl_parent (id1 int, id2 int, id3 int) PARTITION BY RANGE (id1); CREATE TABLE tbl_part1 PARTITION OF tbl_parent FOR VALUES FROM (1) TO (10); @@ -2314,6 +2438,7 @@ CREATE PUBLICATION pub_all_no_viaroot FOR ALL TABLES WITH (publish_via_partition CREATE PUBLICATION pub_all_except FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = true); CREATE PUBLICATION pub_all_except_no_viaroot FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_schema FOR TABLES IN SCHEMA gpt_test_sch; +CREATE PUBLICATION pub_schema_except FOR TABLES IN SCHEMA gpt_test_sch EXCEPT (TABLE gpt_test_sch.tbl_sch); CREATE PUBLICATION pub_normal FOR TABLE tbl_normal WHERE (id < 10); CREATE PUBLICATION pub_part_leaf FOR TABLE tbl_part1 WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_part_parent FOR TABLE tbl_parent (id1, id2) WHERE (id1 = 10) WITH (publish_via_partition_root = true); @@ -2465,6 +2590,18 @@ SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_part1'); -- no r ---------+---------+-------+------ (0 rows) +-- test for EXCEPT clause with schema publication (bug: excluded table was incorrectly returned) +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch'); -- no result (excluded) + pubname | relname | attrs | qual +---------+---------+-------+------ +(0 rows) + +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch2'); -- one row (included via schema) + pubname | relname | attrs | qual +-------------------+----------+-------+------ + pub_schema_except | tbl_sch2 | 1 | +(1 row) + -- two rows with different row filter SELECT * FROM test_gpt(ARRAY['pub_all', 'pub_normal'], 'tbl_normal'); pubname | relname | attrs | qual @@ -2517,6 +2654,7 @@ DROP PUBLICATION pub_all_no_viaroot; DROP PUBLICATION pub_all_except; DROP PUBLICATION pub_all_except_no_viaroot; DROP PUBLICATION pub_schema; +DROP PUBLICATION pub_schema_except; DROP PUBLICATION pub_normal; DROP PUBLICATION pub_part_leaf; DROP PUBLICATION pub_part_parent; @@ -2525,7 +2663,9 @@ DROP PUBLICATION pub_part_parent_child; DROP VIEW gpt_test_view; DROP TABLE tbl_normal, tbl_parent, tbl_part1; DROP SCHEMA gpt_test_sch CASCADE; -NOTICE: drop cascades to table gpt_test_sch.tbl_sch +NOTICE: drop cascades to 2 other objects +DETAIL: drop cascades to table gpt_test_sch.tbl_sch +drop cascades to table gpt_test_sch.tbl_sch2 -- stage objects for pg_dump tests CREATE SCHEMA pubme CREATE TABLE t0 (c int, d int) CREATE TABLE t1 (c int); CREATE SCHEMA pubme2 CREATE TABLE t0 (c int, d int); diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 041e14a4de6..bd523e376b2 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -123,6 +123,9 @@ CREATE PUBLICATION testpub_foralltables_excepttable1 FOR ALL TABLES EXCEPT (TABL \d testpub_tbl1 -- fail - first table in the EXCEPT list should use TABLE keyword CREATE PUBLICATION testpub_foralltables_excepttable2 FOR ALL TABLES EXCEPT (testpub_tbl1, testpub_tbl2); +-- fail - EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testpub_tbl3); --------------------------------------------- -- SET ALL TABLES/SEQUENCES @@ -220,7 +223,71 @@ RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Create same-named tables in public to verify unqualified EXCEPT entries +-- are qualified with the named schema, not public +CREATE TABLE testpub_nopk (foo int, bar int); +CREATE TABLE testpub_tbl_s1 (a int primary key, b text); + +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + +-- Exclude multiple tables using unqualified names; same-named tables exist in +-- public to confirm unqualified names resolve to pub_test, not public +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); + +-- Multiple schemas each with their own EXCEPT clause +CREATE PUBLICATION testpub_schema_except_multi + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_schema_except_multi + +-- fail: table appears in both the explicit table list and the EXCEPT clause +CREATE PUBLICATION testpub_except_conflict + FOR TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: nonexistent table in EXCEPT clause +CREATE PUBLICATION testpub_except_norel + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- fail: partition cannot appear in EXCEPT clause; only root tables are allowed +CREATE TABLE pub_test.testpub_parted_s (a int) PARTITION BY LIST (a); +CREATE TABLE pub_test.testpub_part_s PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (1); +CREATE PUBLICATION testpub_except_partition + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); + +-- fail: TABLE keyword is required for the first entry in the EXCEPT clause +CREATE PUBLICATION testpub_except_nokw + FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + +-- Cleanup +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP TABLE pub_test.testpub_parted_s CASCADE; +DROP TABLE testpub_nopk, testpub_tbl_s1; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; + +--------------------------------------------- +-- Tests for publications with SEQUENCES +--------------------------------------------- CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; @@ -1189,6 +1256,18 @@ ALTER PUBLICATION testpub1_forschema SET TABLES IN SCHEMA pub_test1, pub_test1; ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo (a, b); ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b); +-- EXCEPT clause with CURRENT_SCHEMA: cross-schema entry must be rejected +SET search_path = pub_test1; +-- qualified name from wrong schema -> error +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.tbl1); +-- unqualified name implicitly qualified with current schema (pub_test1.tbl) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl); +RESET client_min_messages; +\dRp+ testpub_cursch_except +DROP PUBLICATION testpub_cursch_except; +RESET search_path; + -- cleanup pub_test1 schema for invalidation tests ALTER PUBLICATION testpub2_forschema DROP TABLES IN SCHEMA pub_test1; DROP PUBLICATION testpub3_forschema, testpub4_forschema, testpub5_forschema, testpub6_forschema, testpub_fortable; @@ -1443,6 +1522,7 @@ DROP ROLE regress_publication_user_dummy; -- Test pg_get_publication_tables(text[], oid) function CREATE SCHEMA gpt_test_sch; CREATE TABLE gpt_test_sch.tbl_sch (id int); +CREATE TABLE gpt_test_sch.tbl_sch2 (id int); CREATE TABLE tbl_normal (id int); CREATE TABLE tbl_parent (id1 int, id2 int, id3 int) PARTITION BY RANGE (id1); CREATE TABLE tbl_part1 PARTITION OF tbl_parent FOR VALUES FROM (1) TO (10); @@ -1454,6 +1534,7 @@ CREATE PUBLICATION pub_all_no_viaroot FOR ALL TABLES WITH (publish_via_partition CREATE PUBLICATION pub_all_except FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = true); CREATE PUBLICATION pub_all_except_no_viaroot FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_schema FOR TABLES IN SCHEMA gpt_test_sch; +CREATE PUBLICATION pub_schema_except FOR TABLES IN SCHEMA gpt_test_sch EXCEPT (TABLE gpt_test_sch.tbl_sch); CREATE PUBLICATION pub_normal FOR TABLE tbl_normal WHERE (id < 10); CREATE PUBLICATION pub_part_leaf FOR TABLE tbl_part1 WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_part_parent FOR TABLE tbl_parent (id1, id2) WHERE (id1 = 10) WITH (publish_via_partition_root = true); @@ -1510,6 +1591,10 @@ SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'gpt_test_sch.tbl_sch SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_parent'); -- no result (excluded) SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_part1'); -- no result +-- test for EXCEPT clause with schema publication (bug: excluded table was incorrectly returned) +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch'); -- no result (excluded) +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch2'); -- one row (included via schema) + -- two rows with different row filter SELECT * FROM test_gpt(ARRAY['pub_all', 'pub_normal'], 'tbl_normal'); @@ -1538,6 +1623,7 @@ DROP PUBLICATION pub_all_no_viaroot; DROP PUBLICATION pub_all_except; DROP PUBLICATION pub_all_except_no_viaroot; DROP PUBLICATION pub_schema; +DROP PUBLICATION pub_schema_except; DROP PUBLICATION pub_normal; DROP PUBLICATION pub_part_leaf; DROP PUBLICATION pub_part_parent; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 8c58d282eee..18c7b2c1fca 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -24,14 +24,17 @@ my $result; sub test_except_root_partition { - my ($pubviaroot) = @_; + my ($pubviaroot, $pubsql) = @_; + $pubsql //= + "CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1)"; + $pubsql .= " WITH (publish_via_partition_root = $pubviaroot)"; # If the root partitioned table is in the EXCEPT clause, all its # partitions are excluded from publication, regardless of the # publish_via_partition_root setting. $node_publisher->safe_psql( 'postgres', qq( - CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1) WITH (publish_via_partition_root = $pubviaroot); + $pubsql; INSERT INTO root1 VALUES (1), (101); )); $node_subscriber->safe_psql('postgres', @@ -223,6 +226,131 @@ $node_subscriber->safe_psql( test_except_root_partition('false'); test_except_root_partition('true'); +# Same validation using TABLES IN SCHEMA instead of FOR ALL TABLES. +my $schema_pub = + "CREATE PUBLICATION tap_pub_part FOR TABLES IN SCHEMA public EXCEPT (TABLE public.root1)"; +test_except_root_partition('false', $schema_pub); +test_except_root_partition('true', $schema_pub); + +# ============================================ +# EXCEPT test cases for TABLES IN SCHEMA +# ============================================ + +# Create a dedicated schema with two tables: one to be published and one to be +# excluded. Also create inherited tables to verify ONLY semantics. +$node_publisher->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_published AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.tab_excluded AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.parent (a int); + CREATE TABLE sch1.child (b int) INHERITS (sch1.parent); +)); + +$node_subscriber->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_published (a int); + CREATE TABLE sch1.tab_excluded (a int); + CREATE TABLE sch1.parent (a int); + CREATE TABLE sch1.child (b int) INHERITS (sch1.parent); +)); + +# Basic test: initial sync respects EXCEPT. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_excluded)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: initial sync copies included table'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: initial sync skips excluded table'); + +# DML: only the included table should be replicated. +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (6); + INSERT INTO sch1.tab_excluded VALUES (6); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(6), + 'TABLES IN SCHEMA EXCEPT: DML on included table is replicated'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: DML on excluded table is not replicated'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Inherited tables: excluding the parent (without ONLY) also excludes the child. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.parent)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.child VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.child"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: excluding parent (without ONLY) also excludes child' +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Test that EXCEPT (TABLE ONLY parent) excludes only the parent itself, not its +# child. Truncate child first so rows from the previous test are not copied by +# the initial table sync of the next subscription. +$node_publisher->safe_psql('postgres', 'TRUNCATE sch1.child'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE sch1.child'); +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE ONLY sch1.parent)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.child VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.child"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: ONLY parent in EXCEPT does not exclude child'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Cleanup schema tables before the multi-publication section. +$node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); +$node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); + # ============================================ # Test when a subscription is subscribing to multiple publications # ============================================ @@ -254,6 +382,7 @@ $node_publisher->safe_psql( DROP PUBLICATION tap_pub2; TRUNCATE tab1; )); +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_subscriber->safe_psql('postgres', qq(TRUNCATE tab1)); # OK when a table is excluded by pub1 EXCEPT clause, but it is included by pub2 -- 2.50.1 (Apple Git-155)
v11-0002-Add-EXCEPT-support-to-ALTER-PUBLICATION-ADD-TABL.patch (application/octet-stream, 22.5K) download From fb3a29860a2d9ca69d4559ea117df99c6286f3b3 Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Fri, 29 May 2026 20:04:57 +0530 Subject: [PATCH v11 2/3] Add EXCEPT support to ALTER PUBLICATION ADD TABLES IN SCHEMA Extend the EXCEPT clause support to allow tables to be excluded when adding a schema to a publication via ALTER PUBLICATION ... ADD. Syntax: ALTER PUBLICATION pub ADD TABLES IN SCHEMA s EXCEPT (TABLE s.t1); Since pg_dump uses ALTER PUBLICATION ... ADD, support for it is included in this patch. --- doc/src/sgml/ref/alter_publication.sgml | 40 +++++++- src/backend/catalog/pg_publication.c | 19 ++-- src/backend/commands/publicationcmds.c | 107 +++++++++++++++++++++- src/bin/pg_dump/pg_dump.c | 30 +++++- src/bin/pg_dump/t/002_pg_dump.pl | 24 +++++ src/bin/psql/tab-complete.in.c | 17 ++++ src/test/regress/expected/publication.out | 32 ++++++- src/test/regress/sql/publication.sql | 20 +++- src/test/subscription/t/037_except.pl | 32 +++++++ 9 files changed, 306 insertions(+), 15 deletions(-) diff --git a/doc/src/sgml/ref/alter_publication.sgml b/doc/src/sgml/ref/alter_publication.sgml index 52114a16a39..326978da454 100644 --- a/doc/src/sgml/ref/alter_publication.sgml +++ b/doc/src/sgml/ref/alter_publication.sgml @@ -31,7 +31,7 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA <replaceable class="parameter">tables_in_schema</replaceable> [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -47,6 +47,10 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <replaceable class="parameter">table_object</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] [ WHERE ( <replaceable class="parameter">expression</replaceable> ) ] +<phrase>and <replaceable class="parameter">tables_in_schema</replaceable> is:</phrase> + + { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] + <phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> TABLE <replaceable class="parameter">table_object</replaceable> [, ... ] @@ -110,6 +114,14 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <literal>ADD TABLE</literal>. </para> + <para> + The <literal>EXCEPT</literal> clause can be used with + <literal>ADD TABLES IN SCHEMA</literal> to exclude specific tables from the + publication. Using <literal>DROP TABLES IN SCHEMA</literal> on a publication + will automatically also remove any associated <literal>EXCEPT</literal> + entries. + </para> + <para> The fourth variant of this command listed in the synopsis can change all of the publication properties specified in @@ -198,6 +210,22 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r </listitem> </varlistentry> + <varlistentry> + <term><literal>EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] )</literal></term> + <listitem> + <para> + When used with <literal>ADD TABLES IN SCHEMA</literal>, specifies + tables to be excluded from the publication. Each named + table must belong to the schema specified in the same + <literal>TABLES IN SCHEMA</literal> clause. Table names may be + schema-qualified or unqualified; unqualified names are implicitly + qualified with the schema named in the same clause. See + <xref linkend="sql-createpublication"/> for further details on the + semantics of <literal>EXCEPT</literal>. + </para> + </listitem> + </varlistentry> + <varlistentry> <term><literal>SET ( <replaceable class="parameter">publication_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] )</literal></term> <listitem> @@ -288,6 +316,16 @@ ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA marketing, sales; </programlisting> </para> + <para> + Add schema <structname>sales</structname> to the publication + <structname>sales_publication</structname>, excluding the + <structname>sales.internal</structname> and + <structname>sales.drafts</structname> tables: +<programlisting> +ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA sales EXCEPT (TABLE internal, drafts); +</programlisting> + </para> + <para> Add tables <structname>users</structname>, <structname>departments</structname> and schema diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index 4089b505f89..d1ff8839037 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -649,15 +649,18 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, * here, as CreatePublication() function invalidates all relations as part * of defining a FOR ALL TABLES publication. * - * For ALTER PUBLICATION, invalidation is needed only when adding an - * EXCEPT table to a publication already marked as ALL TABLES. For - * publications that were originally empty or defined as ALL SEQUENCES and - * are being converted to ALL TABLES, invalidation is skipped here, as - * AlterPublicationAllFlags() function invalidates all relations while - * marking the publication as ALL TABLES publication. + * For ALTER PUBLICATION, invalidation is needed when adding an EXCEPT + * table to either a FOR ALL TABLES publication (pub->alltables is true) + * or a FOR TABLES IN SCHEMA publication (is_schema_publication is true). + * The exception: when a publication is being converted to FOR ALL TABLES + * (pub->alltables is still false at this point), + * AlterPublicationAllFlags() will perform a full invalidation, so we skip + * it here. */ - inval_except_table = (alter_stmt != NULL) && pub->alltables && - (alter_stmt->for_all_tables && pri->except); + inval_except_table = (alter_stmt != NULL) && pri->except && + (pub->alltables + ? alter_stmt->for_all_tables + : is_schema_publication(pubid)); if (!pri->except || inval_except_table) { diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 876898aa487..9fa5f4bf67a 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -70,6 +70,13 @@ static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok); static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); +static void AlterPublicationSchemas(AlterPublicationStmt *stmt, + HeapTuple tup, List *schemaidlist, + List *except_pubtables); +static void AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, + List *except_pubtables, + List *schemaidlist); static char defGetGeneratedColsOption(DefElem *def); @@ -1500,7 +1507,8 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, */ static void AlterPublicationSchemas(AlterPublicationStmt *stmt, - HeapTuple tup, List *schemaidlist) + HeapTuple tup, List *schemaidlist, + List *except_pubtables) { Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); @@ -1577,6 +1585,97 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, */ PublicationAddSchemas(pubform->oid, schemaidlist, true, stmt); } + + /* + * Increment the command counter so that is_schema_publication() in + * GetExcludedPublicationTables() can see the just-inserted schema + * rows when AlterPublicationSchemaExceptTables runs next. + */ + if (stmt->action == AP_AddObjects || stmt->action == AP_SetObjects) + CommandCounterIncrement(); + + AlterPublicationSchemaExceptTables(stmt, tup, except_pubtables, schemaidlist); +} + +/* + * Alter the EXCEPT list of a schema-level publication. + * + * Adds, removes, or replaces except-table entries in pg_publication_rel + * (rows with prexcept = true). These entries suppress publication of the + * named tables that would otherwise be covered by a FOR TABLES IN SCHEMA + * clause. + */ +static void +AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, List *except_pubtables, + List *schemaidlist) +{ + Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); + Oid pubid = pubform->oid; + + /* + * Nothing to do if no EXCEPT entries. + */ + if (!except_pubtables) + return; + + /* + * This function handles EXCEPT entries for schema-level publications + * only. For FOR ALL TABLES publications, EXCEPT entries are already + * processed by AlterPublicationTables(). + */ + if (schemaidlist == NIL && !is_schema_publication(pubid)) + return; + + /* + * Dropping a schema from a publication removes all its EXCEPT entries via + * cascade. The concept of "drop all schema tables from the publication + * EXCEPT these ones" is not supported. + */ + if (stmt->action == AP_DropObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); + + /* + * XXX EXCEPT with SET is not currently implemented. Workaround: DROP and + * re-ADD the schema with the desired EXCEPT list. + */ + if (stmt->action == AP_SetObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"), + errhint("Drop and re-add the schema with the desired EXCEPT list."))); + + if (stmt->action == AP_AddObjects) + { + List *rels; + List *explicitrelids; + + rels = OpenTableList(except_pubtables); + + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + /* + * Validate that each excluded table is not also in the explicit table + * list (which would be contradictory). + */ + foreach_ptr(PublicationRelInfo, pri, rels) + { + Oid relid = RelationGetRelid(pri->relation); + + if (list_member_oid(explicitrelids, relid)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" cannot appear in both the table list and the EXCEPT clause", + RelationGetQualifiedRelationName(pri->relation))); + } + + PublicationAddTables(pubid, rels, false, stmt); + + CloseTableList(rels); + } } /* @@ -1786,10 +1885,12 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) errmsg("publication \"%s\" does not exist", stmt->pubname)); - relations = list_concat(relations, except_pubtables); + if (stmt->for_all_tables) + relations = list_concat(relations, except_pubtables); + AlterPublicationTables(stmt, tup, relations, pstate->p_sourcetext, schemaidlist != NIL); - AlterPublicationSchemas(stmt, tup, schemaidlist); + AlterPublicationSchemas(stmt, tup, schemaidlist, except_pubtables); AlterPublicationAllFlags(stmt, rel, tup); } diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c index a0f7f8e2168..85ab3b00875 100644 --- a/src/bin/pg_dump/pg_dump.c +++ b/src/bin/pg_dump/pg_dump.c @@ -5019,6 +5019,7 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) PublicationInfo *pubinfo = pubsinfo->publication; PQExpBuffer query; char *tag; + bool has_except = false; /* Do nothing if not dumping schema */ if (!dopt->dumpSchema) @@ -5029,7 +5030,34 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) query = createPQExpBuffer(); appendPQExpBuffer(query, "ALTER PUBLICATION %s ", fmtId(pubinfo->dobj.name)); - appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s;\n", fmtId(schemainfo->dobj.name)); + appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s", fmtId(schemainfo->dobj.name)); + + /* + * Append EXCEPT clause for any tables that belong to this schema + * and are excluded from the publication. + */ + for (SimplePtrListCell *cell = pubinfo->except_tables.head; cell; cell = cell->next) + { + TableInfo *tbinfo = (TableInfo *) cell->ptr; + + if (strcmp(tbinfo->dobj.namespace->dobj.name, schemainfo->dobj.name) == 0) + { + if (!has_except) + { + appendPQExpBufferStr(query, " EXCEPT ("); + has_except = true; + } + else + appendPQExpBufferStr(query, ", "); + + appendPQExpBuffer(query, "TABLE ONLY %s", fmtId(tbinfo->dobj.name)); + } + } + + if (has_except) + appendPQExpBufferStr(query, ")"); + + appendPQExpBufferStr(query, ";\n"); /* * There is no point in creating drop query as the drop is done by schema diff --git a/src/bin/pg_dump/t/002_pg_dump.pl b/src/bin/pg_dump/t/002_pg_dump.pl index 3ee9fda50e4..b8f4aa769ec 100644 --- a/src/bin/pg_dump/t/002_pg_dump.pl +++ b/src/bin/pg_dump/t/002_pg_dump.pl @@ -3242,6 +3242,30 @@ my %tests = ( like => { %full_runs, section_post_data => 1, }, }, + 'CREATE PUBLICATION pub11' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub11 FOR TABLES IN SCHEMA dump_test EXCEPT (TABLE test_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub11 WITH (publish = 'insert, update, delete, truncate');\E + .*? + \QALTER PUBLICATION pub11 ADD TABLES IN SCHEMA dump_test EXCEPT (TABLE ONLY test_table);\E + /xms, + like => { %full_runs, section_post_data => 1, }, + }, + + 'CREATE PUBLICATION pub12' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub12 FOR TABLES IN SCHEMA dump_test EXCEPT (TABLE test_table, dump_test.test_second_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub12 WITH (publish = 'insert, update, delete, truncate');\E + .*? + \QALTER PUBLICATION pub12 ADD TABLES IN SCHEMA dump_test EXCEPT (TABLE ONLY test_table, TABLE ONLY test_second_table);\E + /xms, + like => { %full_runs, section_post_data => 1, }, + }, + 'CREATE SUBSCRIPTION sub1' => { create_order => 50, create_sql => 'CREATE SUBSCRIPTION sub1 diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index 53bb7c8679b..a290902d61e 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2373,6 +2373,23 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); + /* After a single schema name in ADD context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 6df42a60f9c..8b49239b574 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -564,12 +564,42 @@ CREATE PUBLICATION testpub_except_nokw ERROR: syntax error at or near "testpub_nopk" LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); ^ +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; +-- fail: non-existing table in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- fail: EXCEPT table belongs to a different schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 1: ...xcept ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.tes... + ^ +-- fail: TABLE keyword is required for the first entry in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +ERROR: syntax error at or near "testpub_nopk" +LINE 1: ...lter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_no... + ^ +-- ADD: qualified and unqualified names; unqualified is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + "pub_test.testpub_tbl_s2" + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP TABLE pub_test.testpub_parted_s CASCADE; DROP TABLE testpub_nopk, testpub_tbl_s1; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi, testpub_alter_except; --------------------------------------------- -- Tests for publications with SEQUENCES --------------------------------------------- diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index bd523e376b2..e9387418904 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -278,12 +278,30 @@ CREATE PUBLICATION testpub_except_partition CREATE PUBLICATION testpub_except_nokw FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; + +-- fail: non-existing table in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- fail: EXCEPT table belongs to a different schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- fail: TABLE keyword is required for the first entry in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + +-- ADD: qualified and unqualified names; unqualified is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); +\dRp+ testpub_alter_except + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP TABLE pub_test.testpub_parted_s CASCADE; DROP TABLE testpub_nopk, testpub_tbl_s1; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi, testpub_alter_except; --------------------------------------------- -- Tests for publications with SEQUENCES diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 18c7b2c1fca..0ba6d6f8bb2 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -347,6 +347,38 @@ is($result, qq(5), $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); +# ============================================ +# ALTER PUBLICATION EXCEPT for TABLES IN SCHEMA +# ============================================ + +# Truncate subscriber tables to remove data accumulated from previous tests. +$node_subscriber->safe_psql('postgres', + 'TRUNCATE sch1.tab_published, sch1.tab_excluded, sch1.parent, sch1.child'); + +# ADD: add a schema with an excepted table; verify the except entry takes effect. +$node_publisher->safe_psql('postgres', "CREATE PUBLICATION sch_pub"); +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub ADD TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_excluded)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(6), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: included table synced'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + # Cleanup schema tables before the multi-publication section. $node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); $node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); -- 2.50.1 (Apple Git-155)
v11-0003-Add-EXCEPT-support-to-ALTER-PUBLICATION-SET-TABL.patch (application/octet-stream, 26.1K) download From 79f49a05687c9c1dcd50a0854823bd0cf1481cd4 Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Tue, 2 Jun 2026 11:39:36 +0530 Subject: [PATCH v11 3/3] Add EXCEPT support to ALTER PUBLICATION SET TABLES IN SCHEMA Extend AlterPublicationExceptTables() with the AP_SetObjects case, which redefines the publication and replaces the entire EXCEPT list. Syntax: ALTER PUBLICATION pub SET TABLES IN SCHEMA s EXCEPT (TABLE t1); This patch also cleans up EXCEPT entries when a schema is dropped from the publication. --- doc/src/sgml/ref/alter_publication.sgml | 27 +++- src/backend/commands/publicationcmds.c | 135 +++++++++++++++++--- src/backend/replication/pgoutput/pgoutput.c | 10 +- src/bin/psql/tab-complete.in.c | 17 +++ src/test/regress/expected/publication.out | 86 +++++++++++++ src/test/regress/sql/publication.sql | 38 ++++++ src/test/subscription/t/037_except.pl | 85 ++++++++++++ 7 files changed, 371 insertions(+), 27 deletions(-) diff --git a/doc/src/sgml/ref/alter_publication.sgml b/doc/src/sgml/ref/alter_publication.sgml index 326978da454..8df1f7a2e34 100644 --- a/doc/src/sgml/ref/alter_publication.sgml +++ b/doc/src/sgml/ref/alter_publication.sgml @@ -97,7 +97,11 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r used with a publication defined with <literal>FOR TABLE</literal> or <literal>FOR TABLES IN SCHEMA</literal>, replaces the list of tables/schemas in the publication with the specified list; the existing tables or schemas - that were present in the publication will be removed. + that were present in the publication will be removed. When + <literal>SET TABLES IN SCHEMA</literal> is used with an + <literal>EXCEPT</literal> clause, the excluded tables for each schema are + replaced with the specified list; if <literal>EXCEPT</literal> is omitted + for a schema, any existing exclusions for that schema are cleared. </para> <para> @@ -116,10 +120,8 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <para> The <literal>EXCEPT</literal> clause can be used with - <literal>ADD TABLES IN SCHEMA</literal> to exclude specific tables from the - publication. Using <literal>DROP TABLES IN SCHEMA</literal> on a publication - will automatically also remove any associated <literal>EXCEPT</literal> - entries. + <literal>ADD TABLES IN SCHEMA</literal> to exclude specific tables from a + schema-level publication. </para> <para> @@ -214,7 +216,8 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <term><literal>EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] )</literal></term> <listitem> <para> - When used with <literal>ADD TABLES IN SCHEMA</literal>, specifies + When used with <literal>ADD TABLES IN SCHEMA</literal> + or <literal>SET TABLES IN SCHEMA</literal>, specifies tables to be excluded from the publication. Each named table must belong to the schema specified in the same <literal>TABLES IN SCHEMA</literal> clause. Table names may be @@ -326,6 +329,18 @@ ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA sales EXCEPT (TABLE int </programlisting> </para> + <para> + Replace the schema list of <structname>sales_publication</structname> with + <structname>sales</structname>, excluding only + <structname>sales.drafts</structname>. Other than + <structname>sales.drafts</structname>, any previously excluded tables for schema + <structname>sales</structname> are no longer excluded. Any schemas previously in + <structname>sales_publication</structname> are removed: +<programlisting> +ALTER PUBLICATION sales_publication SET TABLES IN SCHEMA sales EXCEPT (TABLE drafts); +</programlisting> + </para> + <para> Add tables <structname>users</structname>, <structname>departments</structname> and schema diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 9fa5f4bf67a..73e77b884dc 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -1588,8 +1588,8 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, /* * Increment the command counter so that is_schema_publication() in - * GetExcludedPublicationTables() can see the just-inserted schema - * rows when AlterPublicationSchemaExceptTables runs next. + * GetExcludedPublicationTables() can see the just-inserted schema rows + * when AlterPublicationSchemaExceptTables runs next. */ if (stmt->action == AP_AddObjects || stmt->action == AP_SetObjects) CommandCounterIncrement(); @@ -1607,16 +1607,18 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, */ static void AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, - HeapTuple tup, List *except_pubtables, - List *schemaidlist) + HeapTuple tup, List *except_pubtables, + List *schemaidlist) { Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); Oid pubid = pubform->oid; /* - * Nothing to do if no EXCEPT entries. + * Nothing to do if there are no EXCEPT entries, unless handling the SET + * command, because if the user has removed all exceptions we need to drop + * any existing ones. */ - if (!except_pubtables) + if (!except_pubtables && stmt->action != AP_SetObjects) return; /* @@ -1637,16 +1639,6 @@ AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); - /* - * XXX EXCEPT with SET is not currently implemented. Workaround: DROP and - * re-ADD the schema with the desired EXCEPT list. - */ - if (stmt->action == AP_SetObjects) - ereport(ERROR, - (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"), - errhint("Drop and re-add the schema with the desired EXCEPT list."))); - if (stmt->action == AP_AddObjects) { List *rels; @@ -1674,6 +1666,84 @@ AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, PublicationAddTables(pubid, rels, false, stmt); + CloseTableList(rels); + } + else /* AP_SetObjects */ + { + List *oldexceptrelids = NIL; + List *newexceptrelids = NIL; + List *delrelids = NIL; + List *rels; + List *explicitrelids; + + rels = OpenTableList(except_pubtables); + + /* Collect OIDs of the desired new EXCEPT list. */ + foreach_ptr(PublicationRelInfo, pri, rels) + newexceptrelids = lappend_oid(newexceptrelids, + RelationGetRelid(pri->relation)); + + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + /* + * Validate that each excluded table is not also in the explicit table + * list (which would be contradictory). + */ + foreach_ptr(PublicationRelInfo, pri, rels) + { + Oid relid = RelationGetRelid(pri->relation); + + if (list_member_oid(explicitrelids, relid)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" cannot appear in both the table list and the EXCEPT clause", + RelationGetQualifiedRelationName(pri->relation))); + } + + /* + * Get the current set of EXCEPT entries. Only FOR ALL TABLES and + * schema-level publications can have EXCEPT entries; for any other + * publication type oldexceptrelids stays NIL. + * + * Note: we check is_schema_publication() against the current catalog + * state (before AlterPublicationSchemas has run), so if the caller is + * doing SET TABLE t1 to convert a schema publication into a plain + * table publication, is_schema_publication() still returns true here. + * That is intentional: it lets us discover and clean up any stale + * EXCEPT entries that belong to the old schema definition. + */ + if (GetPublication(pubid)->alltables || is_schema_publication(pubid)) + oldexceptrelids = GetExcludedPublicationTables(pubid, + PUBLICATION_PART_ROOT); + + /* Build a list of old EXCEPT entries not present in the new list. */ + foreach_oid(oldrelid, oldexceptrelids) + { + if (!list_member_oid(newexceptrelids, oldrelid)) + delrelids = lappend_oid(delrelids, oldrelid); + } + + /* Drop old EXCEPT entries not present in the new list. */ + foreach_oid(relid, delrelids) + { + Oid proid; + ObjectAddress obj; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + /* Add new EXCEPT entries, skipping any already present. */ + PublicationAddTables(pubid, rels, true, stmt); + CloseTableList(rels); } } @@ -2362,6 +2432,7 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) foreach(lc, schemas) { Oid schemaid = lfirst_oid(lc); + List *except_relids; psid = GetSysCacheOid2(PUBLICATIONNAMESPACEMAP, Anum_pg_publication_namespace_oid, @@ -2378,8 +2449,40 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) get_namespace_name(schemaid)))); } + /* + * Collect EXCEPT entries for tables belonging to this schema before + * removing the schema entry. + */ + except_relids = GetExcludedPublicationTables(pubid, PUBLICATION_PART_ROOT); + ObjectAddressSet(obj, PublicationNamespaceRelationId, psid); performDeletion(&obj, DROP_CASCADE, 0); + + /* + * Drop any prexcept rows for tables belonging to this schema. These + * rows have no pg_depend entry pointing at the + * pg_publication_namespace row, so they are not cascaded by the + * performDeletion() call above and must be cleaned up explicitly. + */ + foreach_oid(relid, except_relids) + { + Oid proid; + + if (get_rel_namespace(relid) != schemaid) + continue; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + list_free(except_relids); } } diff --git a/src/backend/replication/pgoutput/pgoutput.c b/src/backend/replication/pgoutput/pgoutput.c index 7ee84ec1c83..9831be54b47 100644 --- a/src/backend/replication/pgoutput/pgoutput.c +++ b/src/backend/replication/pgoutput/pgoutput.c @@ -2229,7 +2229,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) */ if (pub->alltables) { - List *exceptpubids = NIL; + List *except_pubids = NIL; if (am_partition) { @@ -2252,7 +2252,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) * clause. Therefore, for a partition, exclusion must be * evaluated at the top-most ancestor. */ - exceptpubids = GetRelationExcludedPublications(last_ancestor_relid); + except_pubids = GetRelationExcludedPublications(last_ancestor_relid); } else { @@ -2260,13 +2260,13 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) * For a regular table or a root partitioned table, check * exclusion on table itself. */ - exceptpubids = GetRelationExcludedPublications(pub_relid); + except_pubids = GetRelationExcludedPublications(pub_relid); } - if (!list_member_oid(exceptpubids, pub->oid)) + if (!list_member_oid(except_pubids, pub->oid)) publish = true; - list_free(exceptpubids); + list_free(except_pubids); if (!publish) continue; diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index a290902d61e..e8bfb36cb1c 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2390,6 +2390,23 @@ match_previous_words(int pattern_id, } else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) COMPLETE_WITH(")"); + /* After a single schema name in SET context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 8b49239b574..35db7e1ff6d 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -594,6 +594,92 @@ Except tables: "pub_test.testpub_tbl_s1" "pub_test.testpub_tbl_s2" +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s2" + +-- fail: table in EXCEPT clause also appears in the explicit table list +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot appear in both the table list and the EXCEPT clause +-- error: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 1: ...xcept SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.tes... + ^ +-- SET: unqualified name in EXCEPT is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- SET without EXCEPT clears the existing except list +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + +-- SET to a different schema removes old schema's EXCEPT entries +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA public; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "public" + +-- fail: nonexistent table in EXCEPT clause (SET path) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- SET: multiple schemas each with their own EXCEPT clause +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- error: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +ERROR: EXCEPT clause is not supported with DROP in ALTER PUBLICATION +-- DROP TABLES IN SCHEMA removes associated EXCEPT entries +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "public" +Except tables: + "public.testpub_tbl1" + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index e9387418904..9b714639c75 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -296,6 +296,44 @@ ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (tes ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); \dRp+ testpub_alter_except +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + +-- fail: table in EXCEPT clause also appears in the explicit table list +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- error: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- SET: unqualified name in EXCEPT is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +\dRp+ testpub_alter_except + +-- SET without EXCEPT clears the existing except list +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + +-- SET to a different schema removes old schema's EXCEPT entries +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA public; +\dRp+ testpub_alter_except + +-- fail: nonexistent table in EXCEPT clause (SET path) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- SET: multiple schemas each with their own EXCEPT clause +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_alter_except + +-- error: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); + +-- DROP TABLES IN SCHEMA removes associated EXCEPT entries +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 0ba6d6f8bb2..01eafb5b7c8 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -376,6 +376,61 @@ $result = is($result, qq(0), 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); +# SET: replace the except list; tab_excluded is now included and tab_published is excluded. +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_published)" +); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (7); + INSERT INTO sch1.tab_excluded VALUES (7); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded WHERE a = 7"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: newly included table is replicated' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published WHERE a = 7"); +is($result, qq(0), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: now-excluded table is not replicated' +); + +# SET without EXCEPT: clears the except list; both tables are now published. +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1"); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (8); + INSERT INTO sch1.tab_excluded VALUES (8); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published WHERE a = 8"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_published replicated after except list cleared' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded WHERE a = 8"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_excluded replicated after except list cleared' +); + $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); @@ -443,6 +498,36 @@ $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); +# OK when a table is excluded by a TABLES IN SCHEMA EXCEPT publication, +# but is included by another publication. +$node_publisher->safe_psql('postgres', 'TRUNCATE tab1'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE tab1'); + +$node_publisher->safe_psql( + 'postgres', qq( + CREATE PUBLICATION tap_pub1 FOR TABLES IN SCHEMA public EXCEPT (TABLE public.tab1); + CREATE PUBLICATION tap_pub2 FOR TABLE tab1; + INSERT INTO tab1 VALUES(1); +)); +$node_subscriber->psql('postgres', + "CREATE SUBSCRIPTION tap_sub CONNECTION '$publisher_connstr' PUBLICATION tap_pub1, tap_pub2" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'tap_sub'); + +$node_publisher->safe_psql('postgres', qq(INSERT INTO tab1 VALUES(2))); +$node_publisher->wait_for_catchup('tap_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT * FROM tab1 ORDER BY a"); +is( $result, qq(1 +2), + "TABLES IN SCHEMA EXCEPT: table excluded in schema pub but included by another pub is replicated" +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); + $node_publisher->stop('fast'); done_testing(); -- 2.50.1 (Apple Git-155)
^ permalink raw reply [nested|flat] 196+ messages in thread

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-06-09 21:36  Zsolt Parragi <zsolt.parragi@percona.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  1 sibling, 1 reply; 196+ messages in thread

From: Zsolt Parragi @ 2026-06-09 21:36 UTC (permalink / raw)
  To: pgsql-hackers@lists.postgresql.org

> Do you mean other.t should be there?

Yes, that was a typo in my example.

> After considering, I chose to follow behavior similar to existing FOR
> ALL TABLES publications to handle schema-switch cases. Today, if a
> table excluded via EXCEPT is dropped, the corresponding prexcept entry
> is removed, and recreating a table with the same name does not
> automatically restore the exclusion.
>
> I applied the same principle to schema changes: once an excluded table
> moves out of the schema, the exclusion is removed.

I'm not that sure about the analogy. DROP TABLE is a destructive
operation, executing DROP TABLE and then CREATE TABLE won't
automatically bring back the data.

With this approach, two cheap ALTER TABLE ... SET SCHEMA statements
can clear an EXCEPT clause without the proper permissions.

But I'm not sure what's the best solution for this. The v11 approach
is at least more consistent than the previous behavior.

> 1) Reject the schema change: Error out if a table with a prexcept
> entry is moved between schemas. This feels overly restrictive.

It is restrictive, but maybe it's the better solution? Or
alternatively, maybe it should require proper permissions to remove
the except clause?

Another thing that could improve this if we would print out a warning
that the statement caused a change in the publication? But then that's
also a question for the preexisting drop table case.





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-06-10 04:36  Peter Smith <smithpb2250@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  1 sibling, 1 reply; 196+ messages in thread

From: Peter Smith @ 2026-06-10 04:36 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

Hi Nisha.

Some review comments for v11-0001.

(I had no new review comments for v11-0002, v11-0003)

======
doc/src/sgml/ref/create_publication.sgml

1.
+     <para>
+      For <literal>FOR TABLES IN SCHEMA</literal> publications, the
+      <literal>EXCEPT</literal> clause is schema-scoped: the exclusion applies
+      only in the context of the schema to which it was attached.  If a table
+      listed in the <literal>EXCEPT</literal> clause is later moved to a
+      different schema using <command>ALTER TABLE ... SET SCHEMA</command>,
+      the exclusion is removed.  The table will then be published if its new
+      schema is part of a publication.  If the table is moved back to
+      the original schema, the exclusion is not restored; the user must
+      re-establish it explicitly using <command>ALTER PUBLICATION</command>.
+      Dropping a table always removes it from the <literal>EXCEPT</literal>
+      list regardless of publication type.
+     </para>

1a.
I felt this should be moved up to be the 2nd paragraph of the "EXCEPT"
part. Subsequent information about
inheritance/partitions/multi-publications is common for both EXCEPTS.

~

1b.
All that info about "If a table..." seemed more relevant to ALTER
PUBLICATION than to CREATE PUBLICATION, so I didn't think we needed
those details here.

======
src/backend/commands/publicationcmds.c

RemovePublicationExceptForRelation:

2.
+/*
+ * Remove any EXCEPT clause entries for a relation from schema publications.
+ * Called when a table changes schema (ALTER TABLE ... SET SCHEMA), so that
+ * a schema-scoped exclusion does not silently follow the table to its new
+ * schema.  FOR ALL TABLES publications are skipped because their EXCEPT
+ * clause is publication-scoped, not schema-scoped, so that exclusion should
+ * persist regardless of what schema the table is in.
+ */

Instead of saying "FOR ALL TABLES publications are skipped", rephrase
that to be something like: "This problem does not apply to FOR ALL
TABLES publications because..."

Anyway, I think you can remove that note from the function comment,
and instead put it here:
+ if (!is_schema_publication(pubid))
+ continue;

~~~

3.
+{
+ List    *pubids;
+ ListCell   *lc;
+ ObjectAddress obj;
+
+ pubids = GetRelationExcludedPublications(relid);
+
+ foreach(lc, pubids)

Using a `foreach_oid` loop might be tidier here.

======
src/backend/commands/tablecmds.c

4.
  table_close(classRel, RowExclusiveLock);
+
+ /*
+ * Remove any EXCEPT clause entries for this relation from schema
+ * publications.  A schema-scoped exclusion is no longer meaningful once
+ * the table moves to a different schema.
+ */
+ if (rel->rd_rel->relkind == RELKIND_RELATION ||
+ rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
+ RemovePublicationExceptForRelation(RelationGetRelid(rel));

Should this code be put prior to the table_close, where the other
dependent stuff is also removed?

======
src/backend/parser/gram.y

5.
+ /* For TABLES_IN_CUR_SCHEMA: leave except_tables for execution time */

Isn't this repeating exactly what you already said in the other
comment ("For TABLES_IN_CUR_SCHEMA the schema name is not yet
known...")?

======
src/test/regress/sql/publication.sql

6.
+-- test for EXCEPT clause with schema publication (bug: excluded
table was incorrectly returned)
+SELECT * FROM test_gpt(ARRAY['pub_schema_except'],
'gpt_test_sch.tbl_sch'); -- no result (excluded)
+SELECT * FROM test_gpt(ARRAY['pub_schema_except'],
'gpt_test_sch.tbl_sch2'); -- one row (included via schema)
+

Is that "(bug: ...)" comment necessary?

======
Kind Regards,
Peter Smith.
Fujitsu Australia





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-06-10 09:03  Nisha Moond <nisha.moond412@gmail.com>
  parent: Zsolt Parragi <zsolt.parragi@percona.com>
  0 siblings, 1 reply; 196+ messages in thread

From: Nisha Moond @ 2026-06-10 09:03 UTC (permalink / raw)
  To: Zsolt Parragi <zsolt.parragi@percona.com>; +Cc: pgsql-hackers@lists.postgresql.org

On Wed, Jun 10, 2026 at 3:06 AM Zsolt Parragi <zsolt.parragi@percona.com> wrote:
>
> > Do you mean other.t should be there?
>
> Yes, that was a typo in my example.
>
> > After considering, I chose to follow behavior similar to existing FOR
> > ALL TABLES publications to handle schema-switch cases. Today, if a
> > table excluded via EXCEPT is dropped, the corresponding prexcept entry
> > is removed, and recreating a table with the same name does not
> > automatically restore the exclusion.
> >
> > I applied the same principle to schema changes: once an excluded table
> > moves out of the schema, the exclusion is removed.
>
> I'm not that sure about the analogy. DROP TABLE is a destructive
> operation, executing DROP TABLE and then CREATE TABLE won't
> automatically bring back the data.
>
> With this approach, two cheap ALTER TABLE ... SET SCHEMA statements
> can clear an EXCEPT clause without the proper permissions.
>

We already have similar behavior today. A non-publication owner can
run ALTER TABLE ... SET SCHEMA and remove a table from a FOR TABLES IN
SCHEMA publication without any warning or publication-level permission
check.

> But I'm not sure what's the best solution for this. The v11 approach
> is at least more consistent than the previous behavior.
>
> > 1) Reject the schema change: Error out if a table with a prexcept
> > entry is moved between schemas. This feels overly restrictive.
>
> It is restrictive, but maybe it's the better solution? Or
> alternatively, maybe it should require proper permissions to remove
> the except clause?
>

My concern is that introducing a permission check only for the EXCEPT
case would create an inconsistency: one type of schema move affecting
publication behavior would require publication ownership, while
another would not.

That said, I'm okay with restricting schema changes for tables in an
EXCEPT list if others feel that's the right behavior. Let's wait for
feedback from others.

> Another thing that could improve this if we would print out a warning
> that the statement caused a change in the publication? But then that's
> also a question for the preexisting drop table case.
>

Right, As also mentioned above, ALTER TABLE changes that affect
publication membership currently do not emit any notice or warning, so
I'm not sure we need one here either.

--
Thanks,
Nisha





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-06-10 10:26  Nisha Moond <nisha.moond412@gmail.com>
  parent: Peter Smith <smithpb2250@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: Nisha Moond @ 2026-06-10 10:26 UTC (permalink / raw)
  To: Peter Smith <smithpb2250@gmail.com>; +Cc: Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Wed, Jun 10, 2026 at 10:07 AM Peter Smith <smithpb2250@gmail.com> wrote:
>
> Hi Nisha.
>
> Some review comments for v11-0001.
>
> (I had no new review comments for v11-0002, v11-0003)
>

Thanks for the review. I've addressed all the comments as suggested
and attached the updated v12 patch set.

--
Thanks,
Nisha

Attachments: download all (3 files, .tar.gz)

v12-0001-Support-EXCEPT-clause-for-schema-level-publicati.patch (application/octet-stream, 62.4K) download From a42af50e9d5fb0d65715b6400637c8625bf27711 Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Mon, 4 May 2026 12:49:27 +0530 Subject: [PATCH v12 1/3] Support EXCEPT clause for schema-level publications Extend table exclusion support in publications to allow specific tables to be excluded from schema-level publications using an EXCEPT clause in CREATE PUBLICATION. Supported syntax: CREATE PUBLICATION <pub> FOR TABLES IN SCHEMA s EXCEPT (TABLE t1,...); --- doc/src/sgml/logical-replication.sgml | 3 +- doc/src/sgml/ref/create_publication.sgml | 29 +++- src/backend/catalog/pg_publication.c | 161 ++++++++++++++++---- src/backend/commands/publicationcmds.c | 137 +++++++++++++++-- src/backend/commands/tablecmds.c | 10 ++ src/backend/parser/gram.y | 54 ++++++- src/backend/replication/pgoutput/pgoutput.c | 30 +++- src/bin/psql/describe.c | 18 +++ src/bin/psql/tab-complete.in.c | 35 ++++- src/include/catalog/pg_publication.h | 3 +- src/include/commands/publicationcmds.h | 1 + src/include/nodes/parsenodes.h | 2 + src/test/regress/expected/publication.out | 144 ++++++++++++++++- src/test/regress/sql/publication.sql | 88 ++++++++++- src/test/subscription/t/037_except.pl | 133 +++++++++++++++- 15 files changed, 791 insertions(+), 57 deletions(-) diff --git a/doc/src/sgml/logical-replication.sgml b/doc/src/sgml/logical-replication.sgml index 9e7868487de..1433d2660fe 100644 --- a/doc/src/sgml/logical-replication.sgml +++ b/doc/src/sgml/logical-replication.sgml @@ -117,7 +117,8 @@ or <literal>FOR ALL SEQUENCES</literal>. Unlike tables, sequences can be synchronized at any time. For more information, see <xref linkend="logical-replication-sequences"/>. When a publication is - created with <literal>FOR ALL TABLES</literal>, a table or set of tables can + created with <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal>, a table or set of tables can be explicitly excluded from publication using the <link linkend="sql-createpublication-params-for-except-table"><literal>EXCEPT</literal></link> clause. diff --git a/doc/src/sgml/ref/create_publication.sgml b/doc/src/sgml/ref/create_publication.sgml index f82d640e6ca..d5c88f206f0 100644 --- a/doc/src/sgml/ref/create_publication.sgml +++ b/doc/src/sgml/ref/create_publication.sgml @@ -28,7 +28,7 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA <replaceable class="parameter">tables_in_schema</replaceable> [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -39,6 +39,10 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <replaceable class="parameter">table_object</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] [ WHERE ( <replaceable class="parameter">expression</replaceable> ) ] +<phrase>and <replaceable class="parameter">tables_in_schema</replaceable> is:</phrase> + + { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] + <phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> TABLE <replaceable class="parameter">table_object</replaceable> [, ... ] @@ -142,6 +146,8 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <para> Marks the publication as one that replicates changes for all tables in the specified list of schemas, including tables created in the future. + Tables listed in the <literal>EXCEPT</literal> clause for a given schema + are excluded from the publication. </para> <para> @@ -173,7 +179,7 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <para> Marks the publication as one that replicates changes for all tables in the database, including tables created in the future. Tables listed in - <literal>EXCEPT</literal> clause are excluded from the publication. + the <literal>EXCEPT</literal> clause are excluded from the publication. </para> </listitem> </varlistentry> @@ -198,7 +204,15 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <listitem> <para> This clause specifies a list of tables to be excluded from the - publication. + publication. It can be used with <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal>. + </para> + <para> + For <literal>FOR TABLES IN SCHEMA</literal> publications, the + <literal>EXCEPT</literal> clause is schema-scoped: the exclusion applies + only within the schema to which it was attached. For + <literal>FOR ALL TABLES</literal> publications, the exclusion applies to + the table regardless of the schema it is in. </para> <para> For inherited tables, if <literal>ONLY</literal> is specified before the @@ -515,6 +529,15 @@ CREATE PUBLICATION production_publication FOR TABLE users, departments, TABLES I CREATE PUBLICATION sales_publication FOR TABLES IN SCHEMA marketing, sales; </programlisting></para> + <para> + Create a publication that publishes all changes for all the tables present in + the schema <structname>sales</structname>, except + <structname>internal</structname> and <structname>drafts</structname>: +<programlisting> +CREATE PUBLICATION sales_filtered FOR TABLES IN SCHEMA sales EXCEPT (TABLE internal, drafts); +</programlisting> + </para> + <para> Create a publication that publishes all changes for table <structname>users</structname>, but replicates only columns <structname>user_id</structname> and diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index 5c457d9aca8..4089b505f89 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -444,13 +444,19 @@ GetPubPartitionOptionRelations(List *result, PublicationPartOpt pub_partopt, * * Note that the list of ancestors should be ordered such that the topmost * ancestor is at the end of the list. + * + * except_pubids is a list of publication OIDs whose schema membership + * should be ignored for the ancestor (because the ancestor is in their + * EXCEPT clause). */ Oid -GetTopMostAncestorInPublication(Oid puboid, List *ancestors, int *ancestor_level) +GetTopMostAncestorInPublication(Oid puboid, List *ancestors, + int *ancestor_level, List *except_pubids) { ListCell *lc; Oid topmost_relid = InvalidOid; int level = 0; + bool check_schemas = !list_member_oid(except_pubids, puboid); /* * Find the "topmost" ancestor that is in this publication. @@ -470,7 +476,7 @@ GetTopMostAncestorInPublication(Oid puboid, List *ancestors, int *ancestor_level if (ancestor_level) *ancestor_level = level; } - else + else if (check_schemas) { aschemaPubids = GetSchemaPublications(get_rel_namespace(ancestor)); if (list_member_oid(aschemaPubids, puboid)) @@ -545,18 +551,30 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, * duplicates, it's here just to provide nicer error message in common * case. The real protection is the unique key on the catalog. */ - if (SearchSysCacheExists2(PUBLICATIONRELMAP, ObjectIdGetDatum(relid), - ObjectIdGetDatum(pubid))) + tup = SearchSysCache2(PUBLICATIONRELMAP, ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + + if (HeapTupleIsValid(tup)) { + bool is_except = ((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept; + + ReleaseSysCache(tup); table_close(rel, RowExclusiveLock); if (if_not_exists) return InvalidObjectAddress; - ereport(ERROR, - (errcode(ERRCODE_DUPLICATE_OBJECT), - errmsg("relation \"%s\" is already member of publication \"%s\"", - RelationGetRelationName(targetrel), pub->name))); + if (is_except) + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("table \"%s\" cannot be added because it is excluded from publication \"%s\"", + RelationGetQualifiedRelationName(targetrel), + pub->name))); + else + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("relation \"%s\" is already member of publication \"%s\"", + RelationGetRelationName(targetrel), pub->name))); } check_publication_add_relation(pri); @@ -982,12 +1000,13 @@ GetIncludedPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) * Gets list of table oids that were specified in the EXCEPT clause for a * publication. * - * This should only be used FOR ALL TABLES publications. + * This is used for FOR ALL TABLES and FOR TABLES IN SCHEMA publications, + * both of which support EXCEPT TABLE. */ List * GetExcludedPublicationTables(Oid pubid, PublicationPartOpt pub_partopt) { - Assert(GetPublication(pubid)->alltables); + Assert(GetPublication(pubid)->alltables || is_schema_publication(pubid)); return get_publication_relations(pubid, pub_partopt, true); } @@ -1049,15 +1068,15 @@ GetAllPublicationRelations(Oid pubid, char relkind, bool pubviaroot) TableScanDesc scan; HeapTuple tuple; List *result = NIL; - List *exceptlist = NIL; + List *except_relids = NIL; Assert(!(relkind == RELKIND_SEQUENCE && pubviaroot)); /* EXCEPT filtering applies only to relations, not sequences */ if (relkind == RELKIND_RELATION) - exceptlist = GetExcludedPublicationTables(pubid, pubviaroot ? - PUBLICATION_PART_ROOT : - PUBLICATION_PART_LEAF); + except_relids = GetExcludedPublicationTables(pubid, pubviaroot ? + PUBLICATION_PART_ROOT : + PUBLICATION_PART_LEAF); classRel = table_open(RelationRelationId, AccessShareLock); @@ -1075,7 +1094,7 @@ GetAllPublicationRelations(Oid pubid, char relkind, bool pubviaroot) if (is_publishable_class(relid, relForm) && !(relForm->relispartition && pubviaroot) && - !list_member_oid(exceptlist, relid)) + !list_member_oid(except_relids, relid)) result = lappend_oid(result, relid); } @@ -1097,7 +1116,7 @@ GetAllPublicationRelations(Oid pubid, char relkind, bool pubviaroot) if (is_publishable_class(relid, relForm) && !relForm->relispartition && - !list_member_oid(exceptlist, relid)) + !list_member_oid(except_relids, relid)) result = lappend_oid(result, relid); } @@ -1232,22 +1251,67 @@ GetSchemaPublicationRelations(Oid schemaid, PublicationPartOpt pub_partopt) /* * Gets the list of all relations published by FOR TABLES IN SCHEMA - * publication. + * publication, excluding any tables listed in the EXCEPT clause. */ List * GetAllSchemaPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) { List *result = NIL; List *pubschemalist = GetPublicationSchemas(pubid); + List *except_relids = NIL; ListCell *cell; + /* get the list of tables excluded via EXCEPT TABLE for this publication */ + if (pubschemalist != NIL) + except_relids = GetExcludedPublicationTables(pubid, pub_partopt); + foreach(cell, pubschemalist) { Oid schemaid = lfirst_oid(cell); List *schemaRels = NIL; schemaRels = GetSchemaPublicationRelations(schemaid, pub_partopt); - result = list_concat(result, schemaRels); + + if (except_relids != NIL) + { + /* filter out any tables that appear in the EXCEPT list */ + ListCell *rlc; + + foreach(rlc, schemaRels) + { + Oid relid = lfirst_oid(rlc); + bool excluded = list_member_oid(except_relids, relid); + + /* + * Also exclude any relation whose partition ancestor is in + * the EXCEPT list. This matters when pub_partopt is + * PUBLICATION_PART_ROOT: the except list holds only the root + * OID, but the schema scan may also return individual + * partition relations that live in the same schema. + */ + if (!excluded && get_rel_relispartition(relid)) + { + List *ancestors = get_partition_ancestors(relid); + ListCell *alc; + + foreach(alc, ancestors) + { + if (list_member_oid(except_relids, lfirst_oid(alc))) + { + excluded = true; + break; + } + } + list_free(ancestors); + } + + if (!excluded) + result = lappend_oid(result, relid); + } + list_free(schemaRels); + } + else + result = list_concat(result, schemaRels); } return result; @@ -1324,6 +1388,7 @@ is_table_publishable_in_publication(Oid relid, Publication *pub) { bool relispartition; List *ancestors = NIL; + HeapTuple tup; /* * For non-pubviaroot publications, a partitioned table is never the @@ -1380,20 +1445,62 @@ is_table_publishable_in_publication(Oid relid, Publication *pub) * If it's false, the partition is covered by its ancestor's presence in * the publication, it should be included (return true). */ - if (relispartition && - OidIsValid(GetTopMostAncestorInPublication(pub->oid, ancestors, NULL))) - return !pub->pubviaroot; + if (relispartition) + { + Oid ancestor_oid; + + ancestor_oid = GetTopMostAncestorInPublication(pub->oid, ancestors, NULL, NIL); + if (OidIsValid(ancestor_oid)) + { + /* + * The ancestor was found in the publication (via explicit + * membership or schema membership), but it may be excluded. Check + * for a prexcept row before concluding the partition is + * published. + */ + tup = SearchSysCache2(PUBLICATIONRELMAP, + ObjectIdGetDatum(ancestor_oid), + ObjectIdGetDatum(pub->oid)); + if (HeapTupleIsValid(tup)) + { + bool is_except; + + is_except = ((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept; + ReleaseSysCache(tup); + if (is_except) + return false; + } + return !pub->pubviaroot; + } + } /* * Check whether the table is explicitly published via pg_publication_rel * or pg_publication_namespace. + * + * A pg_publication_rel row with prexcept=true means the table is + * explicitly excluded via EXCEPT and must not be reported as published, + * even if its schema is otherwise included. A row with prexcept=false + * means it is explicitly included. If no pg_publication_rel row exists, + * the table is published iff its schema appears in + * pg_publication_namespace. */ - return (SearchSysCacheExists2(PUBLICATIONRELMAP, - ObjectIdGetDatum(relid), - ObjectIdGetDatum(pub->oid)) || - SearchSysCacheExists2(PUBLICATIONNAMESPACEMAP, - ObjectIdGetDatum(get_rel_namespace(relid)), - ObjectIdGetDatum(pub->oid))); + + tup = SearchSysCache2(PUBLICATIONRELMAP, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pub->oid)); + if (HeapTupleIsValid(tup)) + { + bool is_except; + + is_except = ((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept; + ReleaseSysCache(tup); + return !is_except; + } + + return SearchSysCacheExists2(PUBLICATIONNAMESPACEMAP, + ObjectIdGetDatum(get_rel_namespace(relid)), + ObjectIdGetDatum(pub->oid)); } /* diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 440adb356ad..49f6173be17 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -181,7 +181,7 @@ parse_publication_options(ParseState *pstate, */ static void ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, - List **rels, List **exceptrels, List **schemas) + List **rels, List **except_pubtables, List **schemas) { ListCell *cell; PublicationObjSpec *pubobj; @@ -200,7 +200,7 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, { case PUBLICATIONOBJ_EXCEPT_TABLE: pubobj->pubtable->except = true; - *exceptrels = lappend(*exceptrels, pubobj->pubtable); + *except_pubtables = lappend(*except_pubtables, pubobj->pubtable); break; case PUBLICATIONOBJ_TABLE: pubobj->pubtable->except = false; @@ -224,6 +224,38 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, /* Filter out duplicates if user specifies "sch1, sch1" */ *schemas = list_append_unique_oid(*schemas, schemaid); + + /* + * Qualify unqualified EXCEPT table names with the resolved + * current schema and reject any explicitly cross-schema + * entries. This mirrors the parse-time handling done for + * TABLES_IN_SCHEMA in preprocess_pubobj_list(), deferred here + * because CURRENT_SCHEMA is not known until execution time. + */ + if (pubobj->except_tables != NIL) + { + char *cur_schema_name = get_namespace_name(schemaid); + + foreach_ptr(PublicationObjSpec, eobj, pubobj->except_tables) + { + const char *eobj_schemaname = + eobj->pubtable->relation->schemaname; + const char *eobj_relname = + eobj->pubtable->relation->relname; + + if (eobj_schemaname == NULL) + eobj->pubtable->relation->schemaname = cur_schema_name; + else if (strcmp(eobj_schemaname, cur_schema_name) != 0) + ereport(ERROR, + errcode(ERRCODE_INVALID_OBJECT_DEFINITION), + errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", + quote_qualified_identifier(eobj_schemaname, eobj_relname), + cur_schema_name)); + + *except_pubtables = lappend(*except_pubtables, + eobj->pubtable); + } + } break; default: /* shouldn't happen */ @@ -305,7 +337,7 @@ pub_rf_contains_invalid_column(Oid pubid, Relation relation, List *ancestors, if (pubviaroot && relation->rd_rel->relispartition) { publish_as_relid - = GetTopMostAncestorInPublication(pubid, ancestors, NULL); + = GetTopMostAncestorInPublication(pubid, ancestors, NULL, NIL); if (!OidIsValid(publish_as_relid)) publish_as_relid = relid; @@ -389,7 +421,7 @@ pub_contains_invalid_column(Oid pubid, Relation relation, List *ancestors, */ if (pubviaroot && relation->rd_rel->relispartition) { - publish_as_relid = GetTopMostAncestorInPublication(pubid, ancestors, NULL); + publish_as_relid = GetTopMostAncestorInPublication(pubid, ancestors, NULL, NIL); if (!OidIsValid(publish_as_relid)) publish_as_relid = relid; @@ -849,7 +881,7 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) char publish_generated_columns; AclResult aclresult; List *relations = NIL; - List *exceptrelations = NIL; + List *except_pubtables = NIL; List *schemaidlist = NIL; /* must have CREATE privilege on database */ @@ -936,16 +968,16 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) /* Associate objects with the publication. */ ObjectsInPublicationToOids(stmt->pubobjects, pstate, &relations, - &exceptrelations, &schemaidlist); + &except_pubtables, &schemaidlist); if (stmt->for_all_tables) { /* Process EXCEPT table list */ - if (exceptrelations != NIL) + if (except_pubtables != NIL) { List *rels; - rels = OpenTableList(exceptrelations); + rels = OpenTableList(except_pubtables); PublicationAddTables(puboid, rels, true, NULL); CloseTableList(rels); } @@ -959,6 +991,8 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) } else if (!stmt->for_all_sequences) { + List *explicitrelids = NIL; + /* FOR TABLES IN SCHEMA requires superuser */ if (schemaidlist != NIL && !superuser()) ereport(ERROR, @@ -977,6 +1011,19 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) schemaidlist != NIL, publish_via_partition_root); + /* + * Collect explicit table OIDs now, before we close the relation + * list, so that except-table validation below can check for + * contradictions without relying on a catalog scan that might not + * yet see the just-inserted rows. + */ + if (except_pubtables != NIL) + { + foreach_ptr(PublicationRelInfo, pri, rels) + explicitrelids = lappend_oid(explicitrelids, + RelationGetRelid(pri->relation)); + } + PublicationAddTables(puboid, rels, true, NULL); CloseTableList(rels); } @@ -989,6 +1036,34 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) */ LockSchemaList(schemaidlist); PublicationAddSchemas(puboid, schemaidlist, true, NULL); + + if (except_pubtables != NIL) + { + List *except_rels; + + except_rels = OpenTableList(except_pubtables); + + /* + * Validate that each excluded table is not also in the + * explicit table list (which would be contradictory). Use the + * in-memory explicitrelids collected above rather than + * re-reading the catalog, which may not yet see the + * just-inserted rows. + */ + foreach_ptr(PublicationRelInfo, pri, except_rels) + { + Oid except_relid = RelationGetRelid(pri->relation); + + if (list_member_oid(explicitrelids, except_relid)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" cannot appear in both the table list and the EXCEPT clause", + RelationGetQualifiedRelationName(pri->relation))); + } + + PublicationAddTables(puboid, except_rels, true, NULL); + CloseTableList(except_rels); + } } } @@ -1683,12 +1758,12 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) else { List *relations = NIL; - List *exceptrelations = NIL; + List *except_pubtables = NIL; List *schemaidlist = NIL; Oid pubid = pubform->oid; ObjectsInPublicationToOids(stmt->pubobjects, pstate, &relations, - &exceptrelations, &schemaidlist); + &except_pubtables, &schemaidlist); CheckAlterPublication(stmt, tup, relations, schemaidlist); @@ -1711,7 +1786,7 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) errmsg("publication \"%s\" does not exist", stmt->pubname)); - relations = list_concat(relations, exceptrelations); + relations = list_concat(relations, except_pubtables); AlterPublicationTables(stmt, tup, relations, pstate->p_sourcetext, schemaidlist != NIL); AlterPublicationSchemas(stmt, tup, schemaidlist); @@ -1829,6 +1904,46 @@ RemovePublicationSchemaById(Oid psoid) table_close(rel, RowExclusiveLock); } +/* + * Remove any EXCEPT clause entries for a relation from schema publications. + * Called when a table changes schema (ALTER TABLE ... SET SCHEMA), so that + * a schema-scoped exclusion does not silently follow the table to its new + * schema. + */ +void +RemovePublicationExceptForRelation(Oid relid) +{ + List *pubids; + ObjectAddress obj; + + pubids = GetRelationExcludedPublications(relid); + + foreach_oid(pubid, pubids) + { + Oid proid; + + /* + * This problem does not apply to FOR ALL TABLES publications, because + * their EXCEPT clause is publication-scoped, not schema-scoped: the + * exclusion should persist regardless of what schema the table is in. + */ + if (!is_schema_publication(pubid)) + continue; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + list_free(pubids); +} + /* * Open relations specified by a PublicationTable list. * The returned tables are locked in ShareUpdateExclusiveLock mode in order to diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index a33e22e8e61..bd96b4fd025 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -63,6 +63,7 @@ #include "commands/event_trigger.h" #include "commands/extension.h" #include "commands/repack.h" +#include "commands/publicationcmds.h" #include "commands/sequence.h" #include "commands/tablecmds.h" #include "commands/tablespace.h" @@ -19290,6 +19291,15 @@ AlterTableNamespaceInternal(Relation rel, Oid oldNspOid, Oid nspOid, AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid, false, objsMoved); + /* + * Remove any EXCEPT clause entries for this relation from schema + * publications. A schema-scoped exclusion is no longer meaningful once + * the table moves to a different schema. + */ + if (rel->rd_rel->relkind == RELKIND_RELATION || + rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE) + RemovePublicationExceptForRelation(RelationGetRelid(rel)); + table_close(classRel, RowExclusiveLock); } diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y index ff4e1388c55..6a7a1bc5f8d 100644 --- a/src/backend/parser/gram.y +++ b/src/backend/parser/gram.y @@ -58,6 +58,7 @@ #include "nodes/makefuncs.h" #include "nodes/nodeFuncs.h" #include "parser/parser.h" +#include "utils/builtins.h" #include "utils/datetime.h" #include "utils/xml.h" @@ -11272,7 +11273,7 @@ AlterOwnerStmt: ALTER AGGREGATE aggregate_with_argtypes OWNER TO RoleSpec * pub_obj is one of: * * TABLE table [, ...] - * TABLES IN SCHEMA schema [, ...] + * TABLES IN SCHEMA schema [EXCEPT (TABLE table [, ...] )] [, ...] * *****************************************************************************/ @@ -11332,23 +11333,26 @@ PublicationObjSpec: $$->pubtable->columns = $3; $$->pubtable->whereClause = $4; } - | TABLES IN_P SCHEMA ColId + | TABLES IN_P SCHEMA ColId opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_SCHEMA; $$->name = $4; + $$->except_tables = $5; $$->location = @4; } - | TABLES IN_P SCHEMA CURRENT_SCHEMA + | TABLES IN_P SCHEMA CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_CUR_SCHEMA; + $$->except_tables = $5; $$->location = @4; } - | ColId opt_column_list OptWhereClause + | ColId opt_column_list OptWhereClause opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $4; /* * If either a row filter or column list is specified, create * a PublicationTable object. @@ -11392,10 +11396,11 @@ PublicationObjSpec: $$->pubtable->columns = $2; $$->pubtable->whereClause = $3; } - | CURRENT_SCHEMA + | CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $2; $$->location = @1; } ; @@ -20784,6 +20789,8 @@ preprocess_pub_all_objtype_list(List *all_objects_list, List **pubobjects, /* * Process pubobjspec_list to check for errors in any of the objects and * convert PUBLICATIONOBJ_CONTINUATION into appropriate PublicationObjSpecType. + * Also flattens except_tables from TABLES IN SCHEMA nodes into the list so + * that ObjectsInPublicationToOids() sees them as top-level EXCEPT_TABLE entries. */ static void preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) @@ -20812,6 +20819,13 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLE) { + /* EXCEPT is not valid for table objects */ + if (pubobj->except_tables != NIL) + ereport(ERROR, + errcode(ERRCODE_SYNTAX_ERROR), + errmsg("EXCEPT is not allowed for TABLE publication objects"), + parser_errposition(pubobj->location)); + /* relation name or pubtable must be set for this type of object */ if (!pubobj->name && !pubobj->pubtable) ereport(ERROR, @@ -20860,6 +20874,36 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) errcode(ERRCODE_SYNTAX_ERROR), errmsg("invalid schema name"), parser_errposition(pubobj->location)); + + /* + * For TABLES_IN_SCHEMA, qualify unqualified EXCEPT table names + * with the parent schema and reject cross-schema entries at parse + * time, then flatten into the top-level list. + * + * For TABLES_IN_CUR_SCHEMA the schema name is not yet known, so + * skip both steps here; ObjectsInPublicationToOids() will + * qualify names and validate schema membership at execution time. + */ + if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLES_IN_SCHEMA) + { + foreach_ptr(PublicationObjSpec, eobj, pubobj->except_tables) + { + const char *eobj_schemaname = eobj->pubtable->relation->schemaname; + const char *eobj_relname = eobj->pubtable->relation->relname; + + if (eobj_schemaname == NULL) + eobj->pubtable->relation->schemaname = pubobj->name; + else if (strcmp(eobj_schemaname, pubobj->name) != 0) + ereport(ERROR, + errcode(ERRCODE_INVALID_OBJECT_DEFINITION), + errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", + quote_qualified_identifier(eobj_schemaname, eobj_relname), + pubobj->name), + parser_errposition(eobj->location)); + } + pubobjspec_list = list_concat(pubobjspec_list, pubobj->except_tables); + pubobj->except_tables = NIL; + } } prevobjtype = pubobj->pubobjtype; diff --git a/src/backend/replication/pgoutput/pgoutput.c b/src/backend/replication/pgoutput/pgoutput.c index 4ecfcbff7ab..7ee84ec1c83 100644 --- a/src/backend/replication/pgoutput/pgoutput.c +++ b/src/backend/replication/pgoutput/pgoutput.c @@ -2097,6 +2097,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) * are absorbed while decoding WAL. */ List *schemaPubids = GetSchemaPublications(schemaId); + List *except_pubids; ListCell *lc; Oid publish_as_relid = relid; int publish_ancestor_level = 0; @@ -2104,6 +2105,28 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) char relkind = get_rel_relkind(relid); List *rel_publications = NIL; + /* + * For the schema EXCEPT check, we must look up the top-most ancestor + * rather than the relation itself. check_publication_add_relation() + * prevents individual partitions from appearing in the EXCEPT clause, + * so only a root (non-partition) table can have prexcept = true. + * Using the partition's own OID would always return NIL and miss the + * exclusion. + */ + Oid root_relid; + + if (am_partition) + { + List *ancestors = get_partition_ancestors(relid); + + root_relid = llast_oid(ancestors); + list_free(ancestors); + } + else + root_relid = relid; + + except_pubids = GetRelationExcludedPublications(root_relid); + /* Reload publications if needed before use. */ if (!publications_valid) { @@ -2267,7 +2290,8 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) ancestor = GetTopMostAncestorInPublication(pub->oid, ancestors, - &level); + &level, + except_pubids); if (ancestor != InvalidOid) { @@ -2281,7 +2305,8 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) } if (list_member_oid(pubids, pub->oid) || - list_member_oid(schemaPubids, pub->oid) || + (list_member_oid(schemaPubids, pub->oid) && + !list_member_oid(except_pubids, pub->oid)) || ancestor_published) publish = true; } @@ -2360,6 +2385,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) list_free(pubids); list_free(schemaPubids); + list_free(except_pubids); list_free(rel_publications); entry->replicate_valid = true; diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c index 7f9b2b71a36..a9ae6d31251 100644 --- a/src/bin/psql/describe.c +++ b/src/bin/psql/describe.c @@ -7038,6 +7038,24 @@ describePublications(const char *pattern) if (!addFooterToPublicationDesc(&buf, _("Tables from schemas:"), true, &cont)) goto error_return; + + if (pset.sversion >= 190000) + { + /* + * Get tables in the EXCEPT clause for this schema + * publication. + */ + printfPQExpBuffer(&buf, + "SELECT concat(c.relnamespace::regnamespace, '.', c.relname)\n" + "FROM pg_catalog.pg_class c\n" + " JOIN pg_catalog.pg_publication_rel pr ON c.oid = pr.prrelid\n" + "WHERE pr.prpubid = '%s'\n" + " AND pr.prexcept\n" + "ORDER BY 1", pubid); + if (!addFooterToPublicationDesc(&buf, _("Except tables:"), + true, &cont)) + goto error_return; + } } } else diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index de547a8cb37..53bb7c8679b 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -1065,6 +1065,24 @@ static const SchemaQuery Query_for_trigger_of_table = { "SELECT nspname FROM pg_catalog.pg_namespace "\ " WHERE nspname LIKE '%s'" +#define Query_for_list_of_tables_in_schema \ +"SELECT n.nspname || '.' || c.relname "\ +" FROM pg_catalog.pg_class c "\ +" JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "\ +" WHERE c.relkind IN (" CppAsString2(RELKIND_RELATION) ", " \ + CppAsString2(RELKIND_PARTITIONED_TABLE) ") "\ +" AND (n.nspname || '.' || c.relname) LIKE '%s' "\ +" AND n.nspname = '%s'" + +#define Query_for_list_of_tables_in_current_schema \ +"SELECT c.relname "\ +" FROM pg_catalog.pg_class c "\ +" JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "\ +" WHERE c.relkind IN (" CppAsString2(RELKIND_RELATION) ", " \ + CppAsString2(RELKIND_PARTITIONED_TABLE) ") "\ +" AND c.relname LIKE '%s' "\ +" AND n.nspname = pg_catalog.current_schema()" + /* Use COMPLETE_WITH_QUERY_VERBATIM with these queries for GUC names: */ #define Query_for_list_of_alter_system_set_vars \ "SELECT pg_catalog.lower(name) FROM pg_catalog.pg_settings "\ @@ -3787,8 +3805,21 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); - else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && (!ends_with(prev_wd, ','))) - COMPLETE_WITH("WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE", "WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* Complete "CREATE PUBLICATION <name> [...] WITH" */ else if (Matches("CREATE", "PUBLICATION", MatchAnyN, "WITH", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/include/catalog/pg_publication.h b/src/include/catalog/pg_publication.h index 89b4bb14f62..53e3d7c6f3d 100644 --- a/src/include/catalog/pg_publication.h +++ b/src/include/catalog/pg_publication.h @@ -191,7 +191,8 @@ extern List *GetPubPartitionOptionRelations(List *result, PublicationPartOpt pub_partopt, Oid relid); extern Oid GetTopMostAncestorInPublication(Oid puboid, List *ancestors, - int *ancestor_level); + int *ancestor_level, + List *except_pubids); extern bool is_publishable_relation(Relation rel); extern bool is_schema_publication(Oid pubid); diff --git a/src/include/commands/publicationcmds.h b/src/include/commands/publicationcmds.h index 4cf45c17cc5..93c77331437 100644 --- a/src/include/commands/publicationcmds.h +++ b/src/include/commands/publicationcmds.h @@ -27,6 +27,7 @@ extern void AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt); extern void RemovePublicationById(Oid pubid); extern void RemovePublicationRelById(Oid proid); extern void RemovePublicationSchemaById(Oid psoid); +extern void RemovePublicationExceptForRelation(Oid relid); extern ObjectAddress AlterPublicationOwner(const char *name, Oid newOwnerId); extern void AlterPublicationOwner_oid(Oid pubid, Oid newOwnerId); diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h index 91377a6cde3..98a03c0eeda 100644 --- a/src/include/nodes/parsenodes.h +++ b/src/include/nodes/parsenodes.h @@ -4493,6 +4493,8 @@ typedef struct PublicationObjSpec PublicationObjSpecType pubobjtype; /* type of this publication object */ char *name; PublicationTable *pubtable; + List *except_tables; /* tables specified in the EXCEPT clause (for + * TABLES IN SCHEMA) */ ParseLoc location; /* token location, or -1 if unknown */ } PublicationObjSpec; diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 29e54b214a0..ba01c720d4e 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -270,6 +270,12 @@ CREATE PUBLICATION testpub_foralltables_excepttable2 FOR ALL TABLES EXCEPT (test ERROR: syntax error at or near "testpub_tbl1" LINE 1: ..._foralltables_excepttable2 FOR ALL TABLES EXCEPT (testpub_tb... ^ +-- fail - EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testpub_tbl3); +ERROR: EXCEPT is not allowed for TABLE publication objects +LINE 2: FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testp... + ^ --------------------------------------------- -- SET ALL TABLES/SEQUENCES --------------------------------------------- @@ -470,7 +476,103 @@ HINT: Change the publication's EXCEPT clause using ALTER PUBLICATION ... SET AL RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Create same-named tables in public to verify unqualified EXCEPT entries +-- are qualified with the named schema, not public +CREATE TABLE testpub_nopk (foo int, bar int); +CREATE TABLE testpub_tbl_s1 (a int primary key, b text); +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + Publication testpub_schema_except1 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- Exclude multiple tables using unqualified names; same-named tables exist in +-- public to confirm unqualified names resolve to pub_test, not public +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + Publication testpub_schema_except2 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_nopk" + "pub_test.testpub_tbl_s1" + +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testp... + ^ +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); +ERROR: table "pub_test.testpub_tbl_s1" in EXCEPT clause does not belong to schema "public" +LINE 2: ...R TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.t... + ^ +-- Multiple schemas each with their own EXCEPT clause +CREATE PUBLICATION testpub_schema_except_multi + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_schema_except_multi + Publication testpub_schema_except_multi + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- fail: table appears in both the explicit table list and the EXCEPT clause +CREATE PUBLICATION testpub_except_conflict + FOR TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot appear in both the table list and the EXCEPT clause +-- fail: nonexistent table in EXCEPT clause +CREATE PUBLICATION testpub_except_norel + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- fail: partition cannot appear in EXCEPT clause; only root tables are allowed +CREATE TABLE pub_test.testpub_parted_s (a int) PARTITION BY LIST (a); +CREATE TABLE pub_test.testpub_part_s PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (1); +CREATE PUBLICATION testpub_except_partition + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); +ERROR: cannot specify relation "pub_test.testpub_part_s" in the publication EXCEPT clause +DETAIL: This operation is not supported for individual partitions. +-- fail: TABLE keyword is required for the first entry in the EXCEPT clause +CREATE PUBLICATION testpub_except_nokw + FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +ERROR: syntax error at or near "testpub_nopk" +LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + ^ +-- Cleanup +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP TABLE pub_test.testpub_parted_s CASCADE; +DROP TABLE testpub_nopk, testpub_tbl_s1; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +--------------------------------------------- +-- Tests for publications with SEQUENCES +--------------------------------------------- CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; -- FOR ALL SEQUENCES @@ -1953,6 +2055,27 @@ ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b); ERROR: column specification not allowed for schema LINE 1: ...TION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b)... ^ +-- EXCEPT clause with CURRENT_SCHEMA: cross-schema entry must be rejected +SET search_path = pub_test1; +-- qualified name from wrong schema -> error +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.tbl1); +ERROR: table "pub_test2.tbl1" in EXCEPT clause does not belong to schema "pub_test1" +-- unqualified name implicitly qualified with current schema (pub_test1.tbl) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl); +RESET client_min_messages; +\dRp+ testpub_cursch_except + Publication testpub_cursch_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test1" +Except tables: + "pub_test1.tbl" + +DROP PUBLICATION testpub_cursch_except; +RESET search_path; -- cleanup pub_test1 schema for invalidation tests ALTER PUBLICATION testpub2_forschema DROP TABLES IN SCHEMA pub_test1; DROP PUBLICATION testpub3_forschema, testpub4_forschema, testpub5_forschema, testpub6_forschema, testpub_fortable; @@ -2304,6 +2427,7 @@ DROP ROLE regress_publication_user_dummy; -- Test pg_get_publication_tables(text[], oid) function CREATE SCHEMA gpt_test_sch; CREATE TABLE gpt_test_sch.tbl_sch (id int); +CREATE TABLE gpt_test_sch.tbl_sch2 (id int); CREATE TABLE tbl_normal (id int); CREATE TABLE tbl_parent (id1 int, id2 int, id3 int) PARTITION BY RANGE (id1); CREATE TABLE tbl_part1 PARTITION OF tbl_parent FOR VALUES FROM (1) TO (10); @@ -2314,6 +2438,7 @@ CREATE PUBLICATION pub_all_no_viaroot FOR ALL TABLES WITH (publish_via_partition CREATE PUBLICATION pub_all_except FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = true); CREATE PUBLICATION pub_all_except_no_viaroot FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_schema FOR TABLES IN SCHEMA gpt_test_sch; +CREATE PUBLICATION pub_schema_except FOR TABLES IN SCHEMA gpt_test_sch EXCEPT (TABLE gpt_test_sch.tbl_sch); CREATE PUBLICATION pub_normal FOR TABLE tbl_normal WHERE (id < 10); CREATE PUBLICATION pub_part_leaf FOR TABLE tbl_part1 WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_part_parent FOR TABLE tbl_parent (id1, id2) WHERE (id1 = 10) WITH (publish_via_partition_root = true); @@ -2465,6 +2590,18 @@ SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_part1'); -- no r ---------+---------+-------+------ (0 rows) +-- test for EXCEPT clause with schema publication +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch'); -- no result (excluded) + pubname | relname | attrs | qual +---------+---------+-------+------ +(0 rows) + +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch2'); -- one row (included via schema) + pubname | relname | attrs | qual +-------------------+----------+-------+------ + pub_schema_except | tbl_sch2 | 1 | +(1 row) + -- two rows with different row filter SELECT * FROM test_gpt(ARRAY['pub_all', 'pub_normal'], 'tbl_normal'); pubname | relname | attrs | qual @@ -2517,6 +2654,7 @@ DROP PUBLICATION pub_all_no_viaroot; DROP PUBLICATION pub_all_except; DROP PUBLICATION pub_all_except_no_viaroot; DROP PUBLICATION pub_schema; +DROP PUBLICATION pub_schema_except; DROP PUBLICATION pub_normal; DROP PUBLICATION pub_part_leaf; DROP PUBLICATION pub_part_parent; @@ -2525,7 +2663,9 @@ DROP PUBLICATION pub_part_parent_child; DROP VIEW gpt_test_view; DROP TABLE tbl_normal, tbl_parent, tbl_part1; DROP SCHEMA gpt_test_sch CASCADE; -NOTICE: drop cascades to table gpt_test_sch.tbl_sch +NOTICE: drop cascades to 2 other objects +DETAIL: drop cascades to table gpt_test_sch.tbl_sch +drop cascades to table gpt_test_sch.tbl_sch2 -- stage objects for pg_dump tests CREATE SCHEMA pubme CREATE TABLE t0 (c int, d int) CREATE TABLE t1 (c int); CREATE SCHEMA pubme2 CREATE TABLE t0 (c int, d int); diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 041e14a4de6..4bc0e2ff23d 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -123,6 +123,9 @@ CREATE PUBLICATION testpub_foralltables_excepttable1 FOR ALL TABLES EXCEPT (TABL \d testpub_tbl1 -- fail - first table in the EXCEPT list should use TABLE keyword CREATE PUBLICATION testpub_foralltables_excepttable2 FOR ALL TABLES EXCEPT (testpub_tbl1, testpub_tbl2); +-- fail - EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testpub_tbl3); --------------------------------------------- -- SET ALL TABLES/SEQUENCES @@ -220,7 +223,71 @@ RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Create same-named tables in public to verify unqualified EXCEPT entries +-- are qualified with the named schema, not public +CREATE TABLE testpub_nopk (foo int, bar int); +CREATE TABLE testpub_tbl_s1 (a int primary key, b text); + +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + +-- Exclude multiple tables using unqualified names; same-named tables exist in +-- public to confirm unqualified names resolve to pub_test, not public +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); + +-- Multiple schemas each with their own EXCEPT clause +CREATE PUBLICATION testpub_schema_except_multi + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_schema_except_multi + +-- fail: table appears in both the explicit table list and the EXCEPT clause +CREATE PUBLICATION testpub_except_conflict + FOR TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: nonexistent table in EXCEPT clause +CREATE PUBLICATION testpub_except_norel + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- fail: partition cannot appear in EXCEPT clause; only root tables are allowed +CREATE TABLE pub_test.testpub_parted_s (a int) PARTITION BY LIST (a); +CREATE TABLE pub_test.testpub_part_s PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (1); +CREATE PUBLICATION testpub_except_partition + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); + +-- fail: TABLE keyword is required for the first entry in the EXCEPT clause +CREATE PUBLICATION testpub_except_nokw + FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + +-- Cleanup +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP TABLE pub_test.testpub_parted_s CASCADE; +DROP TABLE testpub_nopk, testpub_tbl_s1; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; + +--------------------------------------------- +-- Tests for publications with SEQUENCES +--------------------------------------------- CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; @@ -1189,6 +1256,18 @@ ALTER PUBLICATION testpub1_forschema SET TABLES IN SCHEMA pub_test1, pub_test1; ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo (a, b); ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b); +-- EXCEPT clause with CURRENT_SCHEMA: cross-schema entry must be rejected +SET search_path = pub_test1; +-- qualified name from wrong schema -> error +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.tbl1); +-- unqualified name implicitly qualified with current schema (pub_test1.tbl) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl); +RESET client_min_messages; +\dRp+ testpub_cursch_except +DROP PUBLICATION testpub_cursch_except; +RESET search_path; + -- cleanup pub_test1 schema for invalidation tests ALTER PUBLICATION testpub2_forschema DROP TABLES IN SCHEMA pub_test1; DROP PUBLICATION testpub3_forschema, testpub4_forschema, testpub5_forschema, testpub6_forschema, testpub_fortable; @@ -1443,6 +1522,7 @@ DROP ROLE regress_publication_user_dummy; -- Test pg_get_publication_tables(text[], oid) function CREATE SCHEMA gpt_test_sch; CREATE TABLE gpt_test_sch.tbl_sch (id int); +CREATE TABLE gpt_test_sch.tbl_sch2 (id int); CREATE TABLE tbl_normal (id int); CREATE TABLE tbl_parent (id1 int, id2 int, id3 int) PARTITION BY RANGE (id1); CREATE TABLE tbl_part1 PARTITION OF tbl_parent FOR VALUES FROM (1) TO (10); @@ -1454,6 +1534,7 @@ CREATE PUBLICATION pub_all_no_viaroot FOR ALL TABLES WITH (publish_via_partition CREATE PUBLICATION pub_all_except FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = true); CREATE PUBLICATION pub_all_except_no_viaroot FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_schema FOR TABLES IN SCHEMA gpt_test_sch; +CREATE PUBLICATION pub_schema_except FOR TABLES IN SCHEMA gpt_test_sch EXCEPT (TABLE gpt_test_sch.tbl_sch); CREATE PUBLICATION pub_normal FOR TABLE tbl_normal WHERE (id < 10); CREATE PUBLICATION pub_part_leaf FOR TABLE tbl_part1 WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_part_parent FOR TABLE tbl_parent (id1, id2) WHERE (id1 = 10) WITH (publish_via_partition_root = true); @@ -1510,6 +1591,10 @@ SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'gpt_test_sch.tbl_sch SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_parent'); -- no result (excluded) SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_part1'); -- no result +-- test for EXCEPT clause with schema publication +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch'); -- no result (excluded) +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch2'); -- one row (included via schema) + -- two rows with different row filter SELECT * FROM test_gpt(ARRAY['pub_all', 'pub_normal'], 'tbl_normal'); @@ -1538,6 +1623,7 @@ DROP PUBLICATION pub_all_no_viaroot; DROP PUBLICATION pub_all_except; DROP PUBLICATION pub_all_except_no_viaroot; DROP PUBLICATION pub_schema; +DROP PUBLICATION pub_schema_except; DROP PUBLICATION pub_normal; DROP PUBLICATION pub_part_leaf; DROP PUBLICATION pub_part_parent; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 8c58d282eee..18c7b2c1fca 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -24,14 +24,17 @@ my $result; sub test_except_root_partition { - my ($pubviaroot) = @_; + my ($pubviaroot, $pubsql) = @_; + $pubsql //= + "CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1)"; + $pubsql .= " WITH (publish_via_partition_root = $pubviaroot)"; # If the root partitioned table is in the EXCEPT clause, all its # partitions are excluded from publication, regardless of the # publish_via_partition_root setting. $node_publisher->safe_psql( 'postgres', qq( - CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1) WITH (publish_via_partition_root = $pubviaroot); + $pubsql; INSERT INTO root1 VALUES (1), (101); )); $node_subscriber->safe_psql('postgres', @@ -223,6 +226,131 @@ $node_subscriber->safe_psql( test_except_root_partition('false'); test_except_root_partition('true'); +# Same validation using TABLES IN SCHEMA instead of FOR ALL TABLES. +my $schema_pub = + "CREATE PUBLICATION tap_pub_part FOR TABLES IN SCHEMA public EXCEPT (TABLE public.root1)"; +test_except_root_partition('false', $schema_pub); +test_except_root_partition('true', $schema_pub); + +# ============================================ +# EXCEPT test cases for TABLES IN SCHEMA +# ============================================ + +# Create a dedicated schema with two tables: one to be published and one to be +# excluded. Also create inherited tables to verify ONLY semantics. +$node_publisher->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_published AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.tab_excluded AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.parent (a int); + CREATE TABLE sch1.child (b int) INHERITS (sch1.parent); +)); + +$node_subscriber->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_published (a int); + CREATE TABLE sch1.tab_excluded (a int); + CREATE TABLE sch1.parent (a int); + CREATE TABLE sch1.child (b int) INHERITS (sch1.parent); +)); + +# Basic test: initial sync respects EXCEPT. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_excluded)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: initial sync copies included table'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: initial sync skips excluded table'); + +# DML: only the included table should be replicated. +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (6); + INSERT INTO sch1.tab_excluded VALUES (6); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(6), + 'TABLES IN SCHEMA EXCEPT: DML on included table is replicated'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: DML on excluded table is not replicated'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Inherited tables: excluding the parent (without ONLY) also excludes the child. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.parent)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.child VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.child"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: excluding parent (without ONLY) also excludes child' +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Test that EXCEPT (TABLE ONLY parent) excludes only the parent itself, not its +# child. Truncate child first so rows from the previous test are not copied by +# the initial table sync of the next subscription. +$node_publisher->safe_psql('postgres', 'TRUNCATE sch1.child'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE sch1.child'); +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE ONLY sch1.parent)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.child VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.child"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: ONLY parent in EXCEPT does not exclude child'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Cleanup schema tables before the multi-publication section. +$node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); +$node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); + # ============================================ # Test when a subscription is subscribing to multiple publications # ============================================ @@ -254,6 +382,7 @@ $node_publisher->safe_psql( DROP PUBLICATION tap_pub2; TRUNCATE tab1; )); +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_subscriber->safe_psql('postgres', qq(TRUNCATE tab1)); # OK when a table is excluded by pub1 EXCEPT clause, but it is included by pub2 -- 2.50.1 (Apple Git-155)
v12-0002-Add-EXCEPT-support-to-ALTER-PUBLICATION-ADD-TABL.patch (application/octet-stream, 23.2K) download From 54dfb2a13e915e15c2da558019848530746864f0 Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Fri, 29 May 2026 20:04:57 +0530 Subject: [PATCH v12 2/3] Add EXCEPT support to ALTER PUBLICATION ADD TABLES IN SCHEMA Extend the EXCEPT clause support to allow tables to be excluded when adding a schema to a publication via ALTER PUBLICATION ... ADD. Syntax: ALTER PUBLICATION pub ADD TABLES IN SCHEMA s EXCEPT (TABLE s.t1); Since pg_dump uses ALTER PUBLICATION ... ADD, support for it is included in this patch. --- doc/src/sgml/ref/alter_publication.sgml | 52 ++++++++++- src/backend/catalog/pg_publication.c | 19 ++-- src/backend/commands/publicationcmds.c | 107 +++++++++++++++++++++- src/bin/pg_dump/pg_dump.c | 30 +++++- src/bin/pg_dump/t/002_pg_dump.pl | 24 +++++ src/bin/psql/tab-complete.in.c | 17 ++++ src/test/regress/expected/publication.out | 32 ++++++- src/test/regress/sql/publication.sql | 20 +++- src/test/subscription/t/037_except.pl | 32 +++++++ 9 files changed, 318 insertions(+), 15 deletions(-) diff --git a/doc/src/sgml/ref/alter_publication.sgml b/doc/src/sgml/ref/alter_publication.sgml index 52114a16a39..8d9d3573bd7 100644 --- a/doc/src/sgml/ref/alter_publication.sgml +++ b/doc/src/sgml/ref/alter_publication.sgml @@ -31,7 +31,7 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA <replaceable class="parameter">tables_in_schema</replaceable> [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -47,6 +47,10 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <replaceable class="parameter">table_object</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] [ WHERE ( <replaceable class="parameter">expression</replaceable> ) ] +<phrase>and <replaceable class="parameter">tables_in_schema</replaceable> is:</phrase> + + { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] + <phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> TABLE <replaceable class="parameter">table_object</replaceable> [, ... ] @@ -110,6 +114,14 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <literal>ADD TABLE</literal>. </para> + <para> + The <literal>EXCEPT</literal> clause can be used with + <literal>ADD TABLES IN SCHEMA</literal> to exclude specific tables from the + publication. Using <literal>DROP TABLES IN SCHEMA</literal> on a publication + will automatically also remove any associated <literal>EXCEPT</literal> + entries. + </para> + <para> The fourth variant of this command listed in the synopsis can change all of the publication properties specified in @@ -198,6 +210,34 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r </listitem> </varlistentry> + <varlistentry> + <term><literal>EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] )</literal></term> + <listitem> + <para> + When used with <literal>ADD TABLES IN SCHEMA</literal>, specifies + tables to be excluded from the publication. Each named + table must belong to the schema specified in the same + <literal>TABLES IN SCHEMA</literal> clause. Table names may be + schema-qualified or unqualified; unqualified names are implicitly + qualified with the schema named in the same clause. See + <xref linkend="sql-createpublication"/> for further details on the + semantics of <literal>EXCEPT</literal>. + </para> + <para> + For <literal>FOR TABLES IN SCHEMA</literal> publications, the + <literal>EXCEPT</literal> clause is schema-scoped. If a table listed in + the <literal>EXCEPT</literal> clause is later moved to a different schema + using <command>ALTER TABLE ... SET SCHEMA</command>, the exclusion is + removed; the table will then be published if its new schema is part of a + publication. If the table is subsequently moved back to the original + schema, the exclusion is not restored, and must be re-established + explicitly using <command>ALTER PUBLICATION</command>. Dropping a table + always removes it from the <literal>EXCEPT</literal> clause, regardless of + publication type. + </para> + </listitem> + </varlistentry> + <varlistentry> <term><literal>SET ( <replaceable class="parameter">publication_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] )</literal></term> <listitem> @@ -288,6 +328,16 @@ ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA marketing, sales; </programlisting> </para> + <para> + Add schema <structname>sales</structname> to the publication + <structname>sales_publication</structname>, excluding the + <structname>sales.internal</structname> and + <structname>sales.drafts</structname> tables: +<programlisting> +ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA sales EXCEPT (TABLE internal, drafts); +</programlisting> + </para> + <para> Add tables <structname>users</structname>, <structname>departments</structname> and schema diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index 4089b505f89..d1ff8839037 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -649,15 +649,18 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, * here, as CreatePublication() function invalidates all relations as part * of defining a FOR ALL TABLES publication. * - * For ALTER PUBLICATION, invalidation is needed only when adding an - * EXCEPT table to a publication already marked as ALL TABLES. For - * publications that were originally empty or defined as ALL SEQUENCES and - * are being converted to ALL TABLES, invalidation is skipped here, as - * AlterPublicationAllFlags() function invalidates all relations while - * marking the publication as ALL TABLES publication. + * For ALTER PUBLICATION, invalidation is needed when adding an EXCEPT + * table to either a FOR ALL TABLES publication (pub->alltables is true) + * or a FOR TABLES IN SCHEMA publication (is_schema_publication is true). + * The exception: when a publication is being converted to FOR ALL TABLES + * (pub->alltables is still false at this point), + * AlterPublicationAllFlags() will perform a full invalidation, so we skip + * it here. */ - inval_except_table = (alter_stmt != NULL) && pub->alltables && - (alter_stmt->for_all_tables && pri->except); + inval_except_table = (alter_stmt != NULL) && pri->except && + (pub->alltables + ? alter_stmt->for_all_tables + : is_schema_publication(pubid)); if (!pri->except || inval_except_table) { diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 49f6173be17..be4d578b7b4 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -70,6 +70,13 @@ static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok); static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); +static void AlterPublicationSchemas(AlterPublicationStmt *stmt, + HeapTuple tup, List *schemaidlist, + List *except_pubtables); +static void AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, + List *except_pubtables, + List *schemaidlist); static char defGetGeneratedColsOption(DefElem *def); @@ -1500,7 +1507,8 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, */ static void AlterPublicationSchemas(AlterPublicationStmt *stmt, - HeapTuple tup, List *schemaidlist) + HeapTuple tup, List *schemaidlist, + List *except_pubtables) { Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); @@ -1577,6 +1585,97 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, */ PublicationAddSchemas(pubform->oid, schemaidlist, true, stmt); } + + /* + * Increment the command counter so that is_schema_publication() in + * GetExcludedPublicationTables() can see the just-inserted schema + * rows when AlterPublicationSchemaExceptTables runs next. + */ + if (stmt->action == AP_AddObjects || stmt->action == AP_SetObjects) + CommandCounterIncrement(); + + AlterPublicationSchemaExceptTables(stmt, tup, except_pubtables, schemaidlist); +} + +/* + * Alter the EXCEPT list of a schema-level publication. + * + * Adds, removes, or replaces except-table entries in pg_publication_rel + * (rows with prexcept = true). These entries suppress publication of the + * named tables that would otherwise be covered by a FOR TABLES IN SCHEMA + * clause. + */ +static void +AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, List *except_pubtables, + List *schemaidlist) +{ + Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); + Oid pubid = pubform->oid; + + /* + * Nothing to do if no EXCEPT entries. + */ + if (!except_pubtables) + return; + + /* + * This function handles EXCEPT entries for schema-level publications + * only. For FOR ALL TABLES publications, EXCEPT entries are already + * processed by AlterPublicationTables(). + */ + if (schemaidlist == NIL && !is_schema_publication(pubid)) + return; + + /* + * Dropping a schema from a publication removes all its EXCEPT entries via + * cascade. The concept of "drop all schema tables from the publication + * EXCEPT these ones" is not supported. + */ + if (stmt->action == AP_DropObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); + + /* + * XXX EXCEPT with SET is not currently implemented. Workaround: DROP and + * re-ADD the schema with the desired EXCEPT list. + */ + if (stmt->action == AP_SetObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"), + errhint("Drop and re-add the schema with the desired EXCEPT list."))); + + if (stmt->action == AP_AddObjects) + { + List *rels; + List *explicitrelids; + + rels = OpenTableList(except_pubtables); + + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + /* + * Validate that each excluded table is not also in the explicit table + * list (which would be contradictory). + */ + foreach_ptr(PublicationRelInfo, pri, rels) + { + Oid relid = RelationGetRelid(pri->relation); + + if (list_member_oid(explicitrelids, relid)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" cannot appear in both the table list and the EXCEPT clause", + RelationGetQualifiedRelationName(pri->relation))); + } + + PublicationAddTables(pubid, rels, false, stmt); + + CloseTableList(rels); + } } /* @@ -1786,10 +1885,12 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) errmsg("publication \"%s\" does not exist", stmt->pubname)); - relations = list_concat(relations, except_pubtables); + if (stmt->for_all_tables) + relations = list_concat(relations, except_pubtables); + AlterPublicationTables(stmt, tup, relations, pstate->p_sourcetext, schemaidlist != NIL); - AlterPublicationSchemas(stmt, tup, schemaidlist); + AlterPublicationSchemas(stmt, tup, schemaidlist, except_pubtables); AlterPublicationAllFlags(stmt, rel, tup); } diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c index a0f7f8e2168..85ab3b00875 100644 --- a/src/bin/pg_dump/pg_dump.c +++ b/src/bin/pg_dump/pg_dump.c @@ -5019,6 +5019,7 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) PublicationInfo *pubinfo = pubsinfo->publication; PQExpBuffer query; char *tag; + bool has_except = false; /* Do nothing if not dumping schema */ if (!dopt->dumpSchema) @@ -5029,7 +5030,34 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) query = createPQExpBuffer(); appendPQExpBuffer(query, "ALTER PUBLICATION %s ", fmtId(pubinfo->dobj.name)); - appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s;\n", fmtId(schemainfo->dobj.name)); + appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s", fmtId(schemainfo->dobj.name)); + + /* + * Append EXCEPT clause for any tables that belong to this schema + * and are excluded from the publication. + */ + for (SimplePtrListCell *cell = pubinfo->except_tables.head; cell; cell = cell->next) + { + TableInfo *tbinfo = (TableInfo *) cell->ptr; + + if (strcmp(tbinfo->dobj.namespace->dobj.name, schemainfo->dobj.name) == 0) + { + if (!has_except) + { + appendPQExpBufferStr(query, " EXCEPT ("); + has_except = true; + } + else + appendPQExpBufferStr(query, ", "); + + appendPQExpBuffer(query, "TABLE ONLY %s", fmtId(tbinfo->dobj.name)); + } + } + + if (has_except) + appendPQExpBufferStr(query, ")"); + + appendPQExpBufferStr(query, ";\n"); /* * There is no point in creating drop query as the drop is done by schema diff --git a/src/bin/pg_dump/t/002_pg_dump.pl b/src/bin/pg_dump/t/002_pg_dump.pl index 3ee9fda50e4..b8f4aa769ec 100644 --- a/src/bin/pg_dump/t/002_pg_dump.pl +++ b/src/bin/pg_dump/t/002_pg_dump.pl @@ -3242,6 +3242,30 @@ my %tests = ( like => { %full_runs, section_post_data => 1, }, }, + 'CREATE PUBLICATION pub11' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub11 FOR TABLES IN SCHEMA dump_test EXCEPT (TABLE test_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub11 WITH (publish = 'insert, update, delete, truncate');\E + .*? + \QALTER PUBLICATION pub11 ADD TABLES IN SCHEMA dump_test EXCEPT (TABLE ONLY test_table);\E + /xms, + like => { %full_runs, section_post_data => 1, }, + }, + + 'CREATE PUBLICATION pub12' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub12 FOR TABLES IN SCHEMA dump_test EXCEPT (TABLE test_table, dump_test.test_second_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub12 WITH (publish = 'insert, update, delete, truncate');\E + .*? + \QALTER PUBLICATION pub12 ADD TABLES IN SCHEMA dump_test EXCEPT (TABLE ONLY test_table, TABLE ONLY test_second_table);\E + /xms, + like => { %full_runs, section_post_data => 1, }, + }, + 'CREATE SUBSCRIPTION sub1' => { create_order => 50, create_sql => 'CREATE SUBSCRIPTION sub1 diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index 53bb7c8679b..a290902d61e 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2373,6 +2373,23 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); + /* After a single schema name in ADD context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index ba01c720d4e..3c452139bf9 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -564,12 +564,42 @@ CREATE PUBLICATION testpub_except_nokw ERROR: syntax error at or near "testpub_nopk" LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); ^ +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; +-- fail: non-existing table in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- fail: EXCEPT table belongs to a different schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 1: ...xcept ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.tes... + ^ +-- fail: TABLE keyword is required for the first entry in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +ERROR: syntax error at or near "testpub_nopk" +LINE 1: ...lter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_no... + ^ +-- ADD: qualified and unqualified names; unqualified is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + "pub_test.testpub_tbl_s2" + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP TABLE pub_test.testpub_parted_s CASCADE; DROP TABLE testpub_nopk, testpub_tbl_s1; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi, testpub_alter_except; --------------------------------------------- -- Tests for publications with SEQUENCES --------------------------------------------- diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 4bc0e2ff23d..240190aa41f 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -278,12 +278,30 @@ CREATE PUBLICATION testpub_except_partition CREATE PUBLICATION testpub_except_nokw FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; + +-- fail: non-existing table in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- fail: EXCEPT table belongs to a different schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- fail: TABLE keyword is required for the first entry in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + +-- ADD: qualified and unqualified names; unqualified is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); +\dRp+ testpub_alter_except + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP TABLE pub_test.testpub_parted_s CASCADE; DROP TABLE testpub_nopk, testpub_tbl_s1; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi, testpub_alter_except; --------------------------------------------- -- Tests for publications with SEQUENCES diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 18c7b2c1fca..0ba6d6f8bb2 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -347,6 +347,38 @@ is($result, qq(5), $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); +# ============================================ +# ALTER PUBLICATION EXCEPT for TABLES IN SCHEMA +# ============================================ + +# Truncate subscriber tables to remove data accumulated from previous tests. +$node_subscriber->safe_psql('postgres', + 'TRUNCATE sch1.tab_published, sch1.tab_excluded, sch1.parent, sch1.child'); + +# ADD: add a schema with an excepted table; verify the except entry takes effect. +$node_publisher->safe_psql('postgres', "CREATE PUBLICATION sch_pub"); +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub ADD TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_excluded)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(6), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: included table synced'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + # Cleanup schema tables before the multi-publication section. $node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); $node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); -- 2.50.1 (Apple Git-155)
v12-0003-Add-EXCEPT-support-to-ALTER-PUBLICATION-SET-TABL.patch (application/octet-stream, 26.1K) download From 989aa017d4074e4af2ca0f68ab75289a1f3fad66 Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Tue, 2 Jun 2026 11:39:36 +0530 Subject: [PATCH v12 3/3] Add EXCEPT support to ALTER PUBLICATION SET TABLES IN SCHEMA Extend AlterPublicationExceptTables() with the AP_SetObjects case, which redefines the publication and replaces the entire EXCEPT list. Syntax: ALTER PUBLICATION pub SET TABLES IN SCHEMA s EXCEPT (TABLE t1); This patch also cleans up EXCEPT entries when a schema is dropped from the publication. --- doc/src/sgml/ref/alter_publication.sgml | 27 +++- src/backend/commands/publicationcmds.c | 135 +++++++++++++++++--- src/backend/replication/pgoutput/pgoutput.c | 10 +- src/bin/psql/tab-complete.in.c | 17 +++ src/test/regress/expected/publication.out | 86 +++++++++++++ src/test/regress/sql/publication.sql | 38 ++++++ src/test/subscription/t/037_except.pl | 85 ++++++++++++ 7 files changed, 371 insertions(+), 27 deletions(-) diff --git a/doc/src/sgml/ref/alter_publication.sgml b/doc/src/sgml/ref/alter_publication.sgml index 8d9d3573bd7..4be085ef1b2 100644 --- a/doc/src/sgml/ref/alter_publication.sgml +++ b/doc/src/sgml/ref/alter_publication.sgml @@ -97,7 +97,11 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r used with a publication defined with <literal>FOR TABLE</literal> or <literal>FOR TABLES IN SCHEMA</literal>, replaces the list of tables/schemas in the publication with the specified list; the existing tables or schemas - that were present in the publication will be removed. + that were present in the publication will be removed. When + <literal>SET TABLES IN SCHEMA</literal> is used with an + <literal>EXCEPT</literal> clause, the excluded tables for each schema are + replaced with the specified list; if <literal>EXCEPT</literal> is omitted + for a schema, any existing exclusions for that schema are cleared. </para> <para> @@ -116,10 +120,8 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <para> The <literal>EXCEPT</literal> clause can be used with - <literal>ADD TABLES IN SCHEMA</literal> to exclude specific tables from the - publication. Using <literal>DROP TABLES IN SCHEMA</literal> on a publication - will automatically also remove any associated <literal>EXCEPT</literal> - entries. + <literal>ADD TABLES IN SCHEMA</literal> to exclude specific tables from a + schema-level publication. </para> <para> @@ -214,7 +216,8 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <term><literal>EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] )</literal></term> <listitem> <para> - When used with <literal>ADD TABLES IN SCHEMA</literal>, specifies + When used with <literal>ADD TABLES IN SCHEMA</literal> + or <literal>SET TABLES IN SCHEMA</literal>, specifies tables to be excluded from the publication. Each named table must belong to the schema specified in the same <literal>TABLES IN SCHEMA</literal> clause. Table names may be @@ -338,6 +341,18 @@ ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA sales EXCEPT (TABLE int </programlisting> </para> + <para> + Replace the schema list of <structname>sales_publication</structname> with + <structname>sales</structname>, excluding only + <structname>sales.drafts</structname>. Other than + <structname>sales.drafts</structname>, any previously excluded tables for schema + <structname>sales</structname> are no longer excluded. Any schemas previously in + <structname>sales_publication</structname> are removed: +<programlisting> +ALTER PUBLICATION sales_publication SET TABLES IN SCHEMA sales EXCEPT (TABLE drafts); +</programlisting> + </para> + <para> Add tables <structname>users</structname>, <structname>departments</structname> and schema diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index be4d578b7b4..ba217418a3a 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -1588,8 +1588,8 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, /* * Increment the command counter so that is_schema_publication() in - * GetExcludedPublicationTables() can see the just-inserted schema - * rows when AlterPublicationSchemaExceptTables runs next. + * GetExcludedPublicationTables() can see the just-inserted schema rows + * when AlterPublicationSchemaExceptTables runs next. */ if (stmt->action == AP_AddObjects || stmt->action == AP_SetObjects) CommandCounterIncrement(); @@ -1607,16 +1607,18 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, */ static void AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, - HeapTuple tup, List *except_pubtables, - List *schemaidlist) + HeapTuple tup, List *except_pubtables, + List *schemaidlist) { Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); Oid pubid = pubform->oid; /* - * Nothing to do if no EXCEPT entries. + * Nothing to do if there are no EXCEPT entries, unless handling the SET + * command, because if the user has removed all exceptions we need to drop + * any existing ones. */ - if (!except_pubtables) + if (!except_pubtables && stmt->action != AP_SetObjects) return; /* @@ -1637,16 +1639,6 @@ AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); - /* - * XXX EXCEPT with SET is not currently implemented. Workaround: DROP and - * re-ADD the schema with the desired EXCEPT list. - */ - if (stmt->action == AP_SetObjects) - ereport(ERROR, - (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"), - errhint("Drop and re-add the schema with the desired EXCEPT list."))); - if (stmt->action == AP_AddObjects) { List *rels; @@ -1674,6 +1666,84 @@ AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, PublicationAddTables(pubid, rels, false, stmt); + CloseTableList(rels); + } + else /* AP_SetObjects */ + { + List *oldexceptrelids = NIL; + List *newexceptrelids = NIL; + List *delrelids = NIL; + List *rels; + List *explicitrelids; + + rels = OpenTableList(except_pubtables); + + /* Collect OIDs of the desired new EXCEPT list. */ + foreach_ptr(PublicationRelInfo, pri, rels) + newexceptrelids = lappend_oid(newexceptrelids, + RelationGetRelid(pri->relation)); + + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + /* + * Validate that each excluded table is not also in the explicit table + * list (which would be contradictory). + */ + foreach_ptr(PublicationRelInfo, pri, rels) + { + Oid relid = RelationGetRelid(pri->relation); + + if (list_member_oid(explicitrelids, relid)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" cannot appear in both the table list and the EXCEPT clause", + RelationGetQualifiedRelationName(pri->relation))); + } + + /* + * Get the current set of EXCEPT entries. Only FOR ALL TABLES and + * schema-level publications can have EXCEPT entries; for any other + * publication type oldexceptrelids stays NIL. + * + * Note: we check is_schema_publication() against the current catalog + * state (before AlterPublicationSchemas has run), so if the caller is + * doing SET TABLE t1 to convert a schema publication into a plain + * table publication, is_schema_publication() still returns true here. + * That is intentional: it lets us discover and clean up any stale + * EXCEPT entries that belong to the old schema definition. + */ + if (GetPublication(pubid)->alltables || is_schema_publication(pubid)) + oldexceptrelids = GetExcludedPublicationTables(pubid, + PUBLICATION_PART_ROOT); + + /* Build a list of old EXCEPT entries not present in the new list. */ + foreach_oid(oldrelid, oldexceptrelids) + { + if (!list_member_oid(newexceptrelids, oldrelid)) + delrelids = lappend_oid(delrelids, oldrelid); + } + + /* Drop old EXCEPT entries not present in the new list. */ + foreach_oid(relid, delrelids) + { + Oid proid; + ObjectAddress obj; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + /* Add new EXCEPT entries, skipping any already present. */ + PublicationAddTables(pubid, rels, true, stmt); + CloseTableList(rels); } } @@ -2363,6 +2433,7 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) foreach(lc, schemas) { Oid schemaid = lfirst_oid(lc); + List *except_relids; psid = GetSysCacheOid2(PUBLICATIONNAMESPACEMAP, Anum_pg_publication_namespace_oid, @@ -2379,8 +2450,40 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) get_namespace_name(schemaid)))); } + /* + * Collect EXCEPT entries for tables belonging to this schema before + * removing the schema entry. + */ + except_relids = GetExcludedPublicationTables(pubid, PUBLICATION_PART_ROOT); + ObjectAddressSet(obj, PublicationNamespaceRelationId, psid); performDeletion(&obj, DROP_CASCADE, 0); + + /* + * Drop any prexcept rows for tables belonging to this schema. These + * rows have no pg_depend entry pointing at the + * pg_publication_namespace row, so they are not cascaded by the + * performDeletion() call above and must be cleaned up explicitly. + */ + foreach_oid(relid, except_relids) + { + Oid proid; + + if (get_rel_namespace(relid) != schemaid) + continue; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + list_free(except_relids); } } diff --git a/src/backend/replication/pgoutput/pgoutput.c b/src/backend/replication/pgoutput/pgoutput.c index 7ee84ec1c83..9831be54b47 100644 --- a/src/backend/replication/pgoutput/pgoutput.c +++ b/src/backend/replication/pgoutput/pgoutput.c @@ -2229,7 +2229,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) */ if (pub->alltables) { - List *exceptpubids = NIL; + List *except_pubids = NIL; if (am_partition) { @@ -2252,7 +2252,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) * clause. Therefore, for a partition, exclusion must be * evaluated at the top-most ancestor. */ - exceptpubids = GetRelationExcludedPublications(last_ancestor_relid); + except_pubids = GetRelationExcludedPublications(last_ancestor_relid); } else { @@ -2260,13 +2260,13 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) * For a regular table or a root partitioned table, check * exclusion on table itself. */ - exceptpubids = GetRelationExcludedPublications(pub_relid); + except_pubids = GetRelationExcludedPublications(pub_relid); } - if (!list_member_oid(exceptpubids, pub->oid)) + if (!list_member_oid(except_pubids, pub->oid)) publish = true; - list_free(exceptpubids); + list_free(except_pubids); if (!publish) continue; diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index a290902d61e..e8bfb36cb1c 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2390,6 +2390,23 @@ match_previous_words(int pattern_id, } else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) COMPLETE_WITH(")"); + /* After a single schema name in SET context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 3c452139bf9..f7f394a35bf 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -594,6 +594,92 @@ Except tables: "pub_test.testpub_tbl_s1" "pub_test.testpub_tbl_s2" +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s2" + +-- fail: table in EXCEPT clause also appears in the explicit table list +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot appear in both the table list and the EXCEPT clause +-- error: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 1: ...xcept SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.tes... + ^ +-- SET: unqualified name in EXCEPT is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- SET without EXCEPT clears the existing except list +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + +-- SET to a different schema removes old schema's EXCEPT entries +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA public; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "public" + +-- fail: nonexistent table in EXCEPT clause (SET path) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- SET: multiple schemas each with their own EXCEPT clause +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- error: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +ERROR: EXCEPT clause is not supported with DROP in ALTER PUBLICATION +-- DROP TABLES IN SCHEMA removes associated EXCEPT entries +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "public" +Except tables: + "public.testpub_tbl1" + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 240190aa41f..3674437ed50 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -296,6 +296,44 @@ ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (tes ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); \dRp+ testpub_alter_except +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + +-- fail: table in EXCEPT clause also appears in the explicit table list +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- error: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- SET: unqualified name in EXCEPT is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +\dRp+ testpub_alter_except + +-- SET without EXCEPT clears the existing except list +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + +-- SET to a different schema removes old schema's EXCEPT entries +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA public; +\dRp+ testpub_alter_except + +-- fail: nonexistent table in EXCEPT clause (SET path) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- SET: multiple schemas each with their own EXCEPT clause +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_alter_except + +-- error: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); + +-- DROP TABLES IN SCHEMA removes associated EXCEPT entries +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 0ba6d6f8bb2..01eafb5b7c8 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -376,6 +376,61 @@ $result = is($result, qq(0), 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); +# SET: replace the except list; tab_excluded is now included and tab_published is excluded. +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_published)" +); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (7); + INSERT INTO sch1.tab_excluded VALUES (7); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded WHERE a = 7"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: newly included table is replicated' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published WHERE a = 7"); +is($result, qq(0), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: now-excluded table is not replicated' +); + +# SET without EXCEPT: clears the except list; both tables are now published. +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1"); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (8); + INSERT INTO sch1.tab_excluded VALUES (8); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published WHERE a = 8"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_published replicated after except list cleared' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded WHERE a = 8"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_excluded replicated after except list cleared' +); + $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); @@ -443,6 +498,36 @@ $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); +# OK when a table is excluded by a TABLES IN SCHEMA EXCEPT publication, +# but is included by another publication. +$node_publisher->safe_psql('postgres', 'TRUNCATE tab1'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE tab1'); + +$node_publisher->safe_psql( + 'postgres', qq( + CREATE PUBLICATION tap_pub1 FOR TABLES IN SCHEMA public EXCEPT (TABLE public.tab1); + CREATE PUBLICATION tap_pub2 FOR TABLE tab1; + INSERT INTO tab1 VALUES(1); +)); +$node_subscriber->psql('postgres', + "CREATE SUBSCRIPTION tap_sub CONNECTION '$publisher_connstr' PUBLICATION tap_pub1, tap_pub2" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'tap_sub'); + +$node_publisher->safe_psql('postgres', qq(INSERT INTO tab1 VALUES(2))); +$node_publisher->wait_for_catchup('tap_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT * FROM tab1 ORDER BY a"); +is( $result, qq(1 +2), + "TABLES IN SCHEMA EXCEPT: table excluded in schema pub but included by another pub is replicated" +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); + $node_publisher->stop('fast'); done_testing(); -- 2.50.1 (Apple Git-155)
^ permalink raw reply [nested|flat] 196+ messages in thread

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-06-10 20:54  Zsolt Parragi <zsolt.parragi@percona.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: Zsolt Parragi @ 2026-06-10 20:54 UTC (permalink / raw)
  To: pgsql-hackers@lists.postgresql.org

> Let's wait for feedback from others.

Yes, I think that's the best approach for this question.

> Right, As also mentioned above, ALTER TABLE changes that affect
> publication membership currently do not emit any notice or warning, so
> I'm not sure we need one here either.

My idea was to make this change both for existing cases and new cases
in this patch, so it would be consistent, but that wasn't exactly
clear in my previous email, sorry about that. Similarly to how cascade
reports additional objects being dropped.





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-06-11 06:47  Peter Smith <smithpb2250@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: Peter Smith @ 2026-06-11 06:47 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

Hi Nisha.

Some review comments for the v12 patches.

//////
v12-0001

======
doc/src/sgml/ref/create_publication.sgml

1.
      <para>
       This clause specifies a list of tables to be excluded from the
-      publication.
+      publication. It can be used with <literal>FOR ALL TABLES</literal> or
+      <literal>FOR TABLES IN SCHEMA</literal>.
+     </para>
+     <para>
+      For <literal>FOR TABLES IN SCHEMA</literal> publications, the
+      <literal>EXCEPT</literal> clause is schema-scoped: the exclusion applies
+      only within the schema to which it was attached.  For
+      <literal>FOR ALL TABLES</literal> publications, the exclusion applies to
+      the table regardless of the schema it is in.
      </para>

For that 2nd para, I think it ought to avoid words like "attached"
when talking about tables because attaching has a special meaning.

Also, I don't really understand what the 2nd sentence is trying to
say. FOR ALL TABLES exclusions will exclude the *named* tables. Yes,
those named tables might be in any schema (by fully-qualifying the
name), but that's not the same as saying "regardless of the schema".

So, IMO we can throw away that 2nd sentence, and just keep the
simplified 1st one. Since what remains is now very short, probably
just combine both paragraphs.

SUGGESTION
This clause specifies a list of tables to be excluded from the
publication. It can be used with <literal>FOR ALL TABLES</literal> or
<literal>FOR TABLES IN SCHEMA</literal>. For <literal>FOR TABLES IN
SCHEMA</literal>, the exclusion applies only to tables in the schema
associated with the <literal>EXCEPT</literal>.

======
src/backend/commands/publicationcmds.c

RemovePublicationExceptForRelation:

2.
+ if (OidIsValid(proid))
+ {
+ ObjectAddressSet(obj, PublicationRelRelationId, proid);
+ performDeletion(&obj, DROP_CASCADE, 0);
+ }

Variable `obj` can be declared right here; it's the only place using it.

//////////
v12-0002

======
doc/src/sgml/ref/alter_publication.sgml

1.
+     <para>
+      For <literal>FOR TABLES IN SCHEMA</literal> publications, the
+      <literal>EXCEPT</literal> clause is schema-scoped.  If a table listed in
+      the <literal>EXCEPT</literal> clause is later moved to a different schema
+      using <command>ALTER TABLE ... SET SCHEMA</command>, the exclusion is
+      removed; the table will then be published if its new schema is part of a
+      publication.  If the table is subsequently moved back to the original
+      schema, the exclusion is not restored, and must be re-established
+      explicitly using <command>ALTER PUBLICATION</command>.  Dropping a table
+      always removes it from the <literal>EXCEPT</literal> clause,
regardless of
+      publication type.
+     </para>


I think the sentence "If the table is subsequently moved back..." is
overkill, and does not need to be said. The prior info "the exclusion
is removed" already tells me the exclusion is gone, and I think is
reasonable to assume "removed" means that it is gone for good, with no
ambiguity that it might magically come back.

YMMV. Leave it as-is if you prefer.

//////////
v12-0003

No comments.

======
Kind Regards,
Peter Smith.
Fujitsu Australia





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-06-15 06:08  Amit Kapila <amit.kapila16@gmail.com>
  parent: Zsolt Parragi <zsolt.parragi@percona.com>
  0 siblings, 1 reply; 196+ messages in thread

From: Amit Kapila @ 2026-06-15 06:08 UTC (permalink / raw)
  To: Zsolt Parragi <zsolt.parragi@percona.com>; +Cc: pgsql-hackers@lists.postgresql.org

On Thu, Jun 11, 2026 at 2:24 AM Zsolt Parragi <zsolt.parragi@percona.com> wrote:
>
> > Let's wait for feedback from others.
>
> Yes, I think that's the best approach for this question.
>
> > Right, As also mentioned above, ALTER TABLE changes that affect
> > publication membership currently do not emit any notice or warning, so
> > I'm not sure we need one here either.
>
> My idea was to make this change both for existing cases and new cases
> in this patch, so it would be consistent, but that wasn't exactly
> clear in my previous email, sorry about that. Similarly to how cascade
> reports additional objects being dropped.
>

IIUC, the objects here we are talking about are removed because of
their dependency type AUTO at least the existing case of 'drop table'.
So, I think the current behavior suggested by Nisha sounds correct and
consistent with the pre-existing 'drop table' case. Also, we display
such case at DEBUG2 level, see following code in dependency.c:

if (extra->flags & (DEPFLAG_AUTO |
DEPFLAG_INTERNAL |
DEPFLAG_PARTITION |
DEPFLAG_EXTENSION))
{
/*
* auto-cascades are reported at DEBUG2, not msglevel.  We don't
* try to combine them with the regular message because the
* results are too confusing when client_min_messages and
* log_min_messages are different.
*/
ereport(DEBUG2,
(errmsg_internal("drop auto-cascades to %s",

We can consider displaying such a message for schema cases, if not
already there.

-- 
With Regards,
Amit Kapila.





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-06-15 06:19  Amit Kapila <amit.kapila16@gmail.com>
  parent: Peter Smith <smithpb2250@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: Amit Kapila @ 2026-06-15 06:19 UTC (permalink / raw)
  To: Peter Smith <smithpb2250@gmail.com>; +Cc: Nisha Moond <nisha.moond412@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Thu, Jun 11, 2026 at 12:17 PM Peter Smith <smithpb2250@gmail.com> wrote:
>
> //////////
> v12-0002
>
> ======
> doc/src/sgml/ref/alter_publication.sgml
>
> 1.
> +     <para>
> +      For <literal>FOR TABLES IN SCHEMA</literal> publications, the
> +      <literal>EXCEPT</literal> clause is schema-scoped.  If a table listed in
> +      the <literal>EXCEPT</literal> clause is later moved to a different schema
> +      using <command>ALTER TABLE ... SET SCHEMA</command>, the exclusion is
> +      removed; the table will then be published if its new schema is part of a
> +      publication.  If the table is subsequently moved back to the original
> +      schema, the exclusion is not restored, and must be re-established
> +      explicitly using <command>ALTER PUBLICATION</command>.  Dropping a table
> +      always removes it from the <literal>EXCEPT</literal> clause,
> regardless of
> +      publication type.
> +     </para>
>
>
> I think the sentence "If the table is subsequently moved back..." is
> overkill, and does not need to be said. The prior info "the exclusion
> is removed" already tells me the exclusion is gone, and I think is
> reasonable to assume "removed" means that it is gone for good, with no
> ambiguity that it might magically come back.
>
> YMMV. Leave it as-is if you prefer.
>

I feel it is okay to keep the proposed sentence to avoid any ambiguity
by the user to consider the schema-scope state is symmetric.

-- 
With Regards,
Amit Kapila.





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-06-15 11:30  Nisha Moond <nisha.moond412@gmail.com>
  parent: Amit Kapila <amit.kapila16@gmail.com>
  0 siblings, 0 replies; 196+ messages in thread

From: Nisha Moond @ 2026-06-15 11:30 UTC (permalink / raw)
  To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Mon, Jun 15, 2026 at 11:38 AM Amit Kapila <amit.kapila16@gmail.com> wrote:
>
> On Thu, Jun 11, 2026 at 2:24 AM Zsolt Parragi <zsolt.parragi@percona.com> wrote:
> >
> > > Let's wait for feedback from others.
> >
> > Yes, I think that's the best approach for this question.
> >
> > > Right, As also mentioned above, ALTER TABLE changes that affect
> > > publication membership currently do not emit any notice or warning, so
> > > I'm not sure we need one here either.
> >
> > My idea was to make this change both for existing cases and new cases
> > in this patch, so it would be consistent, but that wasn't exactly
> > clear in my previous email, sorry about that. Similarly to how cascade
> > reports additional objects being dropped.
> >
>
> IIUC, the objects here we are talking about are removed because of
> their dependency type AUTO at least the existing case of 'drop table'.
> So, I think the current behavior suggested by Nisha sounds correct and
> consistent with the pre-existing 'drop table' case. Also, we display
> such case at DEBUG2 level, see following code in dependency.c:
>
> if (extra->flags & (DEPFLAG_AUTO |
> DEPFLAG_INTERNAL |
> DEPFLAG_PARTITION |
> DEPFLAG_EXTENSION))
> {
> /*
> * auto-cascades are reported at DEBUG2, not msglevel.  We don't
> * try to combine them with the regular message because the
> * results are too confusing when client_min_messages and
> * log_min_messages are different.
> */
> ereport(DEBUG2,
> (errmsg_internal("drop auto-cascades to %s",
>
> We can consider displaying such a message for schema cases, if not
> already there.
>

The DROP TABLE case is handled automatically via dependency cascade,
so we already get above DEBUG2 log. However, when a table is moved to
a different schema, no such log is emitted because schema changes are
outside the scope of dependency cascade processing.

In v13, I added a DEBUG2 message when a table is removed from the
exclusion list due to a schema change.

--
Thanks,
Nisha





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-06-15 11:30  Nisha Moond <nisha.moond412@gmail.com>
  parent: Amit Kapila <amit.kapila16@gmail.com>
  0 siblings, 3 replies; 196+ messages in thread

From: Nisha Moond @ 2026-06-15 11:30 UTC (permalink / raw)
  To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Mon, Jun 15, 2026 at 11:50 AM Amit Kapila <amit.kapila16@gmail.com> wrote:
>
> On Thu, Jun 11, 2026 at 12:17 PM Peter Smith <smithpb2250@gmail.com> wrote:
> >
> > //////////
> > v12-0002
> >
> > ======
> > doc/src/sgml/ref/alter_publication.sgml
> >
> > 1.
> > +     <para>
> > +      For <literal>FOR TABLES IN SCHEMA</literal> publications, the
> > +      <literal>EXCEPT</literal> clause is schema-scoped.  If a table listed in
> > +      the <literal>EXCEPT</literal> clause is later moved to a different schema
> > +      using <command>ALTER TABLE ... SET SCHEMA</command>, the exclusion is
> > +      removed; the table will then be published if its new schema is part of a
> > +      publication.  If the table is subsequently moved back to the original
> > +      schema, the exclusion is not restored, and must be re-established
> > +      explicitly using <command>ALTER PUBLICATION</command>.  Dropping a table
> > +      always removes it from the <literal>EXCEPT</literal> clause,
> > regardless of
> > +      publication type.
> > +     </para>
> >
> >
> > I think the sentence "If the table is subsequently moved back..." is
> > overkill, and does not need to be said. The prior info "the exclusion
> > is removed" already tells me the exclusion is gone, and I think is
> > reasonable to assume "removed" means that it is gone for good, with no
> > ambiguity that it might magically come back.
> >
> > YMMV. Leave it as-is if you prefer.
> >
>
> I feel it is okay to keep the proposed sentence to avoid any ambiguity
> by the user to consider the schema-scope state is symmetric.
>

Okay, I have kept this para as-it-is.

The other comments on v12-0001 from [1] have also been addressed.

Please find the updated v13 patches attached.

[1] https://www.postgresql.org/message-id/CAHut%2BPv-GA1oGa6%2Bnwn_5AVhBg8NuJThQVUzqhQPXJge49jnew%40mail...

--
Thanks,
Nisha

Attachments: download all (3 files, .tar.gz)

v13-0001-Support-EXCEPT-clause-for-schema-level-publicati.patch (application/octet-stream, 62.7K) download From be49f257aa5e91582d548c35815be6d512bc403e Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Mon, 15 Jun 2026 16:44:47 +0530 Subject: [PATCH v13 1/3] Support EXCEPT clause for schema-level publications Extend table exclusion support in publications to allow specific tables to be excluded from schema-level publications using an EXCEPT clause in CREATE PUBLICATION. Supported syntax: CREATE PUBLICATION <pub> FOR TABLES IN SCHEMA s EXCEPT (TABLE t1,...); --- doc/src/sgml/logical-replication.sgml | 3 +- doc/src/sgml/ref/create_publication.sgml | 24 ++- src/backend/catalog/pg_publication.c | 161 ++++++++++++++++---- src/backend/commands/publicationcmds.c | 146 ++++++++++++++++-- src/backend/commands/tablecmds.c | 11 ++ src/backend/parser/gram.y | 54 ++++++- src/backend/replication/pgoutput/pgoutput.c | 30 +++- src/bin/psql/describe.c | 18 +++ src/bin/psql/tab-complete.in.c | 35 ++++- src/include/catalog/pg_publication.h | 3 +- src/include/commands/publicationcmds.h | 2 + src/include/nodes/parsenodes.h | 2 + src/test/regress/expected/publication.out | 144 ++++++++++++++++- src/test/regress/sql/publication.sql | 88 ++++++++++- src/test/subscription/t/037_except.pl | 133 +++++++++++++++- 15 files changed, 797 insertions(+), 57 deletions(-) diff --git a/doc/src/sgml/logical-replication.sgml b/doc/src/sgml/logical-replication.sgml index 9e7868487de..1433d2660fe 100644 --- a/doc/src/sgml/logical-replication.sgml +++ b/doc/src/sgml/logical-replication.sgml @@ -117,7 +117,8 @@ or <literal>FOR ALL SEQUENCES</literal>. Unlike tables, sequences can be synchronized at any time. For more information, see <xref linkend="logical-replication-sequences"/>. When a publication is - created with <literal>FOR ALL TABLES</literal>, a table or set of tables can + created with <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal>, a table or set of tables can be explicitly excluded from publication using the <link linkend="sql-createpublication-params-for-except-table"><literal>EXCEPT</literal></link> clause. diff --git a/doc/src/sgml/ref/create_publication.sgml b/doc/src/sgml/ref/create_publication.sgml index f82d640e6ca..1017396f476 100644 --- a/doc/src/sgml/ref/create_publication.sgml +++ b/doc/src/sgml/ref/create_publication.sgml @@ -28,7 +28,7 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA <replaceable class="parameter">tables_in_schema</replaceable> [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -39,6 +39,10 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <replaceable class="parameter">table_object</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] [ WHERE ( <replaceable class="parameter">expression</replaceable> ) ] +<phrase>and <replaceable class="parameter">tables_in_schema</replaceable> is:</phrase> + + { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] + <phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> TABLE <replaceable class="parameter">table_object</replaceable> [, ... ] @@ -142,6 +146,8 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <para> Marks the publication as one that replicates changes for all tables in the specified list of schemas, including tables created in the future. + Tables listed in the <literal>EXCEPT</literal> clause for a given schema + are excluded from the publication. </para> <para> @@ -173,7 +179,7 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <para> Marks the publication as one that replicates changes for all tables in the database, including tables created in the future. Tables listed in - <literal>EXCEPT</literal> clause are excluded from the publication. + the <literal>EXCEPT</literal> clause are excluded from the publication. </para> </listitem> </varlistentry> @@ -198,7 +204,10 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <listitem> <para> This clause specifies a list of tables to be excluded from the - publication. + publication. It can be used with <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal>. For <literal>FOR TABLES IN + SCHEMA</literal>, the exclusion applies only to tables in the schema + associated with the <literal>EXCEPT</literal>. </para> <para> For inherited tables, if <literal>ONLY</literal> is specified before the @@ -515,6 +524,15 @@ CREATE PUBLICATION production_publication FOR TABLE users, departments, TABLES I CREATE PUBLICATION sales_publication FOR TABLES IN SCHEMA marketing, sales; </programlisting></para> + <para> + Create a publication that publishes all changes for all the tables present in + the schema <structname>sales</structname>, except + <structname>internal</structname> and <structname>drafts</structname>: +<programlisting> +CREATE PUBLICATION sales_filtered FOR TABLES IN SCHEMA sales EXCEPT (TABLE internal, drafts); +</programlisting> + </para> + <para> Create a publication that publishes all changes for table <structname>users</structname>, but replicates only columns <structname>user_id</structname> and diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index 5c457d9aca8..4089b505f89 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -444,13 +444,19 @@ GetPubPartitionOptionRelations(List *result, PublicationPartOpt pub_partopt, * * Note that the list of ancestors should be ordered such that the topmost * ancestor is at the end of the list. + * + * except_pubids is a list of publication OIDs whose schema membership + * should be ignored for the ancestor (because the ancestor is in their + * EXCEPT clause). */ Oid -GetTopMostAncestorInPublication(Oid puboid, List *ancestors, int *ancestor_level) +GetTopMostAncestorInPublication(Oid puboid, List *ancestors, + int *ancestor_level, List *except_pubids) { ListCell *lc; Oid topmost_relid = InvalidOid; int level = 0; + bool check_schemas = !list_member_oid(except_pubids, puboid); /* * Find the "topmost" ancestor that is in this publication. @@ -470,7 +476,7 @@ GetTopMostAncestorInPublication(Oid puboid, List *ancestors, int *ancestor_level if (ancestor_level) *ancestor_level = level; } - else + else if (check_schemas) { aschemaPubids = GetSchemaPublications(get_rel_namespace(ancestor)); if (list_member_oid(aschemaPubids, puboid)) @@ -545,18 +551,30 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, * duplicates, it's here just to provide nicer error message in common * case. The real protection is the unique key on the catalog. */ - if (SearchSysCacheExists2(PUBLICATIONRELMAP, ObjectIdGetDatum(relid), - ObjectIdGetDatum(pubid))) + tup = SearchSysCache2(PUBLICATIONRELMAP, ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + + if (HeapTupleIsValid(tup)) { + bool is_except = ((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept; + + ReleaseSysCache(tup); table_close(rel, RowExclusiveLock); if (if_not_exists) return InvalidObjectAddress; - ereport(ERROR, - (errcode(ERRCODE_DUPLICATE_OBJECT), - errmsg("relation \"%s\" is already member of publication \"%s\"", - RelationGetRelationName(targetrel), pub->name))); + if (is_except) + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("table \"%s\" cannot be added because it is excluded from publication \"%s\"", + RelationGetQualifiedRelationName(targetrel), + pub->name))); + else + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("relation \"%s\" is already member of publication \"%s\"", + RelationGetRelationName(targetrel), pub->name))); } check_publication_add_relation(pri); @@ -982,12 +1000,13 @@ GetIncludedPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) * Gets list of table oids that were specified in the EXCEPT clause for a * publication. * - * This should only be used FOR ALL TABLES publications. + * This is used for FOR ALL TABLES and FOR TABLES IN SCHEMA publications, + * both of which support EXCEPT TABLE. */ List * GetExcludedPublicationTables(Oid pubid, PublicationPartOpt pub_partopt) { - Assert(GetPublication(pubid)->alltables); + Assert(GetPublication(pubid)->alltables || is_schema_publication(pubid)); return get_publication_relations(pubid, pub_partopt, true); } @@ -1049,15 +1068,15 @@ GetAllPublicationRelations(Oid pubid, char relkind, bool pubviaroot) TableScanDesc scan; HeapTuple tuple; List *result = NIL; - List *exceptlist = NIL; + List *except_relids = NIL; Assert(!(relkind == RELKIND_SEQUENCE && pubviaroot)); /* EXCEPT filtering applies only to relations, not sequences */ if (relkind == RELKIND_RELATION) - exceptlist = GetExcludedPublicationTables(pubid, pubviaroot ? - PUBLICATION_PART_ROOT : - PUBLICATION_PART_LEAF); + except_relids = GetExcludedPublicationTables(pubid, pubviaroot ? + PUBLICATION_PART_ROOT : + PUBLICATION_PART_LEAF); classRel = table_open(RelationRelationId, AccessShareLock); @@ -1075,7 +1094,7 @@ GetAllPublicationRelations(Oid pubid, char relkind, bool pubviaroot) if (is_publishable_class(relid, relForm) && !(relForm->relispartition && pubviaroot) && - !list_member_oid(exceptlist, relid)) + !list_member_oid(except_relids, relid)) result = lappend_oid(result, relid); } @@ -1097,7 +1116,7 @@ GetAllPublicationRelations(Oid pubid, char relkind, bool pubviaroot) if (is_publishable_class(relid, relForm) && !relForm->relispartition && - !list_member_oid(exceptlist, relid)) + !list_member_oid(except_relids, relid)) result = lappend_oid(result, relid); } @@ -1232,22 +1251,67 @@ GetSchemaPublicationRelations(Oid schemaid, PublicationPartOpt pub_partopt) /* * Gets the list of all relations published by FOR TABLES IN SCHEMA - * publication. + * publication, excluding any tables listed in the EXCEPT clause. */ List * GetAllSchemaPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) { List *result = NIL; List *pubschemalist = GetPublicationSchemas(pubid); + List *except_relids = NIL; ListCell *cell; + /* get the list of tables excluded via EXCEPT TABLE for this publication */ + if (pubschemalist != NIL) + except_relids = GetExcludedPublicationTables(pubid, pub_partopt); + foreach(cell, pubschemalist) { Oid schemaid = lfirst_oid(cell); List *schemaRels = NIL; schemaRels = GetSchemaPublicationRelations(schemaid, pub_partopt); - result = list_concat(result, schemaRels); + + if (except_relids != NIL) + { + /* filter out any tables that appear in the EXCEPT list */ + ListCell *rlc; + + foreach(rlc, schemaRels) + { + Oid relid = lfirst_oid(rlc); + bool excluded = list_member_oid(except_relids, relid); + + /* + * Also exclude any relation whose partition ancestor is in + * the EXCEPT list. This matters when pub_partopt is + * PUBLICATION_PART_ROOT: the except list holds only the root + * OID, but the schema scan may also return individual + * partition relations that live in the same schema. + */ + if (!excluded && get_rel_relispartition(relid)) + { + List *ancestors = get_partition_ancestors(relid); + ListCell *alc; + + foreach(alc, ancestors) + { + if (list_member_oid(except_relids, lfirst_oid(alc))) + { + excluded = true; + break; + } + } + list_free(ancestors); + } + + if (!excluded) + result = lappend_oid(result, relid); + } + list_free(schemaRels); + } + else + result = list_concat(result, schemaRels); } return result; @@ -1324,6 +1388,7 @@ is_table_publishable_in_publication(Oid relid, Publication *pub) { bool relispartition; List *ancestors = NIL; + HeapTuple tup; /* * For non-pubviaroot publications, a partitioned table is never the @@ -1380,20 +1445,62 @@ is_table_publishable_in_publication(Oid relid, Publication *pub) * If it's false, the partition is covered by its ancestor's presence in * the publication, it should be included (return true). */ - if (relispartition && - OidIsValid(GetTopMostAncestorInPublication(pub->oid, ancestors, NULL))) - return !pub->pubviaroot; + if (relispartition) + { + Oid ancestor_oid; + + ancestor_oid = GetTopMostAncestorInPublication(pub->oid, ancestors, NULL, NIL); + if (OidIsValid(ancestor_oid)) + { + /* + * The ancestor was found in the publication (via explicit + * membership or schema membership), but it may be excluded. Check + * for a prexcept row before concluding the partition is + * published. + */ + tup = SearchSysCache2(PUBLICATIONRELMAP, + ObjectIdGetDatum(ancestor_oid), + ObjectIdGetDatum(pub->oid)); + if (HeapTupleIsValid(tup)) + { + bool is_except; + + is_except = ((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept; + ReleaseSysCache(tup); + if (is_except) + return false; + } + return !pub->pubviaroot; + } + } /* * Check whether the table is explicitly published via pg_publication_rel * or pg_publication_namespace. + * + * A pg_publication_rel row with prexcept=true means the table is + * explicitly excluded via EXCEPT and must not be reported as published, + * even if its schema is otherwise included. A row with prexcept=false + * means it is explicitly included. If no pg_publication_rel row exists, + * the table is published iff its schema appears in + * pg_publication_namespace. */ - return (SearchSysCacheExists2(PUBLICATIONRELMAP, - ObjectIdGetDatum(relid), - ObjectIdGetDatum(pub->oid)) || - SearchSysCacheExists2(PUBLICATIONNAMESPACEMAP, - ObjectIdGetDatum(get_rel_namespace(relid)), - ObjectIdGetDatum(pub->oid))); + + tup = SearchSysCache2(PUBLICATIONRELMAP, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pub->oid)); + if (HeapTupleIsValid(tup)) + { + bool is_except; + + is_except = ((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept; + ReleaseSysCache(tup); + return !is_except; + } + + return SearchSysCacheExists2(PUBLICATIONNAMESPACEMAP, + ObjectIdGetDatum(get_rel_namespace(relid)), + ObjectIdGetDatum(pub->oid)); } /* diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 440adb356ad..c24c08a57b5 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -181,7 +181,7 @@ parse_publication_options(ParseState *pstate, */ static void ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, - List **rels, List **exceptrels, List **schemas) + List **rels, List **except_pubtables, List **schemas) { ListCell *cell; PublicationObjSpec *pubobj; @@ -200,7 +200,7 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, { case PUBLICATIONOBJ_EXCEPT_TABLE: pubobj->pubtable->except = true; - *exceptrels = lappend(*exceptrels, pubobj->pubtable); + *except_pubtables = lappend(*except_pubtables, pubobj->pubtable); break; case PUBLICATIONOBJ_TABLE: pubobj->pubtable->except = false; @@ -224,6 +224,38 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, /* Filter out duplicates if user specifies "sch1, sch1" */ *schemas = list_append_unique_oid(*schemas, schemaid); + + /* + * Qualify unqualified EXCEPT table names with the resolved + * current schema and reject any explicitly cross-schema + * entries. This mirrors the parse-time handling done for + * TABLES_IN_SCHEMA in preprocess_pubobj_list(), deferred here + * because CURRENT_SCHEMA is not known until execution time. + */ + if (pubobj->except_tables != NIL) + { + char *cur_schema_name = get_namespace_name(schemaid); + + foreach_ptr(PublicationObjSpec, eobj, pubobj->except_tables) + { + const char *eobj_schemaname = + eobj->pubtable->relation->schemaname; + const char *eobj_relname = + eobj->pubtable->relation->relname; + + if (eobj_schemaname == NULL) + eobj->pubtable->relation->schemaname = cur_schema_name; + else if (strcmp(eobj_schemaname, cur_schema_name) != 0) + ereport(ERROR, + errcode(ERRCODE_INVALID_OBJECT_DEFINITION), + errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", + quote_qualified_identifier(eobj_schemaname, eobj_relname), + cur_schema_name)); + + *except_pubtables = lappend(*except_pubtables, + eobj->pubtable); + } + } break; default: /* shouldn't happen */ @@ -305,7 +337,7 @@ pub_rf_contains_invalid_column(Oid pubid, Relation relation, List *ancestors, if (pubviaroot && relation->rd_rel->relispartition) { publish_as_relid - = GetTopMostAncestorInPublication(pubid, ancestors, NULL); + = GetTopMostAncestorInPublication(pubid, ancestors, NULL, NIL); if (!OidIsValid(publish_as_relid)) publish_as_relid = relid; @@ -389,7 +421,7 @@ pub_contains_invalid_column(Oid pubid, Relation relation, List *ancestors, */ if (pubviaroot && relation->rd_rel->relispartition) { - publish_as_relid = GetTopMostAncestorInPublication(pubid, ancestors, NULL); + publish_as_relid = GetTopMostAncestorInPublication(pubid, ancestors, NULL, NIL); if (!OidIsValid(publish_as_relid)) publish_as_relid = relid; @@ -849,7 +881,7 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) char publish_generated_columns; AclResult aclresult; List *relations = NIL; - List *exceptrelations = NIL; + List *except_pubtables = NIL; List *schemaidlist = NIL; /* must have CREATE privilege on database */ @@ -936,16 +968,16 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) /* Associate objects with the publication. */ ObjectsInPublicationToOids(stmt->pubobjects, pstate, &relations, - &exceptrelations, &schemaidlist); + &except_pubtables, &schemaidlist); if (stmt->for_all_tables) { /* Process EXCEPT table list */ - if (exceptrelations != NIL) + if (except_pubtables != NIL) { List *rels; - rels = OpenTableList(exceptrelations); + rels = OpenTableList(except_pubtables); PublicationAddTables(puboid, rels, true, NULL); CloseTableList(rels); } @@ -959,6 +991,8 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) } else if (!stmt->for_all_sequences) { + List *explicitrelids = NIL; + /* FOR TABLES IN SCHEMA requires superuser */ if (schemaidlist != NIL && !superuser()) ereport(ERROR, @@ -977,6 +1011,19 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) schemaidlist != NIL, publish_via_partition_root); + /* + * Collect explicit table OIDs now, before we close the relation + * list, so that except-table validation below can check for + * contradictions without relying on a catalog scan that might not + * yet see the just-inserted rows. + */ + if (except_pubtables != NIL) + { + foreach_ptr(PublicationRelInfo, pri, rels) + explicitrelids = lappend_oid(explicitrelids, + RelationGetRelid(pri->relation)); + } + PublicationAddTables(puboid, rels, true, NULL); CloseTableList(rels); } @@ -989,6 +1036,34 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) */ LockSchemaList(schemaidlist); PublicationAddSchemas(puboid, schemaidlist, true, NULL); + + if (except_pubtables != NIL) + { + List *except_rels; + + except_rels = OpenTableList(except_pubtables); + + /* + * Validate that each excluded table is not also in the + * explicit table list (which would be contradictory). Use the + * in-memory explicitrelids collected above rather than + * re-reading the catalog, which may not yet see the + * just-inserted rows. + */ + foreach_ptr(PublicationRelInfo, pri, except_rels) + { + Oid except_relid = RelationGetRelid(pri->relation); + + if (list_member_oid(explicitrelids, except_relid)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" cannot appear in both the table list and the EXCEPT clause", + RelationGetQualifiedRelationName(pri->relation))); + } + + PublicationAddTables(puboid, except_rels, true, NULL); + CloseTableList(except_rels); + } } } @@ -1683,12 +1758,12 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) else { List *relations = NIL; - List *exceptrelations = NIL; + List *except_pubtables = NIL; List *schemaidlist = NIL; Oid pubid = pubform->oid; ObjectsInPublicationToOids(stmt->pubobjects, pstate, &relations, - &exceptrelations, &schemaidlist); + &except_pubtables, &schemaidlist); CheckAlterPublication(stmt, tup, relations, schemaidlist); @@ -1711,7 +1786,7 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) errmsg("publication \"%s\" does not exist", stmt->pubname)); - relations = list_concat(relations, exceptrelations); + relations = list_concat(relations, except_pubtables); AlterPublicationTables(stmt, tup, relations, pstate->p_sourcetext, schemaidlist != NIL); AlterPublicationSchemas(stmt, tup, schemaidlist); @@ -1829,6 +1904,55 @@ RemovePublicationSchemaById(Oid psoid) table_close(rel, RowExclusiveLock); } +/* + * Remove any EXCEPT clause entries for a relation from schema publications. + * Called when a table changes schema (ALTER TABLE ... SET SCHEMA), so that + * a schema-scoped exclusion does not silently follow the table to its new + * schema. + */ +void +RemovePublicationExceptForRelation(Oid relid, Oid oldNspOid, Oid newNspOid) +{ + List *pubids; + + pubids = GetRelationExcludedPublications(relid); + + foreach_oid(pubid, pubids) + { + Oid proid; + + /* + * This problem does not apply to FOR ALL TABLES publications, because + * their EXCEPT clause is publication-scoped, not schema-scoped: the + * exclusion should persist regardless of what schema the table is in. + */ + if (!is_schema_publication(pubid)) + continue; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddress obj; + + ObjectAddressSet(obj, PublicationRelRelationId, proid); + + ereport(DEBUG2, + errmsg_internal("auto-drop exclusion of table %s from publication %s: table moved to schema %s", + quote_qualified_identifier(get_namespace_name(oldNspOid), + get_rel_name(relid)), + get_publication_name(pubid, false), + quote_identifier(get_namespace_name(newNspOid)))); + + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + list_free(pubids); +} + /* * Open relations specified by a PublicationTable list. * The returned tables are locked in ShareUpdateExclusiveLock mode in order to diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c83b6572abe 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -63,6 +63,7 @@ #include "commands/event_trigger.h" #include "commands/extension.h" #include "commands/repack.h" +#include "commands/publicationcmds.h" #include "commands/sequence.h" #include "commands/tablecmds.h" #include "commands/tablespace.h" @@ -19290,6 +19291,16 @@ AlterTableNamespaceInternal(Relation rel, Oid oldNspOid, Oid nspOid, AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid, false, objsMoved); + /* + * Remove any EXCEPT clause entries for this relation from schema + * publications. A schema-scoped exclusion is no longer meaningful once + * the table moves to a different schema. + */ + if (rel->rd_rel->relkind == RELKIND_RELATION || + rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE) + RemovePublicationExceptForRelation(RelationGetRelid(rel), oldNspOid, + nspOid); + table_close(classRel, RowExclusiveLock); } diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y index ff4e1388c55..6a7a1bc5f8d 100644 --- a/src/backend/parser/gram.y +++ b/src/backend/parser/gram.y @@ -58,6 +58,7 @@ #include "nodes/makefuncs.h" #include "nodes/nodeFuncs.h" #include "parser/parser.h" +#include "utils/builtins.h" #include "utils/datetime.h" #include "utils/xml.h" @@ -11272,7 +11273,7 @@ AlterOwnerStmt: ALTER AGGREGATE aggregate_with_argtypes OWNER TO RoleSpec * pub_obj is one of: * * TABLE table [, ...] - * TABLES IN SCHEMA schema [, ...] + * TABLES IN SCHEMA schema [EXCEPT (TABLE table [, ...] )] [, ...] * *****************************************************************************/ @@ -11332,23 +11333,26 @@ PublicationObjSpec: $$->pubtable->columns = $3; $$->pubtable->whereClause = $4; } - | TABLES IN_P SCHEMA ColId + | TABLES IN_P SCHEMA ColId opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_SCHEMA; $$->name = $4; + $$->except_tables = $5; $$->location = @4; } - | TABLES IN_P SCHEMA CURRENT_SCHEMA + | TABLES IN_P SCHEMA CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_CUR_SCHEMA; + $$->except_tables = $5; $$->location = @4; } - | ColId opt_column_list OptWhereClause + | ColId opt_column_list OptWhereClause opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $4; /* * If either a row filter or column list is specified, create * a PublicationTable object. @@ -11392,10 +11396,11 @@ PublicationObjSpec: $$->pubtable->columns = $2; $$->pubtable->whereClause = $3; } - | CURRENT_SCHEMA + | CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $2; $$->location = @1; } ; @@ -20784,6 +20789,8 @@ preprocess_pub_all_objtype_list(List *all_objects_list, List **pubobjects, /* * Process pubobjspec_list to check for errors in any of the objects and * convert PUBLICATIONOBJ_CONTINUATION into appropriate PublicationObjSpecType. + * Also flattens except_tables from TABLES IN SCHEMA nodes into the list so + * that ObjectsInPublicationToOids() sees them as top-level EXCEPT_TABLE entries. */ static void preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) @@ -20812,6 +20819,13 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLE) { + /* EXCEPT is not valid for table objects */ + if (pubobj->except_tables != NIL) + ereport(ERROR, + errcode(ERRCODE_SYNTAX_ERROR), + errmsg("EXCEPT is not allowed for TABLE publication objects"), + parser_errposition(pubobj->location)); + /* relation name or pubtable must be set for this type of object */ if (!pubobj->name && !pubobj->pubtable) ereport(ERROR, @@ -20860,6 +20874,36 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) errcode(ERRCODE_SYNTAX_ERROR), errmsg("invalid schema name"), parser_errposition(pubobj->location)); + + /* + * For TABLES_IN_SCHEMA, qualify unqualified EXCEPT table names + * with the parent schema and reject cross-schema entries at parse + * time, then flatten into the top-level list. + * + * For TABLES_IN_CUR_SCHEMA the schema name is not yet known, so + * skip both steps here; ObjectsInPublicationToOids() will + * qualify names and validate schema membership at execution time. + */ + if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLES_IN_SCHEMA) + { + foreach_ptr(PublicationObjSpec, eobj, pubobj->except_tables) + { + const char *eobj_schemaname = eobj->pubtable->relation->schemaname; + const char *eobj_relname = eobj->pubtable->relation->relname; + + if (eobj_schemaname == NULL) + eobj->pubtable->relation->schemaname = pubobj->name; + else if (strcmp(eobj_schemaname, pubobj->name) != 0) + ereport(ERROR, + errcode(ERRCODE_INVALID_OBJECT_DEFINITION), + errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", + quote_qualified_identifier(eobj_schemaname, eobj_relname), + pubobj->name), + parser_errposition(eobj->location)); + } + pubobjspec_list = list_concat(pubobjspec_list, pubobj->except_tables); + pubobj->except_tables = NIL; + } } prevobjtype = pubobj->pubobjtype; diff --git a/src/backend/replication/pgoutput/pgoutput.c b/src/backend/replication/pgoutput/pgoutput.c index 4ecfcbff7ab..7ee84ec1c83 100644 --- a/src/backend/replication/pgoutput/pgoutput.c +++ b/src/backend/replication/pgoutput/pgoutput.c @@ -2097,6 +2097,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) * are absorbed while decoding WAL. */ List *schemaPubids = GetSchemaPublications(schemaId); + List *except_pubids; ListCell *lc; Oid publish_as_relid = relid; int publish_ancestor_level = 0; @@ -2104,6 +2105,28 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) char relkind = get_rel_relkind(relid); List *rel_publications = NIL; + /* + * For the schema EXCEPT check, we must look up the top-most ancestor + * rather than the relation itself. check_publication_add_relation() + * prevents individual partitions from appearing in the EXCEPT clause, + * so only a root (non-partition) table can have prexcept = true. + * Using the partition's own OID would always return NIL and miss the + * exclusion. + */ + Oid root_relid; + + if (am_partition) + { + List *ancestors = get_partition_ancestors(relid); + + root_relid = llast_oid(ancestors); + list_free(ancestors); + } + else + root_relid = relid; + + except_pubids = GetRelationExcludedPublications(root_relid); + /* Reload publications if needed before use. */ if (!publications_valid) { @@ -2267,7 +2290,8 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) ancestor = GetTopMostAncestorInPublication(pub->oid, ancestors, - &level); + &level, + except_pubids); if (ancestor != InvalidOid) { @@ -2281,7 +2305,8 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) } if (list_member_oid(pubids, pub->oid) || - list_member_oid(schemaPubids, pub->oid) || + (list_member_oid(schemaPubids, pub->oid) && + !list_member_oid(except_pubids, pub->oid)) || ancestor_published) publish = true; } @@ -2360,6 +2385,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) list_free(pubids); list_free(schemaPubids); + list_free(except_pubids); list_free(rel_publications); entry->replicate_valid = true; diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c index af3935b0078..9470a0bbf5e 100644 --- a/src/bin/psql/describe.c +++ b/src/bin/psql/describe.c @@ -7038,6 +7038,24 @@ describePublications(const char *pattern) if (!addFooterToPublicationDesc(&buf, _("Tables from schemas:"), true, &cont)) goto error_return; + + if (pset.sversion >= 190000) + { + /* + * Get tables in the EXCEPT clause for this schema + * publication. + */ + printfPQExpBuffer(&buf, + "SELECT concat(c.relnamespace::regnamespace, '.', c.relname)\n" + "FROM pg_catalog.pg_class c\n" + " JOIN pg_catalog.pg_publication_rel pr ON c.oid = pr.prrelid\n" + "WHERE pr.prpubid = '%s'\n" + " AND pr.prexcept\n" + "ORDER BY 1", pubid); + if (!addFooterToPublicationDesc(&buf, _("Except tables:"), + true, &cont)) + goto error_return; + } } } else diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index de547a8cb37..53bb7c8679b 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -1065,6 +1065,24 @@ static const SchemaQuery Query_for_trigger_of_table = { "SELECT nspname FROM pg_catalog.pg_namespace "\ " WHERE nspname LIKE '%s'" +#define Query_for_list_of_tables_in_schema \ +"SELECT n.nspname || '.' || c.relname "\ +" FROM pg_catalog.pg_class c "\ +" JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "\ +" WHERE c.relkind IN (" CppAsString2(RELKIND_RELATION) ", " \ + CppAsString2(RELKIND_PARTITIONED_TABLE) ") "\ +" AND (n.nspname || '.' || c.relname) LIKE '%s' "\ +" AND n.nspname = '%s'" + +#define Query_for_list_of_tables_in_current_schema \ +"SELECT c.relname "\ +" FROM pg_catalog.pg_class c "\ +" JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "\ +" WHERE c.relkind IN (" CppAsString2(RELKIND_RELATION) ", " \ + CppAsString2(RELKIND_PARTITIONED_TABLE) ") "\ +" AND c.relname LIKE '%s' "\ +" AND n.nspname = pg_catalog.current_schema()" + /* Use COMPLETE_WITH_QUERY_VERBATIM with these queries for GUC names: */ #define Query_for_list_of_alter_system_set_vars \ "SELECT pg_catalog.lower(name) FROM pg_catalog.pg_settings "\ @@ -3787,8 +3805,21 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); - else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && (!ends_with(prev_wd, ','))) - COMPLETE_WITH("WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE", "WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* Complete "CREATE PUBLICATION <name> [...] WITH" */ else if (Matches("CREATE", "PUBLICATION", MatchAnyN, "WITH", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/include/catalog/pg_publication.h b/src/include/catalog/pg_publication.h index 89b4bb14f62..53e3d7c6f3d 100644 --- a/src/include/catalog/pg_publication.h +++ b/src/include/catalog/pg_publication.h @@ -191,7 +191,8 @@ extern List *GetPubPartitionOptionRelations(List *result, PublicationPartOpt pub_partopt, Oid relid); extern Oid GetTopMostAncestorInPublication(Oid puboid, List *ancestors, - int *ancestor_level); + int *ancestor_level, + List *except_pubids); extern bool is_publishable_relation(Relation rel); extern bool is_schema_publication(Oid pubid); diff --git a/src/include/commands/publicationcmds.h b/src/include/commands/publicationcmds.h index 4cf45c17cc5..59ae52ca7c8 100644 --- a/src/include/commands/publicationcmds.h +++ b/src/include/commands/publicationcmds.h @@ -27,6 +27,8 @@ extern void AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt); extern void RemovePublicationById(Oid pubid); extern void RemovePublicationRelById(Oid proid); extern void RemovePublicationSchemaById(Oid psoid); +extern void RemovePublicationExceptForRelation(Oid relid, Oid oldNspOid, + Oid newNspOid); extern ObjectAddress AlterPublicationOwner(const char *name, Oid newOwnerId); extern void AlterPublicationOwner_oid(Oid pubid, Oid newOwnerId); diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h index 91377a6cde3..98a03c0eeda 100644 --- a/src/include/nodes/parsenodes.h +++ b/src/include/nodes/parsenodes.h @@ -4493,6 +4493,8 @@ typedef struct PublicationObjSpec PublicationObjSpecType pubobjtype; /* type of this publication object */ char *name; PublicationTable *pubtable; + List *except_tables; /* tables specified in the EXCEPT clause (for + * TABLES IN SCHEMA) */ ParseLoc location; /* token location, or -1 if unknown */ } PublicationObjSpec; diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 29e54b214a0..ba01c720d4e 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -270,6 +270,12 @@ CREATE PUBLICATION testpub_foralltables_excepttable2 FOR ALL TABLES EXCEPT (test ERROR: syntax error at or near "testpub_tbl1" LINE 1: ..._foralltables_excepttable2 FOR ALL TABLES EXCEPT (testpub_tb... ^ +-- fail - EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testpub_tbl3); +ERROR: EXCEPT is not allowed for TABLE publication objects +LINE 2: FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testp... + ^ --------------------------------------------- -- SET ALL TABLES/SEQUENCES --------------------------------------------- @@ -470,7 +476,103 @@ HINT: Change the publication's EXCEPT clause using ALTER PUBLICATION ... SET AL RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Create same-named tables in public to verify unqualified EXCEPT entries +-- are qualified with the named schema, not public +CREATE TABLE testpub_nopk (foo int, bar int); +CREATE TABLE testpub_tbl_s1 (a int primary key, b text); +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + Publication testpub_schema_except1 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- Exclude multiple tables using unqualified names; same-named tables exist in +-- public to confirm unqualified names resolve to pub_test, not public +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + Publication testpub_schema_except2 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_nopk" + "pub_test.testpub_tbl_s1" + +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testp... + ^ +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); +ERROR: table "pub_test.testpub_tbl_s1" in EXCEPT clause does not belong to schema "public" +LINE 2: ...R TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.t... + ^ +-- Multiple schemas each with their own EXCEPT clause +CREATE PUBLICATION testpub_schema_except_multi + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_schema_except_multi + Publication testpub_schema_except_multi + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- fail: table appears in both the explicit table list and the EXCEPT clause +CREATE PUBLICATION testpub_except_conflict + FOR TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot appear in both the table list and the EXCEPT clause +-- fail: nonexistent table in EXCEPT clause +CREATE PUBLICATION testpub_except_norel + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- fail: partition cannot appear in EXCEPT clause; only root tables are allowed +CREATE TABLE pub_test.testpub_parted_s (a int) PARTITION BY LIST (a); +CREATE TABLE pub_test.testpub_part_s PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (1); +CREATE PUBLICATION testpub_except_partition + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); +ERROR: cannot specify relation "pub_test.testpub_part_s" in the publication EXCEPT clause +DETAIL: This operation is not supported for individual partitions. +-- fail: TABLE keyword is required for the first entry in the EXCEPT clause +CREATE PUBLICATION testpub_except_nokw + FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +ERROR: syntax error at or near "testpub_nopk" +LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + ^ +-- Cleanup +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP TABLE pub_test.testpub_parted_s CASCADE; +DROP TABLE testpub_nopk, testpub_tbl_s1; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +--------------------------------------------- +-- Tests for publications with SEQUENCES +--------------------------------------------- CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; -- FOR ALL SEQUENCES @@ -1953,6 +2055,27 @@ ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b); ERROR: column specification not allowed for schema LINE 1: ...TION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b)... ^ +-- EXCEPT clause with CURRENT_SCHEMA: cross-schema entry must be rejected +SET search_path = pub_test1; +-- qualified name from wrong schema -> error +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.tbl1); +ERROR: table "pub_test2.tbl1" in EXCEPT clause does not belong to schema "pub_test1" +-- unqualified name implicitly qualified with current schema (pub_test1.tbl) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl); +RESET client_min_messages; +\dRp+ testpub_cursch_except + Publication testpub_cursch_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test1" +Except tables: + "pub_test1.tbl" + +DROP PUBLICATION testpub_cursch_except; +RESET search_path; -- cleanup pub_test1 schema for invalidation tests ALTER PUBLICATION testpub2_forschema DROP TABLES IN SCHEMA pub_test1; DROP PUBLICATION testpub3_forschema, testpub4_forschema, testpub5_forschema, testpub6_forschema, testpub_fortable; @@ -2304,6 +2427,7 @@ DROP ROLE regress_publication_user_dummy; -- Test pg_get_publication_tables(text[], oid) function CREATE SCHEMA gpt_test_sch; CREATE TABLE gpt_test_sch.tbl_sch (id int); +CREATE TABLE gpt_test_sch.tbl_sch2 (id int); CREATE TABLE tbl_normal (id int); CREATE TABLE tbl_parent (id1 int, id2 int, id3 int) PARTITION BY RANGE (id1); CREATE TABLE tbl_part1 PARTITION OF tbl_parent FOR VALUES FROM (1) TO (10); @@ -2314,6 +2438,7 @@ CREATE PUBLICATION pub_all_no_viaroot FOR ALL TABLES WITH (publish_via_partition CREATE PUBLICATION pub_all_except FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = true); CREATE PUBLICATION pub_all_except_no_viaroot FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_schema FOR TABLES IN SCHEMA gpt_test_sch; +CREATE PUBLICATION pub_schema_except FOR TABLES IN SCHEMA gpt_test_sch EXCEPT (TABLE gpt_test_sch.tbl_sch); CREATE PUBLICATION pub_normal FOR TABLE tbl_normal WHERE (id < 10); CREATE PUBLICATION pub_part_leaf FOR TABLE tbl_part1 WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_part_parent FOR TABLE tbl_parent (id1, id2) WHERE (id1 = 10) WITH (publish_via_partition_root = true); @@ -2465,6 +2590,18 @@ SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_part1'); -- no r ---------+---------+-------+------ (0 rows) +-- test for EXCEPT clause with schema publication +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch'); -- no result (excluded) + pubname | relname | attrs | qual +---------+---------+-------+------ +(0 rows) + +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch2'); -- one row (included via schema) + pubname | relname | attrs | qual +-------------------+----------+-------+------ + pub_schema_except | tbl_sch2 | 1 | +(1 row) + -- two rows with different row filter SELECT * FROM test_gpt(ARRAY['pub_all', 'pub_normal'], 'tbl_normal'); pubname | relname | attrs | qual @@ -2517,6 +2654,7 @@ DROP PUBLICATION pub_all_no_viaroot; DROP PUBLICATION pub_all_except; DROP PUBLICATION pub_all_except_no_viaroot; DROP PUBLICATION pub_schema; +DROP PUBLICATION pub_schema_except; DROP PUBLICATION pub_normal; DROP PUBLICATION pub_part_leaf; DROP PUBLICATION pub_part_parent; @@ -2525,7 +2663,9 @@ DROP PUBLICATION pub_part_parent_child; DROP VIEW gpt_test_view; DROP TABLE tbl_normal, tbl_parent, tbl_part1; DROP SCHEMA gpt_test_sch CASCADE; -NOTICE: drop cascades to table gpt_test_sch.tbl_sch +NOTICE: drop cascades to 2 other objects +DETAIL: drop cascades to table gpt_test_sch.tbl_sch +drop cascades to table gpt_test_sch.tbl_sch2 -- stage objects for pg_dump tests CREATE SCHEMA pubme CREATE TABLE t0 (c int, d int) CREATE TABLE t1 (c int); CREATE SCHEMA pubme2 CREATE TABLE t0 (c int, d int); diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 041e14a4de6..4bc0e2ff23d 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -123,6 +123,9 @@ CREATE PUBLICATION testpub_foralltables_excepttable1 FOR ALL TABLES EXCEPT (TABL \d testpub_tbl1 -- fail - first table in the EXCEPT list should use TABLE keyword CREATE PUBLICATION testpub_foralltables_excepttable2 FOR ALL TABLES EXCEPT (testpub_tbl1, testpub_tbl2); +-- fail - EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testpub_tbl3); --------------------------------------------- -- SET ALL TABLES/SEQUENCES @@ -220,7 +223,71 @@ RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Create same-named tables in public to verify unqualified EXCEPT entries +-- are qualified with the named schema, not public +CREATE TABLE testpub_nopk (foo int, bar int); +CREATE TABLE testpub_tbl_s1 (a int primary key, b text); + +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + +-- Exclude multiple tables using unqualified names; same-named tables exist in +-- public to confirm unqualified names resolve to pub_test, not public +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); + +-- Multiple schemas each with their own EXCEPT clause +CREATE PUBLICATION testpub_schema_except_multi + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_schema_except_multi + +-- fail: table appears in both the explicit table list and the EXCEPT clause +CREATE PUBLICATION testpub_except_conflict + FOR TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: nonexistent table in EXCEPT clause +CREATE PUBLICATION testpub_except_norel + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- fail: partition cannot appear in EXCEPT clause; only root tables are allowed +CREATE TABLE pub_test.testpub_parted_s (a int) PARTITION BY LIST (a); +CREATE TABLE pub_test.testpub_part_s PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (1); +CREATE PUBLICATION testpub_except_partition + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); + +-- fail: TABLE keyword is required for the first entry in the EXCEPT clause +CREATE PUBLICATION testpub_except_nokw + FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + +-- Cleanup +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP TABLE pub_test.testpub_parted_s CASCADE; +DROP TABLE testpub_nopk, testpub_tbl_s1; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; + +--------------------------------------------- +-- Tests for publications with SEQUENCES +--------------------------------------------- CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; @@ -1189,6 +1256,18 @@ ALTER PUBLICATION testpub1_forschema SET TABLES IN SCHEMA pub_test1, pub_test1; ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo (a, b); ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b); +-- EXCEPT clause with CURRENT_SCHEMA: cross-schema entry must be rejected +SET search_path = pub_test1; +-- qualified name from wrong schema -> error +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.tbl1); +-- unqualified name implicitly qualified with current schema (pub_test1.tbl) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl); +RESET client_min_messages; +\dRp+ testpub_cursch_except +DROP PUBLICATION testpub_cursch_except; +RESET search_path; + -- cleanup pub_test1 schema for invalidation tests ALTER PUBLICATION testpub2_forschema DROP TABLES IN SCHEMA pub_test1; DROP PUBLICATION testpub3_forschema, testpub4_forschema, testpub5_forschema, testpub6_forschema, testpub_fortable; @@ -1443,6 +1522,7 @@ DROP ROLE regress_publication_user_dummy; -- Test pg_get_publication_tables(text[], oid) function CREATE SCHEMA gpt_test_sch; CREATE TABLE gpt_test_sch.tbl_sch (id int); +CREATE TABLE gpt_test_sch.tbl_sch2 (id int); CREATE TABLE tbl_normal (id int); CREATE TABLE tbl_parent (id1 int, id2 int, id3 int) PARTITION BY RANGE (id1); CREATE TABLE tbl_part1 PARTITION OF tbl_parent FOR VALUES FROM (1) TO (10); @@ -1454,6 +1534,7 @@ CREATE PUBLICATION pub_all_no_viaroot FOR ALL TABLES WITH (publish_via_partition CREATE PUBLICATION pub_all_except FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = true); CREATE PUBLICATION pub_all_except_no_viaroot FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_schema FOR TABLES IN SCHEMA gpt_test_sch; +CREATE PUBLICATION pub_schema_except FOR TABLES IN SCHEMA gpt_test_sch EXCEPT (TABLE gpt_test_sch.tbl_sch); CREATE PUBLICATION pub_normal FOR TABLE tbl_normal WHERE (id < 10); CREATE PUBLICATION pub_part_leaf FOR TABLE tbl_part1 WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_part_parent FOR TABLE tbl_parent (id1, id2) WHERE (id1 = 10) WITH (publish_via_partition_root = true); @@ -1510,6 +1591,10 @@ SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'gpt_test_sch.tbl_sch SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_parent'); -- no result (excluded) SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_part1'); -- no result +-- test for EXCEPT clause with schema publication +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch'); -- no result (excluded) +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch2'); -- one row (included via schema) + -- two rows with different row filter SELECT * FROM test_gpt(ARRAY['pub_all', 'pub_normal'], 'tbl_normal'); @@ -1538,6 +1623,7 @@ DROP PUBLICATION pub_all_no_viaroot; DROP PUBLICATION pub_all_except; DROP PUBLICATION pub_all_except_no_viaroot; DROP PUBLICATION pub_schema; +DROP PUBLICATION pub_schema_except; DROP PUBLICATION pub_normal; DROP PUBLICATION pub_part_leaf; DROP PUBLICATION pub_part_parent; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 8c58d282eee..18c7b2c1fca 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -24,14 +24,17 @@ my $result; sub test_except_root_partition { - my ($pubviaroot) = @_; + my ($pubviaroot, $pubsql) = @_; + $pubsql //= + "CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1)"; + $pubsql .= " WITH (publish_via_partition_root = $pubviaroot)"; # If the root partitioned table is in the EXCEPT clause, all its # partitions are excluded from publication, regardless of the # publish_via_partition_root setting. $node_publisher->safe_psql( 'postgres', qq( - CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1) WITH (publish_via_partition_root = $pubviaroot); + $pubsql; INSERT INTO root1 VALUES (1), (101); )); $node_subscriber->safe_psql('postgres', @@ -223,6 +226,131 @@ $node_subscriber->safe_psql( test_except_root_partition('false'); test_except_root_partition('true'); +# Same validation using TABLES IN SCHEMA instead of FOR ALL TABLES. +my $schema_pub = + "CREATE PUBLICATION tap_pub_part FOR TABLES IN SCHEMA public EXCEPT (TABLE public.root1)"; +test_except_root_partition('false', $schema_pub); +test_except_root_partition('true', $schema_pub); + +# ============================================ +# EXCEPT test cases for TABLES IN SCHEMA +# ============================================ + +# Create a dedicated schema with two tables: one to be published and one to be +# excluded. Also create inherited tables to verify ONLY semantics. +$node_publisher->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_published AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.tab_excluded AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.parent (a int); + CREATE TABLE sch1.child (b int) INHERITS (sch1.parent); +)); + +$node_subscriber->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_published (a int); + CREATE TABLE sch1.tab_excluded (a int); + CREATE TABLE sch1.parent (a int); + CREATE TABLE sch1.child (b int) INHERITS (sch1.parent); +)); + +# Basic test: initial sync respects EXCEPT. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_excluded)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: initial sync copies included table'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: initial sync skips excluded table'); + +# DML: only the included table should be replicated. +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (6); + INSERT INTO sch1.tab_excluded VALUES (6); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(6), + 'TABLES IN SCHEMA EXCEPT: DML on included table is replicated'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: DML on excluded table is not replicated'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Inherited tables: excluding the parent (without ONLY) also excludes the child. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.parent)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.child VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.child"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: excluding parent (without ONLY) also excludes child' +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Test that EXCEPT (TABLE ONLY parent) excludes only the parent itself, not its +# child. Truncate child first so rows from the previous test are not copied by +# the initial table sync of the next subscription. +$node_publisher->safe_psql('postgres', 'TRUNCATE sch1.child'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE sch1.child'); +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE ONLY sch1.parent)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.child VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.child"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: ONLY parent in EXCEPT does not exclude child'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Cleanup schema tables before the multi-publication section. +$node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); +$node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); + # ============================================ # Test when a subscription is subscribing to multiple publications # ============================================ @@ -254,6 +382,7 @@ $node_publisher->safe_psql( DROP PUBLICATION tap_pub2; TRUNCATE tab1; )); +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_subscriber->safe_psql('postgres', qq(TRUNCATE tab1)); # OK when a table is excluded by pub1 EXCEPT clause, but it is included by pub2 -- 2.50.1 (Apple Git-155)
v13-0002-Add-EXCEPT-support-to-ALTER-PUBLICATION-ADD-TABL.patch (application/octet-stream, 23.2K) download From 4b5ba3a1deb6ba3af3e7f08d047a37ab802268b1 Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Mon, 15 Jun 2026 16:45:55 +0530 Subject: [PATCH v13 2/3] Add EXCEPT support to ALTER PUBLICATION ADD TABLES IN SCHEMA Extend the EXCEPT clause support to allow tables to be excluded when adding a schema to a publication via ALTER PUBLICATION ... ADD. Syntax: ALTER PUBLICATION pub ADD TABLES IN SCHEMA s EXCEPT (TABLE s.t1); Since pg_dump uses ALTER PUBLICATION ... ADD, support for it is included in this patch. --- doc/src/sgml/ref/alter_publication.sgml | 52 ++++++++++- src/backend/catalog/pg_publication.c | 19 ++-- src/backend/commands/publicationcmds.c | 107 +++++++++++++++++++++- src/bin/pg_dump/pg_dump.c | 30 +++++- src/bin/pg_dump/t/002_pg_dump.pl | 24 +++++ src/bin/psql/tab-complete.in.c | 17 ++++ src/test/regress/expected/publication.out | 32 ++++++- src/test/regress/sql/publication.sql | 20 +++- src/test/subscription/t/037_except.pl | 32 +++++++ 9 files changed, 318 insertions(+), 15 deletions(-) diff --git a/doc/src/sgml/ref/alter_publication.sgml b/doc/src/sgml/ref/alter_publication.sgml index 52114a16a39..8d9d3573bd7 100644 --- a/doc/src/sgml/ref/alter_publication.sgml +++ b/doc/src/sgml/ref/alter_publication.sgml @@ -31,7 +31,7 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA <replaceable class="parameter">tables_in_schema</replaceable> [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -47,6 +47,10 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <replaceable class="parameter">table_object</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] [ WHERE ( <replaceable class="parameter">expression</replaceable> ) ] +<phrase>and <replaceable class="parameter">tables_in_schema</replaceable> is:</phrase> + + { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] + <phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> TABLE <replaceable class="parameter">table_object</replaceable> [, ... ] @@ -110,6 +114,14 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <literal>ADD TABLE</literal>. </para> + <para> + The <literal>EXCEPT</literal> clause can be used with + <literal>ADD TABLES IN SCHEMA</literal> to exclude specific tables from the + publication. Using <literal>DROP TABLES IN SCHEMA</literal> on a publication + will automatically also remove any associated <literal>EXCEPT</literal> + entries. + </para> + <para> The fourth variant of this command listed in the synopsis can change all of the publication properties specified in @@ -198,6 +210,34 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r </listitem> </varlistentry> + <varlistentry> + <term><literal>EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] )</literal></term> + <listitem> + <para> + When used with <literal>ADD TABLES IN SCHEMA</literal>, specifies + tables to be excluded from the publication. Each named + table must belong to the schema specified in the same + <literal>TABLES IN SCHEMA</literal> clause. Table names may be + schema-qualified or unqualified; unqualified names are implicitly + qualified with the schema named in the same clause. See + <xref linkend="sql-createpublication"/> for further details on the + semantics of <literal>EXCEPT</literal>. + </para> + <para> + For <literal>FOR TABLES IN SCHEMA</literal> publications, the + <literal>EXCEPT</literal> clause is schema-scoped. If a table listed in + the <literal>EXCEPT</literal> clause is later moved to a different schema + using <command>ALTER TABLE ... SET SCHEMA</command>, the exclusion is + removed; the table will then be published if its new schema is part of a + publication. If the table is subsequently moved back to the original + schema, the exclusion is not restored, and must be re-established + explicitly using <command>ALTER PUBLICATION</command>. Dropping a table + always removes it from the <literal>EXCEPT</literal> clause, regardless of + publication type. + </para> + </listitem> + </varlistentry> + <varlistentry> <term><literal>SET ( <replaceable class="parameter">publication_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] )</literal></term> <listitem> @@ -288,6 +328,16 @@ ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA marketing, sales; </programlisting> </para> + <para> + Add schema <structname>sales</structname> to the publication + <structname>sales_publication</structname>, excluding the + <structname>sales.internal</structname> and + <structname>sales.drafts</structname> tables: +<programlisting> +ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA sales EXCEPT (TABLE internal, drafts); +</programlisting> + </para> + <para> Add tables <structname>users</structname>, <structname>departments</structname> and schema diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index 4089b505f89..d1ff8839037 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -649,15 +649,18 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, * here, as CreatePublication() function invalidates all relations as part * of defining a FOR ALL TABLES publication. * - * For ALTER PUBLICATION, invalidation is needed only when adding an - * EXCEPT table to a publication already marked as ALL TABLES. For - * publications that were originally empty or defined as ALL SEQUENCES and - * are being converted to ALL TABLES, invalidation is skipped here, as - * AlterPublicationAllFlags() function invalidates all relations while - * marking the publication as ALL TABLES publication. + * For ALTER PUBLICATION, invalidation is needed when adding an EXCEPT + * table to either a FOR ALL TABLES publication (pub->alltables is true) + * or a FOR TABLES IN SCHEMA publication (is_schema_publication is true). + * The exception: when a publication is being converted to FOR ALL TABLES + * (pub->alltables is still false at this point), + * AlterPublicationAllFlags() will perform a full invalidation, so we skip + * it here. */ - inval_except_table = (alter_stmt != NULL) && pub->alltables && - (alter_stmt->for_all_tables && pri->except); + inval_except_table = (alter_stmt != NULL) && pri->except && + (pub->alltables + ? alter_stmt->for_all_tables + : is_schema_publication(pubid)); if (!pri->except || inval_except_table) { diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index c24c08a57b5..693a0e3e060 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -70,6 +70,13 @@ static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok); static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); +static void AlterPublicationSchemas(AlterPublicationStmt *stmt, + HeapTuple tup, List *schemaidlist, + List *except_pubtables); +static void AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, + List *except_pubtables, + List *schemaidlist); static char defGetGeneratedColsOption(DefElem *def); @@ -1500,7 +1507,8 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, */ static void AlterPublicationSchemas(AlterPublicationStmt *stmt, - HeapTuple tup, List *schemaidlist) + HeapTuple tup, List *schemaidlist, + List *except_pubtables) { Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); @@ -1577,6 +1585,97 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, */ PublicationAddSchemas(pubform->oid, schemaidlist, true, stmt); } + + /* + * Increment the command counter so that is_schema_publication() in + * GetExcludedPublicationTables() can see the just-inserted schema + * rows when AlterPublicationSchemaExceptTables runs next. + */ + if (stmt->action == AP_AddObjects || stmt->action == AP_SetObjects) + CommandCounterIncrement(); + + AlterPublicationSchemaExceptTables(stmt, tup, except_pubtables, schemaidlist); +} + +/* + * Alter the EXCEPT list of a schema-level publication. + * + * Adds, removes, or replaces except-table entries in pg_publication_rel + * (rows with prexcept = true). These entries suppress publication of the + * named tables that would otherwise be covered by a FOR TABLES IN SCHEMA + * clause. + */ +static void +AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, List *except_pubtables, + List *schemaidlist) +{ + Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); + Oid pubid = pubform->oid; + + /* + * Nothing to do if no EXCEPT entries. + */ + if (!except_pubtables) + return; + + /* + * This function handles EXCEPT entries for schema-level publications + * only. For FOR ALL TABLES publications, EXCEPT entries are already + * processed by AlterPublicationTables(). + */ + if (schemaidlist == NIL && !is_schema_publication(pubid)) + return; + + /* + * Dropping a schema from a publication removes all its EXCEPT entries via + * cascade. The concept of "drop all schema tables from the publication + * EXCEPT these ones" is not supported. + */ + if (stmt->action == AP_DropObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); + + /* + * XXX EXCEPT with SET is not currently implemented. Workaround: DROP and + * re-ADD the schema with the desired EXCEPT list. + */ + if (stmt->action == AP_SetObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"), + errhint("Drop and re-add the schema with the desired EXCEPT list."))); + + if (stmt->action == AP_AddObjects) + { + List *rels; + List *explicitrelids; + + rels = OpenTableList(except_pubtables); + + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + /* + * Validate that each excluded table is not also in the explicit table + * list (which would be contradictory). + */ + foreach_ptr(PublicationRelInfo, pri, rels) + { + Oid relid = RelationGetRelid(pri->relation); + + if (list_member_oid(explicitrelids, relid)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" cannot appear in both the table list and the EXCEPT clause", + RelationGetQualifiedRelationName(pri->relation))); + } + + PublicationAddTables(pubid, rels, false, stmt); + + CloseTableList(rels); + } } /* @@ -1786,10 +1885,12 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) errmsg("publication \"%s\" does not exist", stmt->pubname)); - relations = list_concat(relations, except_pubtables); + if (stmt->for_all_tables) + relations = list_concat(relations, except_pubtables); + AlterPublicationTables(stmt, tup, relations, pstate->p_sourcetext, schemaidlist != NIL); - AlterPublicationSchemas(stmt, tup, schemaidlist); + AlterPublicationSchemas(stmt, tup, schemaidlist, except_pubtables); AlterPublicationAllFlags(stmt, rel, tup); } diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c index a0f7f8e2168..85ab3b00875 100644 --- a/src/bin/pg_dump/pg_dump.c +++ b/src/bin/pg_dump/pg_dump.c @@ -5019,6 +5019,7 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) PublicationInfo *pubinfo = pubsinfo->publication; PQExpBuffer query; char *tag; + bool has_except = false; /* Do nothing if not dumping schema */ if (!dopt->dumpSchema) @@ -5029,7 +5030,34 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) query = createPQExpBuffer(); appendPQExpBuffer(query, "ALTER PUBLICATION %s ", fmtId(pubinfo->dobj.name)); - appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s;\n", fmtId(schemainfo->dobj.name)); + appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s", fmtId(schemainfo->dobj.name)); + + /* + * Append EXCEPT clause for any tables that belong to this schema + * and are excluded from the publication. + */ + for (SimplePtrListCell *cell = pubinfo->except_tables.head; cell; cell = cell->next) + { + TableInfo *tbinfo = (TableInfo *) cell->ptr; + + if (strcmp(tbinfo->dobj.namespace->dobj.name, schemainfo->dobj.name) == 0) + { + if (!has_except) + { + appendPQExpBufferStr(query, " EXCEPT ("); + has_except = true; + } + else + appendPQExpBufferStr(query, ", "); + + appendPQExpBuffer(query, "TABLE ONLY %s", fmtId(tbinfo->dobj.name)); + } + } + + if (has_except) + appendPQExpBufferStr(query, ")"); + + appendPQExpBufferStr(query, ";\n"); /* * There is no point in creating drop query as the drop is done by schema diff --git a/src/bin/pg_dump/t/002_pg_dump.pl b/src/bin/pg_dump/t/002_pg_dump.pl index 3ee9fda50e4..b8f4aa769ec 100644 --- a/src/bin/pg_dump/t/002_pg_dump.pl +++ b/src/bin/pg_dump/t/002_pg_dump.pl @@ -3242,6 +3242,30 @@ my %tests = ( like => { %full_runs, section_post_data => 1, }, }, + 'CREATE PUBLICATION pub11' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub11 FOR TABLES IN SCHEMA dump_test EXCEPT (TABLE test_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub11 WITH (publish = 'insert, update, delete, truncate');\E + .*? + \QALTER PUBLICATION pub11 ADD TABLES IN SCHEMA dump_test EXCEPT (TABLE ONLY test_table);\E + /xms, + like => { %full_runs, section_post_data => 1, }, + }, + + 'CREATE PUBLICATION pub12' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub12 FOR TABLES IN SCHEMA dump_test EXCEPT (TABLE test_table, dump_test.test_second_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub12 WITH (publish = 'insert, update, delete, truncate');\E + .*? + \QALTER PUBLICATION pub12 ADD TABLES IN SCHEMA dump_test EXCEPT (TABLE ONLY test_table, TABLE ONLY test_second_table);\E + /xms, + like => { %full_runs, section_post_data => 1, }, + }, + 'CREATE SUBSCRIPTION sub1' => { create_order => 50, create_sql => 'CREATE SUBSCRIPTION sub1 diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index 53bb7c8679b..a290902d61e 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2373,6 +2373,23 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); + /* After a single schema name in ADD context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index ba01c720d4e..3c452139bf9 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -564,12 +564,42 @@ CREATE PUBLICATION testpub_except_nokw ERROR: syntax error at or near "testpub_nopk" LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); ^ +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; +-- fail: non-existing table in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- fail: EXCEPT table belongs to a different schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 1: ...xcept ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.tes... + ^ +-- fail: TABLE keyword is required for the first entry in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +ERROR: syntax error at or near "testpub_nopk" +LINE 1: ...lter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_no... + ^ +-- ADD: qualified and unqualified names; unqualified is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + "pub_test.testpub_tbl_s2" + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP TABLE pub_test.testpub_parted_s CASCADE; DROP TABLE testpub_nopk, testpub_tbl_s1; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi, testpub_alter_except; --------------------------------------------- -- Tests for publications with SEQUENCES --------------------------------------------- diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 4bc0e2ff23d..240190aa41f 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -278,12 +278,30 @@ CREATE PUBLICATION testpub_except_partition CREATE PUBLICATION testpub_except_nokw FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; + +-- fail: non-existing table in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- fail: EXCEPT table belongs to a different schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- fail: TABLE keyword is required for the first entry in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + +-- ADD: qualified and unqualified names; unqualified is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); +\dRp+ testpub_alter_except + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP TABLE pub_test.testpub_parted_s CASCADE; DROP TABLE testpub_nopk, testpub_tbl_s1; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi, testpub_alter_except; --------------------------------------------- -- Tests for publications with SEQUENCES diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 18c7b2c1fca..0ba6d6f8bb2 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -347,6 +347,38 @@ is($result, qq(5), $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); +# ============================================ +# ALTER PUBLICATION EXCEPT for TABLES IN SCHEMA +# ============================================ + +# Truncate subscriber tables to remove data accumulated from previous tests. +$node_subscriber->safe_psql('postgres', + 'TRUNCATE sch1.tab_published, sch1.tab_excluded, sch1.parent, sch1.child'); + +# ADD: add a schema with an excepted table; verify the except entry takes effect. +$node_publisher->safe_psql('postgres', "CREATE PUBLICATION sch_pub"); +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub ADD TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_excluded)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(6), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: included table synced'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + # Cleanup schema tables before the multi-publication section. $node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); $node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); -- 2.50.1 (Apple Git-155)
v13-0003-Add-EXCEPT-support-to-ALTER-PUBLICATION-SET-TABL.patch (application/octet-stream, 26.1K) download From 6949cf77323c3319cdd134074b471d8675b7d9cf Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Mon, 15 Jun 2026 16:46:12 +0530 Subject: [PATCH v13 3/3] Add EXCEPT support to ALTER PUBLICATION SET TABLES IN SCHEMA Extend AlterPublicationExceptTables() with the AP_SetObjects case, which redefines the publication and replaces the entire EXCEPT list. Syntax: ALTER PUBLICATION pub SET TABLES IN SCHEMA s EXCEPT (TABLE t1); This patch also cleans up EXCEPT entries when a schema is dropped from the publication. --- doc/src/sgml/ref/alter_publication.sgml | 27 +++- src/backend/commands/publicationcmds.c | 135 +++++++++++++++++--- src/backend/replication/pgoutput/pgoutput.c | 10 +- src/bin/psql/tab-complete.in.c | 17 +++ src/test/regress/expected/publication.out | 86 +++++++++++++ src/test/regress/sql/publication.sql | 38 ++++++ src/test/subscription/t/037_except.pl | 85 ++++++++++++ 7 files changed, 371 insertions(+), 27 deletions(-) diff --git a/doc/src/sgml/ref/alter_publication.sgml b/doc/src/sgml/ref/alter_publication.sgml index 8d9d3573bd7..4be085ef1b2 100644 --- a/doc/src/sgml/ref/alter_publication.sgml +++ b/doc/src/sgml/ref/alter_publication.sgml @@ -97,7 +97,11 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r used with a publication defined with <literal>FOR TABLE</literal> or <literal>FOR TABLES IN SCHEMA</literal>, replaces the list of tables/schemas in the publication with the specified list; the existing tables or schemas - that were present in the publication will be removed. + that were present in the publication will be removed. When + <literal>SET TABLES IN SCHEMA</literal> is used with an + <literal>EXCEPT</literal> clause, the excluded tables for each schema are + replaced with the specified list; if <literal>EXCEPT</literal> is omitted + for a schema, any existing exclusions for that schema are cleared. </para> <para> @@ -116,10 +120,8 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <para> The <literal>EXCEPT</literal> clause can be used with - <literal>ADD TABLES IN SCHEMA</literal> to exclude specific tables from the - publication. Using <literal>DROP TABLES IN SCHEMA</literal> on a publication - will automatically also remove any associated <literal>EXCEPT</literal> - entries. + <literal>ADD TABLES IN SCHEMA</literal> to exclude specific tables from a + schema-level publication. </para> <para> @@ -214,7 +216,8 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <term><literal>EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] )</literal></term> <listitem> <para> - When used with <literal>ADD TABLES IN SCHEMA</literal>, specifies + When used with <literal>ADD TABLES IN SCHEMA</literal> + or <literal>SET TABLES IN SCHEMA</literal>, specifies tables to be excluded from the publication. Each named table must belong to the schema specified in the same <literal>TABLES IN SCHEMA</literal> clause. Table names may be @@ -338,6 +341,18 @@ ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA sales EXCEPT (TABLE int </programlisting> </para> + <para> + Replace the schema list of <structname>sales_publication</structname> with + <structname>sales</structname>, excluding only + <structname>sales.drafts</structname>. Other than + <structname>sales.drafts</structname>, any previously excluded tables for schema + <structname>sales</structname> are no longer excluded. Any schemas previously in + <structname>sales_publication</structname> are removed: +<programlisting> +ALTER PUBLICATION sales_publication SET TABLES IN SCHEMA sales EXCEPT (TABLE drafts); +</programlisting> + </para> + <para> Add tables <structname>users</structname>, <structname>departments</structname> and schema diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 693a0e3e060..531493a1516 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -1588,8 +1588,8 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, /* * Increment the command counter so that is_schema_publication() in - * GetExcludedPublicationTables() can see the just-inserted schema - * rows when AlterPublicationSchemaExceptTables runs next. + * GetExcludedPublicationTables() can see the just-inserted schema rows + * when AlterPublicationSchemaExceptTables runs next. */ if (stmt->action == AP_AddObjects || stmt->action == AP_SetObjects) CommandCounterIncrement(); @@ -1607,16 +1607,18 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, */ static void AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, - HeapTuple tup, List *except_pubtables, - List *schemaidlist) + HeapTuple tup, List *except_pubtables, + List *schemaidlist) { Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); Oid pubid = pubform->oid; /* - * Nothing to do if no EXCEPT entries. + * Nothing to do if there are no EXCEPT entries, unless handling the SET + * command, because if the user has removed all exceptions we need to drop + * any existing ones. */ - if (!except_pubtables) + if (!except_pubtables && stmt->action != AP_SetObjects) return; /* @@ -1637,16 +1639,6 @@ AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); - /* - * XXX EXCEPT with SET is not currently implemented. Workaround: DROP and - * re-ADD the schema with the desired EXCEPT list. - */ - if (stmt->action == AP_SetObjects) - ereport(ERROR, - (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"), - errhint("Drop and re-add the schema with the desired EXCEPT list."))); - if (stmt->action == AP_AddObjects) { List *rels; @@ -1674,6 +1666,84 @@ AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, PublicationAddTables(pubid, rels, false, stmt); + CloseTableList(rels); + } + else /* AP_SetObjects */ + { + List *oldexceptrelids = NIL; + List *newexceptrelids = NIL; + List *delrelids = NIL; + List *rels; + List *explicitrelids; + + rels = OpenTableList(except_pubtables); + + /* Collect OIDs of the desired new EXCEPT list. */ + foreach_ptr(PublicationRelInfo, pri, rels) + newexceptrelids = lappend_oid(newexceptrelids, + RelationGetRelid(pri->relation)); + + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + /* + * Validate that each excluded table is not also in the explicit table + * list (which would be contradictory). + */ + foreach_ptr(PublicationRelInfo, pri, rels) + { + Oid relid = RelationGetRelid(pri->relation); + + if (list_member_oid(explicitrelids, relid)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" cannot appear in both the table list and the EXCEPT clause", + RelationGetQualifiedRelationName(pri->relation))); + } + + /* + * Get the current set of EXCEPT entries. Only FOR ALL TABLES and + * schema-level publications can have EXCEPT entries; for any other + * publication type oldexceptrelids stays NIL. + * + * Note: we check is_schema_publication() against the current catalog + * state (before AlterPublicationSchemas has run), so if the caller is + * doing SET TABLE t1 to convert a schema publication into a plain + * table publication, is_schema_publication() still returns true here. + * That is intentional: it lets us discover and clean up any stale + * EXCEPT entries that belong to the old schema definition. + */ + if (GetPublication(pubid)->alltables || is_schema_publication(pubid)) + oldexceptrelids = GetExcludedPublicationTables(pubid, + PUBLICATION_PART_ROOT); + + /* Build a list of old EXCEPT entries not present in the new list. */ + foreach_oid(oldrelid, oldexceptrelids) + { + if (!list_member_oid(newexceptrelids, oldrelid)) + delrelids = lappend_oid(delrelids, oldrelid); + } + + /* Drop old EXCEPT entries not present in the new list. */ + foreach_oid(relid, delrelids) + { + Oid proid; + ObjectAddress obj; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + /* Add new EXCEPT entries, skipping any already present. */ + PublicationAddTables(pubid, rels, true, stmt); + CloseTableList(rels); } } @@ -2372,6 +2442,7 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) foreach(lc, schemas) { Oid schemaid = lfirst_oid(lc); + List *except_relids; psid = GetSysCacheOid2(PUBLICATIONNAMESPACEMAP, Anum_pg_publication_namespace_oid, @@ -2388,8 +2459,40 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) get_namespace_name(schemaid)))); } + /* + * Collect EXCEPT entries for tables belonging to this schema before + * removing the schema entry. + */ + except_relids = GetExcludedPublicationTables(pubid, PUBLICATION_PART_ROOT); + ObjectAddressSet(obj, PublicationNamespaceRelationId, psid); performDeletion(&obj, DROP_CASCADE, 0); + + /* + * Drop any prexcept rows for tables belonging to this schema. These + * rows have no pg_depend entry pointing at the + * pg_publication_namespace row, so they are not cascaded by the + * performDeletion() call above and must be cleaned up explicitly. + */ + foreach_oid(relid, except_relids) + { + Oid proid; + + if (get_rel_namespace(relid) != schemaid) + continue; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + list_free(except_relids); } } diff --git a/src/backend/replication/pgoutput/pgoutput.c b/src/backend/replication/pgoutput/pgoutput.c index 7ee84ec1c83..9831be54b47 100644 --- a/src/backend/replication/pgoutput/pgoutput.c +++ b/src/backend/replication/pgoutput/pgoutput.c @@ -2229,7 +2229,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) */ if (pub->alltables) { - List *exceptpubids = NIL; + List *except_pubids = NIL; if (am_partition) { @@ -2252,7 +2252,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) * clause. Therefore, for a partition, exclusion must be * evaluated at the top-most ancestor. */ - exceptpubids = GetRelationExcludedPublications(last_ancestor_relid); + except_pubids = GetRelationExcludedPublications(last_ancestor_relid); } else { @@ -2260,13 +2260,13 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) * For a regular table or a root partitioned table, check * exclusion on table itself. */ - exceptpubids = GetRelationExcludedPublications(pub_relid); + except_pubids = GetRelationExcludedPublications(pub_relid); } - if (!list_member_oid(exceptpubids, pub->oid)) + if (!list_member_oid(except_pubids, pub->oid)) publish = true; - list_free(exceptpubids); + list_free(except_pubids); if (!publish) continue; diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index a290902d61e..e8bfb36cb1c 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2390,6 +2390,23 @@ match_previous_words(int pattern_id, } else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) COMPLETE_WITH(")"); + /* After a single schema name in SET context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 3c452139bf9..f7f394a35bf 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -594,6 +594,92 @@ Except tables: "pub_test.testpub_tbl_s1" "pub_test.testpub_tbl_s2" +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s2" + +-- fail: table in EXCEPT clause also appears in the explicit table list +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot appear in both the table list and the EXCEPT clause +-- error: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 1: ...xcept SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.tes... + ^ +-- SET: unqualified name in EXCEPT is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- SET without EXCEPT clears the existing except list +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + +-- SET to a different schema removes old schema's EXCEPT entries +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA public; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "public" + +-- fail: nonexistent table in EXCEPT clause (SET path) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- SET: multiple schemas each with their own EXCEPT clause +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- error: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +ERROR: EXCEPT clause is not supported with DROP in ALTER PUBLICATION +-- DROP TABLES IN SCHEMA removes associated EXCEPT entries +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "public" +Except tables: + "public.testpub_tbl1" + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 240190aa41f..3674437ed50 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -296,6 +296,44 @@ ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (tes ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); \dRp+ testpub_alter_except +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + +-- fail: table in EXCEPT clause also appears in the explicit table list +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- error: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- SET: unqualified name in EXCEPT is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +\dRp+ testpub_alter_except + +-- SET without EXCEPT clears the existing except list +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + +-- SET to a different schema removes old schema's EXCEPT entries +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA public; +\dRp+ testpub_alter_except + +-- fail: nonexistent table in EXCEPT clause (SET path) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- SET: multiple schemas each with their own EXCEPT clause +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_alter_except + +-- error: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); + +-- DROP TABLES IN SCHEMA removes associated EXCEPT entries +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 0ba6d6f8bb2..01eafb5b7c8 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -376,6 +376,61 @@ $result = is($result, qq(0), 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); +# SET: replace the except list; tab_excluded is now included and tab_published is excluded. +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_published)" +); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (7); + INSERT INTO sch1.tab_excluded VALUES (7); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded WHERE a = 7"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: newly included table is replicated' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published WHERE a = 7"); +is($result, qq(0), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: now-excluded table is not replicated' +); + +# SET without EXCEPT: clears the except list; both tables are now published. +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1"); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (8); + INSERT INTO sch1.tab_excluded VALUES (8); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published WHERE a = 8"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_published replicated after except list cleared' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded WHERE a = 8"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_excluded replicated after except list cleared' +); + $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); @@ -443,6 +498,36 @@ $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); +# OK when a table is excluded by a TABLES IN SCHEMA EXCEPT publication, +# but is included by another publication. +$node_publisher->safe_psql('postgres', 'TRUNCATE tab1'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE tab1'); + +$node_publisher->safe_psql( + 'postgres', qq( + CREATE PUBLICATION tap_pub1 FOR TABLES IN SCHEMA public EXCEPT (TABLE public.tab1); + CREATE PUBLICATION tap_pub2 FOR TABLE tab1; + INSERT INTO tab1 VALUES(1); +)); +$node_subscriber->psql('postgres', + "CREATE SUBSCRIPTION tap_sub CONNECTION '$publisher_connstr' PUBLICATION tap_pub1, tap_pub2" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'tap_sub'); + +$node_publisher->safe_psql('postgres', qq(INSERT INTO tab1 VALUES(2))); +$node_publisher->wait_for_catchup('tap_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT * FROM tab1 ORDER BY a"); +is( $result, qq(1 +2), + "TABLES IN SCHEMA EXCEPT: table excluded in schema pub but included by another pub is replicated" +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); + $node_publisher->stop('fast'); done_testing(); -- 2.50.1 (Apple Git-155)
^ permalink raw reply [nested|flat] 196+ messages in thread

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-06-15 21:45  Zsolt Parragi <zsolt.parragi@percona.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  2 siblings, 0 replies; 196+ messages in thread

From: Zsolt Parragi @ 2026-06-15 21:45 UTC (permalink / raw)
  To: pgsql-hackers@lists.postgresql.org

> In v13, I added a DEBUG2 message when a table is removed from the
> exclusion list due to a schema change.

Thanks, the DEBUG2 message (and the v13 patch) looks good to me and
this way it is consistent with the preexisting case. I have only a
question about test coverage - should the tests include verification
of the ALTER TABLE  ... SET SCHEMA behavior?





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-06-16 01:21  Peter Smith <smithpb2250@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  2 siblings, 1 reply; 196+ messages in thread

From: Peter Smith @ 2026-06-16 01:21 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Mon, Jun 15, 2026 at 9:31 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
>
> On Mon, Jun 15, 2026 at 11:50 AM Amit Kapila <amit.kapila16@gmail.com> wrote:
> >
> > On Thu, Jun 11, 2026 at 12:17 PM Peter Smith <smithpb2250@gmail.com> wrote:
> > >
> > > //////////
> > > v12-0002
> > >
> > > ======
> > > doc/src/sgml/ref/alter_publication.sgml
> > >
> > > 1.
> > > +     <para>
> > > +      For <literal>FOR TABLES IN SCHEMA</literal> publications, the
> > > +      <literal>EXCEPT</literal> clause is schema-scoped.  If a table listed in
> > > +      the <literal>EXCEPT</literal> clause is later moved to a different schema
> > > +      using <command>ALTER TABLE ... SET SCHEMA</command>, the exclusion is
> > > +      removed; the table will then be published if its new schema is part of a
> > > +      publication.  If the table is subsequently moved back to the original
> > > +      schema, the exclusion is not restored, and must be re-established
> > > +      explicitly using <command>ALTER PUBLICATION</command>.  Dropping a table
> > > +      always removes it from the <literal>EXCEPT</literal> clause,
> > > regardless of
> > > +      publication type.
> > > +     </para>
> > >
> > >
> > > I think the sentence "If the table is subsequently moved back..." is
> > > overkill, and does not need to be said. The prior info "the exclusion
> > > is removed" already tells me the exclusion is gone, and I think is
> > > reasonable to assume "removed" means that it is gone for good, with no
> > > ambiguity that it might magically come back.
> > >
> > > YMMV. Leave it as-is if you prefer.
> > >
> >
> > I feel it is okay to keep the proposed sentence to avoid any ambiguity
> > by the user to consider the schema-scope state is symmetric.
> >
>
> Okay, I have kept this para as-it-is.
>

This discussion about the impact of ALTER TABLE ... SET SCHEMA made me
wonder what happens for the existing PG19 case of FOR ALL TABLES
EXCEPT (TABLE ...)

It turns out to be quite different:

======

test_pub=# CREATE SCHEMA myschema;
CREATE SCHEMA
test_pub=# CREATE TABLE t1(A INT);
CREATE TABLE
test_pub=# CREATE TABLE t2(A INT);
CREATE TABLE
test_pub=# CREATE TABLE myschema.myt1(A INT);
CREATE TABLE
test_pub=# CREATE PUBLICATION pub1 FOR ALL TABLES EXCEPT (TABLE myschema.myt1);
CREATE PUBLICATION
test_pub=# \d myschema.myt1
               Table "myschema.myt1"
 Column |  Type   | Collation | Nullable | Default
--------+---------+-----------+----------+---------
 a      | integer |           |          |
Excluded from publications:
    "pub1"

test_pub=# \dRp+ pub1
                                                       Publication pub1
  Owner   | All tables | All sequences | Inserts | Updates | Deletes |
Truncates | Generated columns | Via root | Descri
ption
----------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+-------
------
 postgres | t          | f             | t       | t       | t       |
t         | none              | f        |
Except tables:
    "myschema.myt1"

test_pub=# ALTER TABLE myschema.myt1 SET SCHEMA public;
ALTER TABLE
test_pub=# \d myt1
                Table "public.myt1"
 Column |  Type   | Collation | Nullable | Default
--------+---------+-----------+----------+---------
 a      | integer |           |          |
Excluded from publications:
    "pub1"

test_pub=# \dRp+ pub1
                                                       Publication pub1
  Owner   | All tables | All sequences | Inserts | Updates | Deletes |
Truncates | Generated columns | Via root | Descri
ption
----------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+-------
------
 postgres | t          | f             | t       | t       | t       |
t         | none              | f        |
Except tables:
    "public.myt1"

======

This experiment shows that moving the table did *not* remove the exclusion.

It is kind of "explainable" in hindsight because the exclusion is by
table OID, not name, so it follows the table around when it is moved.
I don't think this is what a user would expect, given that they
explicitly asked to exclude it from a different schema.

Is it a PG19 exclusion bug?

Is it behaviour that needs more documenting?

~

IMO it seemed like a bug of the PG19 FOR ALL TABLES EXCEPT, because it
is the opposite of what the new FOR TABLES IN SCHEMA EXCEPT patch
does:
"If a table listed in the <literal>EXCEPT</literal> clause is later
moved to a different schema using  <command>ALTER TABLE ... SET
SCHEMA</command>, the exclusion is removed;"

Thoughts?

======
Kind Regards,
Peter Smith.
Fujitsu Australia.





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-06-16 04:35  Amit Kapila <amit.kapila16@gmail.com>
  parent: Peter Smith <smithpb2250@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: Amit Kapila @ 2026-06-16 04:35 UTC (permalink / raw)
  To: Peter Smith <smithpb2250@gmail.com>; +Cc: Nisha Moond <nisha.moond412@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Tue, Jun 16, 2026 at 6:52 AM Peter Smith <smithpb2250@gmail.com> wrote:
>
> This discussion about the impact of ALTER TABLE ... SET SCHEMA made me
> wonder what happens for the existing PG19 case of FOR ALL TABLES
> EXCEPT (TABLE ...)
>
> It turns out to be quite different:
>
> ======
>
> test_pub=# CREATE SCHEMA myschema;
> CREATE SCHEMA
> test_pub=# CREATE TABLE t1(A INT);
> CREATE TABLE
> test_pub=# CREATE TABLE t2(A INT);
> CREATE TABLE
> test_pub=# CREATE TABLE myschema.myt1(A INT);
> CREATE TABLE
> test_pub=# CREATE PUBLICATION pub1 FOR ALL TABLES EXCEPT (TABLE myschema.myt1);
> CREATE PUBLICATION
> test_pub=# \d myschema.myt1
>                Table "myschema.myt1"
>  Column |  Type   | Collation | Nullable | Default
> --------+---------+-----------+----------+---------
>  a      | integer |           |          |
> Excluded from publications:
>     "pub1"
>
> test_pub=# \dRp+ pub1
>                                                        Publication pub1
>   Owner   | All tables | All sequences | Inserts | Updates | Deletes |
> Truncates | Generated columns | Via root | Descri
> ption
> ----------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+-------
> ------
>  postgres | t          | f             | t       | t       | t       |
> t         | none              | f        |
> Except tables:
>     "myschema.myt1"
>
> test_pub=# ALTER TABLE myschema.myt1 SET SCHEMA public;
> ALTER TABLE
> test_pub=# \d myt1
>                 Table "public.myt1"
>  Column |  Type   | Collation | Nullable | Default
> --------+---------+-----------+----------+---------
>  a      | integer |           |          |
> Excluded from publications:
>     "pub1"
>
> test_pub=# \dRp+ pub1
>                                                        Publication pub1
>   Owner   | All tables | All sequences | Inserts | Updates | Deletes |
> Truncates | Generated columns | Via root | Descri
> ption
> ----------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+-------
> ------
>  postgres | t          | f             | t       | t       | t       |
> t         | none              | f        |
> Except tables:
>     "public.myt1"
>
> ======
>
> This experiment shows that moving the table did *not* remove the exclusion.
>
> It is kind of "explainable" in hindsight because the exclusion is by
> table OID, not name, so it follows the table around when it is moved.
> I don't think this is what a user would expect, given that they
> explicitly asked to exclude it from a different schema.
>
> Is it a PG19 exclusion bug?
>
> Is it behaviour that needs more documenting?
>
> ~
>
> IMO it seemed like a bug of the PG19 FOR ALL TABLES EXCEPT, because it
> is the opposite of what the new FOR TABLES IN SCHEMA EXCEPT patch
> does:
> "If a table listed in the <literal>EXCEPT</literal> clause is later
> moved to a different schema using  <command>ALTER TABLE ... SET
> SCHEMA</command>, the exclusion is removed;"
>

No, I don't think this is a bug for PG19 and the new behaviour for
PG20 is intentional and required because in this case, the EXCEPT
clause is schema-scoped, so once schema is changed, the table should
be removed from the exclusion list. OTOH, in PG19, the exclusion list
follows the table-level exclusion based on its OID as we can see in
the example provided by you. I think we can consider adding a line for
this in docs if you and others feel that such explicit mention can
avoid ambiguity around this. How about something like the following as
a separate para in EXCEPT clause description: Once a table is
excluded, the exclusion applies to that table itself, regardless of
its name or schema. Renaming the table or moving it to another schema
with <command>ALTER TABLE ... SET SCHEMA</command> does not cancel the
exclusion."

-- 
With Regards,
Amit Kapila.





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-06-16 06:36  Peter Smith <smithpb2250@gmail.com>
  parent: Amit Kapila <amit.kapila16@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: Peter Smith @ 2026-06-16 06:36 UTC (permalink / raw)
  To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: Nisha Moond <nisha.moond412@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Tue, Jun 16, 2026 at 2:36 PM Amit Kapila <amit.kapila16@gmail.com> wrote:
>
> On Tue, Jun 16, 2026 at 6:52 AM Peter Smith <smithpb2250@gmail.com> wrote:
> >
> > This discussion about the impact of ALTER TABLE ... SET SCHEMA made me
> > wonder what happens for the existing PG19 case of FOR ALL TABLES
> > EXCEPT (TABLE ...)
> >
> > It turns out to be quite different:
> >
> > ======
> >
> > test_pub=# CREATE SCHEMA myschema;
> > CREATE SCHEMA
> > test_pub=# CREATE TABLE t1(A INT);
> > CREATE TABLE
> > test_pub=# CREATE TABLE t2(A INT);
> > CREATE TABLE
> > test_pub=# CREATE TABLE myschema.myt1(A INT);
> > CREATE TABLE
> > test_pub=# CREATE PUBLICATION pub1 FOR ALL TABLES EXCEPT (TABLE myschema.myt1);
> > CREATE PUBLICATION
> > test_pub=# \d myschema.myt1
> >                Table "myschema.myt1"
> >  Column |  Type   | Collation | Nullable | Default
> > --------+---------+-----------+----------+---------
> >  a      | integer |           |          |
> > Excluded from publications:
> >     "pub1"
> >
> > test_pub=# \dRp+ pub1
> >                                                        Publication pub1
> >   Owner   | All tables | All sequences | Inserts | Updates | Deletes |
> > Truncates | Generated columns | Via root | Descri
> > ption
> > ----------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+-------
> > ------
> >  postgres | t          | f             | t       | t       | t       |
> > t         | none              | f        |
> > Except tables:
> >     "myschema.myt1"
> >
> > test_pub=# ALTER TABLE myschema.myt1 SET SCHEMA public;
> > ALTER TABLE
> > test_pub=# \d myt1
> >                 Table "public.myt1"
> >  Column |  Type   | Collation | Nullable | Default
> > --------+---------+-----------+----------+---------
> >  a      | integer |           |          |
> > Excluded from publications:
> >     "pub1"
> >
> > test_pub=# \dRp+ pub1
> >                                                        Publication pub1
> >   Owner   | All tables | All sequences | Inserts | Updates | Deletes |
> > Truncates | Generated columns | Via root | Descri
> > ption
> > ----------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+-------
> > ------
> >  postgres | t          | f             | t       | t       | t       |
> > t         | none              | f        |
> > Except tables:
> >     "public.myt1"
> >
> > ======
> >
> > This experiment shows that moving the table did *not* remove the exclusion.
> >
> > It is kind of "explainable" in hindsight because the exclusion is by
> > table OID, not name, so it follows the table around when it is moved.
> > I don't think this is what a user would expect, given that they
> > explicitly asked to exclude it from a different schema.
> >
> > Is it a PG19 exclusion bug?
> >
> > Is it behaviour that needs more documenting?
> >
> > ~
> >
> > IMO it seemed like a bug of the PG19 FOR ALL TABLES EXCEPT, because it
> > is the opposite of what the new FOR TABLES IN SCHEMA EXCEPT patch
> > does:
> > "If a table listed in the <literal>EXCEPT</literal> clause is later
> > moved to a different schema using  <command>ALTER TABLE ... SET
> > SCHEMA</command>, the exclusion is removed;"
> >
>
> No, I don't think this is a bug for PG19 and the new behaviour for
> PG20 is intentional and required because in this case, the EXCEPT
> clause is schema-scoped, so once schema is changed, the table should
> be removed from the exclusion list. OTOH, in PG19, the exclusion list
> follows the table-level exclusion based on its OID as we can see in
> the example provided by you. I think we can consider adding a line for
> this in docs if you and others feel that such explicit mention can
> avoid ambiguity around this. How about something like the following as
> a separate para in EXCEPT clause description: Once a table is
> excluded, the exclusion applies to that table itself, regardless of
> its name or schema. Renaming the table or moving it to another schema
> with <command>ALTER TABLE ... SET SCHEMA</command> does not cancel the
> exclusion."
>

OK. The explanatory text LGTM.

What's the next step? Should I create a new thread/patch to deal with this?

======
Kind Regards.
Peter Smith
Fujitsu Australia





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-06-16 08:23  Peter Smith <smithpb2250@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  2 siblings, 1 reply; 196+ messages in thread

From: Peter Smith @ 2026-06-16 08:23 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

Some review comments for v13-0001.

======
doc/src/sgml/ref/create_publication.sgml

1.
      <para>
       Marks the publication as one that replicates changes for all tables in
       the specified list of schemas, including tables created in the future.
+      Tables listed in the <literal>EXCEPT</literal> clause for a given schema
+      are excluded from the publication.
      </para>

Given Amit's suggestion [1] to modify the EXCEPT text for FOR ALL
TABLES, perhaps there also needs to be an equivalent note for ALL
TABLES IN SCHEMA. Maybe wait to see what happens [1], then you can use
similar wording.

======
src/backend/commands/publicationcmds.c

RemovePublicationExceptForRelation:

2.
+/*
+ * Remove any EXCEPT clause entries for a relation from schema publications.
+ * Called when a table changes schema (ALTER TABLE ... SET SCHEMA), so that
+ * a schema-scoped exclusion does not silently follow the table to its new
+ * schema.
+ */
+void
+RemovePublicationExceptForRelation(Oid relid, Oid oldNspOid, Oid newNspOid)
+{

There's nothing about that function name to indicate it is only for
SCHEMA publications.
There must be a better -- e.g. 'MaybeRemoveExclusionFromSchemaPub', or
whatever...

~~~

3.
+ ereport(DEBUG2,
+ errmsg_internal("auto-drop exclusion of table %s from publication
%s: table moved to schema %s",
+ quote_qualified_identifier(get_namespace_name(oldNspOid),
+    get_rel_name(relid)),
+ get_publication_name(pubid, false),
+ quote_identifier(get_namespace_name(newNspOid))));

Even though this is a debugging message, for consistency, we might as
well quote everything the same as normal messages do:

"auto-drop exclusion of table \"%s\" from publication \"%s\": table
moved to schema \"%s\""

======
[1] https://www.postgresql.org/message-id/CAA4eK1J_QP8CXCshaCy_01ALQQrDSzoTHfXKcAbjiEvV-RkOOw%40mail.gma...

Kind Regards,
Peter Smith.
Fujitsu Australia





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-06-16 10:44  Nisha Moond <nisha.moond412@gmail.com>
  parent: Peter Smith <smithpb2250@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: Nisha Moond @ 2026-06-16 10:44 UTC (permalink / raw)
  To: Peter Smith <smithpb2250@gmail.com>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Tue, Jun 16, 2026 at 1:53 PM Peter Smith <smithpb2250@gmail.com> wrote:
>
> Some review comments for v13-0001.
>
> ======
> doc/src/sgml/ref/create_publication.sgml
>
> 1.
>       <para>
>        Marks the publication as one that replicates changes for all tables in
>        the specified list of schemas, including tables created in the future.
> +      Tables listed in the <literal>EXCEPT</literal> clause for a given schema
> +      are excluded from the publication.
>       </para>
>
> Given Amit's suggestion [1] to modify the EXCEPT text for FOR ALL
> TABLES, perhaps there also needs to be an equivalent note for ALL
> TABLES IN SCHEMA. Maybe wait to see what happens [1], then you can use
> similar wording.
>

Okay, noted. Let's first wait for the conclusion on this.

> ======
> src/backend/commands/publicationcmds.c
>
> RemovePublicationExceptForRelation:
>
> 2.
> +/*
> + * Remove any EXCEPT clause entries for a relation from schema publications.
> + * Called when a table changes schema (ALTER TABLE ... SET SCHEMA), so that
> + * a schema-scoped exclusion does not silently follow the table to its new
> + * schema.
> + */
> +void
> +RemovePublicationExceptForRelation(Oid relid, Oid oldNspOid, Oid newNspOid)
> +{
>
> There's nothing about that function name to indicate it is only for
> SCHEMA publications.
> There must be a better -- e.g. 'MaybeRemoveExclusionFromSchemaPub', or
> whatever...
>

I've renamed it to RemoveSchemaPubExceptForRel to keep it consistent
with the neighboring function names. Let me know if it works.

> ~~~
>
> 3.
> + ereport(DEBUG2,
> + errmsg_internal("auto-drop exclusion of table %s from publication
> %s: table moved to schema %s",
> + quote_qualified_identifier(get_namespace_name(oldNspOid),
> +    get_rel_name(relid)),
> + get_publication_name(pubid, false),
> + quote_identifier(get_namespace_name(newNspOid))));
>
> Even though this is a debugging message, for consistency, we might as
> well quote everything the same as normal messages do:
>
> "auto-drop exclusion of table \"%s\" from publication \"%s\": table
> moved to schema \"%s\""
>

Fixed.
~~~

Also added a test as per Zsolt's suggestion at [1].
I moved all documentation changes into a separate 0004 patch to make
doc review easier.

Please find the attached v14 patches.

[1] https://www.postgresql.org/message-id/CAN4CZFPZnckA9-MPt6xj1QsRQTVKs3ZoKgdZ%2BQG1xa%3D%3DUD46Xw%40ma...

--
Thanks,
Nisha

Attachments: download all (4 files, .tar.gz)

v14-0001-Support-EXCEPT-clause-for-schema-level-publicati.patch (application/octet-stream, 60.4K) download From e382cd1553bebde2f2f95f6b33982eec4ad64e70 Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Tue, 16 Jun 2026 10:58:49 +0530 Subject: [PATCH v14 1/4] Support EXCEPT clause for schema-level publications Extend table exclusion support in publications to allow specific tables to be excluded from schema-level publications using an EXCEPT clause in CREATE PUBLICATION. Supported syntax: CREATE PUBLICATION <pub> FOR TABLES IN SCHEMA s EXCEPT (TABLE t1,...); --- src/backend/catalog/pg_publication.c | 161 ++++++++++++++---- src/backend/commands/publicationcmds.c | 146 +++++++++++++++-- src/backend/commands/tablecmds.c | 11 ++ src/backend/parser/gram.y | 54 ++++++- src/backend/replication/pgoutput/pgoutput.c | 30 +++- src/bin/psql/describe.c | 18 +++ src/bin/psql/tab-complete.in.c | 35 +++- src/include/catalog/pg_publication.h | 3 +- src/include/commands/publicationcmds.h | 2 + src/include/nodes/parsenodes.h | 2 + src/test/regress/expected/publication.out | 171 +++++++++++++++++++- src/test/regress/sql/publication.sql | 100 +++++++++++- src/test/subscription/t/037_except.pl | 133 ++++++++++++++- 13 files changed, 813 insertions(+), 53 deletions(-) diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index 5c457d9aca8..4089b505f89 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -444,13 +444,19 @@ GetPubPartitionOptionRelations(List *result, PublicationPartOpt pub_partopt, * * Note that the list of ancestors should be ordered such that the topmost * ancestor is at the end of the list. + * + * except_pubids is a list of publication OIDs whose schema membership + * should be ignored for the ancestor (because the ancestor is in their + * EXCEPT clause). */ Oid -GetTopMostAncestorInPublication(Oid puboid, List *ancestors, int *ancestor_level) +GetTopMostAncestorInPublication(Oid puboid, List *ancestors, + int *ancestor_level, List *except_pubids) { ListCell *lc; Oid topmost_relid = InvalidOid; int level = 0; + bool check_schemas = !list_member_oid(except_pubids, puboid); /* * Find the "topmost" ancestor that is in this publication. @@ -470,7 +476,7 @@ GetTopMostAncestorInPublication(Oid puboid, List *ancestors, int *ancestor_level if (ancestor_level) *ancestor_level = level; } - else + else if (check_schemas) { aschemaPubids = GetSchemaPublications(get_rel_namespace(ancestor)); if (list_member_oid(aschemaPubids, puboid)) @@ -545,18 +551,30 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, * duplicates, it's here just to provide nicer error message in common * case. The real protection is the unique key on the catalog. */ - if (SearchSysCacheExists2(PUBLICATIONRELMAP, ObjectIdGetDatum(relid), - ObjectIdGetDatum(pubid))) + tup = SearchSysCache2(PUBLICATIONRELMAP, ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + + if (HeapTupleIsValid(tup)) { + bool is_except = ((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept; + + ReleaseSysCache(tup); table_close(rel, RowExclusiveLock); if (if_not_exists) return InvalidObjectAddress; - ereport(ERROR, - (errcode(ERRCODE_DUPLICATE_OBJECT), - errmsg("relation \"%s\" is already member of publication \"%s\"", - RelationGetRelationName(targetrel), pub->name))); + if (is_except) + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("table \"%s\" cannot be added because it is excluded from publication \"%s\"", + RelationGetQualifiedRelationName(targetrel), + pub->name))); + else + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("relation \"%s\" is already member of publication \"%s\"", + RelationGetRelationName(targetrel), pub->name))); } check_publication_add_relation(pri); @@ -982,12 +1000,13 @@ GetIncludedPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) * Gets list of table oids that were specified in the EXCEPT clause for a * publication. * - * This should only be used FOR ALL TABLES publications. + * This is used for FOR ALL TABLES and FOR TABLES IN SCHEMA publications, + * both of which support EXCEPT TABLE. */ List * GetExcludedPublicationTables(Oid pubid, PublicationPartOpt pub_partopt) { - Assert(GetPublication(pubid)->alltables); + Assert(GetPublication(pubid)->alltables || is_schema_publication(pubid)); return get_publication_relations(pubid, pub_partopt, true); } @@ -1049,15 +1068,15 @@ GetAllPublicationRelations(Oid pubid, char relkind, bool pubviaroot) TableScanDesc scan; HeapTuple tuple; List *result = NIL; - List *exceptlist = NIL; + List *except_relids = NIL; Assert(!(relkind == RELKIND_SEQUENCE && pubviaroot)); /* EXCEPT filtering applies only to relations, not sequences */ if (relkind == RELKIND_RELATION) - exceptlist = GetExcludedPublicationTables(pubid, pubviaroot ? - PUBLICATION_PART_ROOT : - PUBLICATION_PART_LEAF); + except_relids = GetExcludedPublicationTables(pubid, pubviaroot ? + PUBLICATION_PART_ROOT : + PUBLICATION_PART_LEAF); classRel = table_open(RelationRelationId, AccessShareLock); @@ -1075,7 +1094,7 @@ GetAllPublicationRelations(Oid pubid, char relkind, bool pubviaroot) if (is_publishable_class(relid, relForm) && !(relForm->relispartition && pubviaroot) && - !list_member_oid(exceptlist, relid)) + !list_member_oid(except_relids, relid)) result = lappend_oid(result, relid); } @@ -1097,7 +1116,7 @@ GetAllPublicationRelations(Oid pubid, char relkind, bool pubviaroot) if (is_publishable_class(relid, relForm) && !relForm->relispartition && - !list_member_oid(exceptlist, relid)) + !list_member_oid(except_relids, relid)) result = lappend_oid(result, relid); } @@ -1232,22 +1251,67 @@ GetSchemaPublicationRelations(Oid schemaid, PublicationPartOpt pub_partopt) /* * Gets the list of all relations published by FOR TABLES IN SCHEMA - * publication. + * publication, excluding any tables listed in the EXCEPT clause. */ List * GetAllSchemaPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) { List *result = NIL; List *pubschemalist = GetPublicationSchemas(pubid); + List *except_relids = NIL; ListCell *cell; + /* get the list of tables excluded via EXCEPT TABLE for this publication */ + if (pubschemalist != NIL) + except_relids = GetExcludedPublicationTables(pubid, pub_partopt); + foreach(cell, pubschemalist) { Oid schemaid = lfirst_oid(cell); List *schemaRels = NIL; schemaRels = GetSchemaPublicationRelations(schemaid, pub_partopt); - result = list_concat(result, schemaRels); + + if (except_relids != NIL) + { + /* filter out any tables that appear in the EXCEPT list */ + ListCell *rlc; + + foreach(rlc, schemaRels) + { + Oid relid = lfirst_oid(rlc); + bool excluded = list_member_oid(except_relids, relid); + + /* + * Also exclude any relation whose partition ancestor is in + * the EXCEPT list. This matters when pub_partopt is + * PUBLICATION_PART_ROOT: the except list holds only the root + * OID, but the schema scan may also return individual + * partition relations that live in the same schema. + */ + if (!excluded && get_rel_relispartition(relid)) + { + List *ancestors = get_partition_ancestors(relid); + ListCell *alc; + + foreach(alc, ancestors) + { + if (list_member_oid(except_relids, lfirst_oid(alc))) + { + excluded = true; + break; + } + } + list_free(ancestors); + } + + if (!excluded) + result = lappend_oid(result, relid); + } + list_free(schemaRels); + } + else + result = list_concat(result, schemaRels); } return result; @@ -1324,6 +1388,7 @@ is_table_publishable_in_publication(Oid relid, Publication *pub) { bool relispartition; List *ancestors = NIL; + HeapTuple tup; /* * For non-pubviaroot publications, a partitioned table is never the @@ -1380,20 +1445,62 @@ is_table_publishable_in_publication(Oid relid, Publication *pub) * If it's false, the partition is covered by its ancestor's presence in * the publication, it should be included (return true). */ - if (relispartition && - OidIsValid(GetTopMostAncestorInPublication(pub->oid, ancestors, NULL))) - return !pub->pubviaroot; + if (relispartition) + { + Oid ancestor_oid; + + ancestor_oid = GetTopMostAncestorInPublication(pub->oid, ancestors, NULL, NIL); + if (OidIsValid(ancestor_oid)) + { + /* + * The ancestor was found in the publication (via explicit + * membership or schema membership), but it may be excluded. Check + * for a prexcept row before concluding the partition is + * published. + */ + tup = SearchSysCache2(PUBLICATIONRELMAP, + ObjectIdGetDatum(ancestor_oid), + ObjectIdGetDatum(pub->oid)); + if (HeapTupleIsValid(tup)) + { + bool is_except; + + is_except = ((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept; + ReleaseSysCache(tup); + if (is_except) + return false; + } + return !pub->pubviaroot; + } + } /* * Check whether the table is explicitly published via pg_publication_rel * or pg_publication_namespace. + * + * A pg_publication_rel row with prexcept=true means the table is + * explicitly excluded via EXCEPT and must not be reported as published, + * even if its schema is otherwise included. A row with prexcept=false + * means it is explicitly included. If no pg_publication_rel row exists, + * the table is published iff its schema appears in + * pg_publication_namespace. */ - return (SearchSysCacheExists2(PUBLICATIONRELMAP, - ObjectIdGetDatum(relid), - ObjectIdGetDatum(pub->oid)) || - SearchSysCacheExists2(PUBLICATIONNAMESPACEMAP, - ObjectIdGetDatum(get_rel_namespace(relid)), - ObjectIdGetDatum(pub->oid))); + + tup = SearchSysCache2(PUBLICATIONRELMAP, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pub->oid)); + if (HeapTupleIsValid(tup)) + { + bool is_except; + + is_except = ((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept; + ReleaseSysCache(tup); + return !is_except; + } + + return SearchSysCacheExists2(PUBLICATIONNAMESPACEMAP, + ObjectIdGetDatum(get_rel_namespace(relid)), + ObjectIdGetDatum(pub->oid)); } /* diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 440adb356ad..85d4b9deefe 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -181,7 +181,7 @@ parse_publication_options(ParseState *pstate, */ static void ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, - List **rels, List **exceptrels, List **schemas) + List **rels, List **except_pubtables, List **schemas) { ListCell *cell; PublicationObjSpec *pubobj; @@ -200,7 +200,7 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, { case PUBLICATIONOBJ_EXCEPT_TABLE: pubobj->pubtable->except = true; - *exceptrels = lappend(*exceptrels, pubobj->pubtable); + *except_pubtables = lappend(*except_pubtables, pubobj->pubtable); break; case PUBLICATIONOBJ_TABLE: pubobj->pubtable->except = false; @@ -224,6 +224,38 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, /* Filter out duplicates if user specifies "sch1, sch1" */ *schemas = list_append_unique_oid(*schemas, schemaid); + + /* + * Qualify unqualified EXCEPT table names with the resolved + * current schema and reject any explicitly cross-schema + * entries. This mirrors the parse-time handling done for + * TABLES_IN_SCHEMA in preprocess_pubobj_list(), deferred here + * because CURRENT_SCHEMA is not known until execution time. + */ + if (pubobj->except_tables != NIL) + { + char *cur_schema_name = get_namespace_name(schemaid); + + foreach_ptr(PublicationObjSpec, eobj, pubobj->except_tables) + { + const char *eobj_schemaname = + eobj->pubtable->relation->schemaname; + const char *eobj_relname = + eobj->pubtable->relation->relname; + + if (eobj_schemaname == NULL) + eobj->pubtable->relation->schemaname = cur_schema_name; + else if (strcmp(eobj_schemaname, cur_schema_name) != 0) + ereport(ERROR, + errcode(ERRCODE_INVALID_OBJECT_DEFINITION), + errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", + quote_qualified_identifier(eobj_schemaname, eobj_relname), + cur_schema_name)); + + *except_pubtables = lappend(*except_pubtables, + eobj->pubtable); + } + } break; default: /* shouldn't happen */ @@ -305,7 +337,7 @@ pub_rf_contains_invalid_column(Oid pubid, Relation relation, List *ancestors, if (pubviaroot && relation->rd_rel->relispartition) { publish_as_relid - = GetTopMostAncestorInPublication(pubid, ancestors, NULL); + = GetTopMostAncestorInPublication(pubid, ancestors, NULL, NIL); if (!OidIsValid(publish_as_relid)) publish_as_relid = relid; @@ -389,7 +421,7 @@ pub_contains_invalid_column(Oid pubid, Relation relation, List *ancestors, */ if (pubviaroot && relation->rd_rel->relispartition) { - publish_as_relid = GetTopMostAncestorInPublication(pubid, ancestors, NULL); + publish_as_relid = GetTopMostAncestorInPublication(pubid, ancestors, NULL, NIL); if (!OidIsValid(publish_as_relid)) publish_as_relid = relid; @@ -849,7 +881,7 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) char publish_generated_columns; AclResult aclresult; List *relations = NIL; - List *exceptrelations = NIL; + List *except_pubtables = NIL; List *schemaidlist = NIL; /* must have CREATE privilege on database */ @@ -936,16 +968,16 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) /* Associate objects with the publication. */ ObjectsInPublicationToOids(stmt->pubobjects, pstate, &relations, - &exceptrelations, &schemaidlist); + &except_pubtables, &schemaidlist); if (stmt->for_all_tables) { /* Process EXCEPT table list */ - if (exceptrelations != NIL) + if (except_pubtables != NIL) { List *rels; - rels = OpenTableList(exceptrelations); + rels = OpenTableList(except_pubtables); PublicationAddTables(puboid, rels, true, NULL); CloseTableList(rels); } @@ -959,6 +991,8 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) } else if (!stmt->for_all_sequences) { + List *explicitrelids = NIL; + /* FOR TABLES IN SCHEMA requires superuser */ if (schemaidlist != NIL && !superuser()) ereport(ERROR, @@ -977,6 +1011,19 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) schemaidlist != NIL, publish_via_partition_root); + /* + * Collect explicit table OIDs now, before we close the relation + * list, so that except-table validation below can check for + * contradictions without relying on a catalog scan that might not + * yet see the just-inserted rows. + */ + if (except_pubtables != NIL) + { + foreach_ptr(PublicationRelInfo, pri, rels) + explicitrelids = lappend_oid(explicitrelids, + RelationGetRelid(pri->relation)); + } + PublicationAddTables(puboid, rels, true, NULL); CloseTableList(rels); } @@ -989,6 +1036,34 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) */ LockSchemaList(schemaidlist); PublicationAddSchemas(puboid, schemaidlist, true, NULL); + + if (except_pubtables != NIL) + { + List *except_rels; + + except_rels = OpenTableList(except_pubtables); + + /* + * Validate that each excluded table is not also in the + * explicit table list (which would be contradictory). Use the + * in-memory explicitrelids collected above rather than + * re-reading the catalog, which may not yet see the + * just-inserted rows. + */ + foreach_ptr(PublicationRelInfo, pri, except_rels) + { + Oid except_relid = RelationGetRelid(pri->relation); + + if (list_member_oid(explicitrelids, except_relid)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" cannot appear in both the table list and the EXCEPT clause", + RelationGetQualifiedRelationName(pri->relation))); + } + + PublicationAddTables(puboid, except_rels, true, NULL); + CloseTableList(except_rels); + } } } @@ -1683,12 +1758,12 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) else { List *relations = NIL; - List *exceptrelations = NIL; + List *except_pubtables = NIL; List *schemaidlist = NIL; Oid pubid = pubform->oid; ObjectsInPublicationToOids(stmt->pubobjects, pstate, &relations, - &exceptrelations, &schemaidlist); + &except_pubtables, &schemaidlist); CheckAlterPublication(stmt, tup, relations, schemaidlist); @@ -1711,7 +1786,7 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) errmsg("publication \"%s\" does not exist", stmt->pubname)); - relations = list_concat(relations, exceptrelations); + relations = list_concat(relations, except_pubtables); AlterPublicationTables(stmt, tup, relations, pstate->p_sourcetext, schemaidlist != NIL); AlterPublicationSchemas(stmt, tup, schemaidlist); @@ -1829,6 +1904,55 @@ RemovePublicationSchemaById(Oid psoid) table_close(rel, RowExclusiveLock); } +/* + * Remove any EXCEPT clause entries for a relation from schema publications. + * Called when a table changes schema (ALTER TABLE ... SET SCHEMA), so that + * a schema-scoped exclusion does not silently follow the table to its new + * schema. + */ +void +RemoveSchemaPubExceptForRel(Oid relid, Oid oldNspOid, Oid newNspOid) +{ + List *pubids; + + pubids = GetRelationExcludedPublications(relid); + + foreach_oid(pubid, pubids) + { + Oid proid; + + /* + * This problem does not apply to FOR ALL TABLES publications, because + * their EXCEPT clause is publication-scoped, not schema-scoped: the + * exclusion should persist regardless of what schema the table is in. + */ + if (!is_schema_publication(pubid)) + continue; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddress obj; + + ObjectAddressSet(obj, PublicationRelRelationId, proid); + + ereport(DEBUG2, + errmsg_internal("auto-drop exclusion of table \"%s.%s\" from publication \"%s\": table moved to schema \"%s\"", + get_namespace_name(oldNspOid), + get_rel_name(relid), + get_publication_name(pubid, false), + get_namespace_name(newNspOid))); + + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + list_free(pubids); +} + /* * Open relations specified by a PublicationTable list. * The returned tables are locked in ShareUpdateExclusiveLock mode in order to diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..f8b7e6766d9 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -63,6 +63,7 @@ #include "commands/event_trigger.h" #include "commands/extension.h" #include "commands/repack.h" +#include "commands/publicationcmds.h" #include "commands/sequence.h" #include "commands/tablecmds.h" #include "commands/tablespace.h" @@ -19290,6 +19291,16 @@ AlterTableNamespaceInternal(Relation rel, Oid oldNspOid, Oid nspOid, AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid, false, objsMoved); + /* + * Remove any EXCEPT clause entries for this relation from schema + * publications. A schema-scoped exclusion is no longer meaningful once + * the table moves to a different schema. + */ + if (rel->rd_rel->relkind == RELKIND_RELATION || + rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE) + RemoveSchemaPubExceptForRel(RelationGetRelid(rel), oldNspOid, + nspOid); + table_close(classRel, RowExclusiveLock); } diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y index ff4e1388c55..6a7a1bc5f8d 100644 --- a/src/backend/parser/gram.y +++ b/src/backend/parser/gram.y @@ -58,6 +58,7 @@ #include "nodes/makefuncs.h" #include "nodes/nodeFuncs.h" #include "parser/parser.h" +#include "utils/builtins.h" #include "utils/datetime.h" #include "utils/xml.h" @@ -11272,7 +11273,7 @@ AlterOwnerStmt: ALTER AGGREGATE aggregate_with_argtypes OWNER TO RoleSpec * pub_obj is one of: * * TABLE table [, ...] - * TABLES IN SCHEMA schema [, ...] + * TABLES IN SCHEMA schema [EXCEPT (TABLE table [, ...] )] [, ...] * *****************************************************************************/ @@ -11332,23 +11333,26 @@ PublicationObjSpec: $$->pubtable->columns = $3; $$->pubtable->whereClause = $4; } - | TABLES IN_P SCHEMA ColId + | TABLES IN_P SCHEMA ColId opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_SCHEMA; $$->name = $4; + $$->except_tables = $5; $$->location = @4; } - | TABLES IN_P SCHEMA CURRENT_SCHEMA + | TABLES IN_P SCHEMA CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_CUR_SCHEMA; + $$->except_tables = $5; $$->location = @4; } - | ColId opt_column_list OptWhereClause + | ColId opt_column_list OptWhereClause opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $4; /* * If either a row filter or column list is specified, create * a PublicationTable object. @@ -11392,10 +11396,11 @@ PublicationObjSpec: $$->pubtable->columns = $2; $$->pubtable->whereClause = $3; } - | CURRENT_SCHEMA + | CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $2; $$->location = @1; } ; @@ -20784,6 +20789,8 @@ preprocess_pub_all_objtype_list(List *all_objects_list, List **pubobjects, /* * Process pubobjspec_list to check for errors in any of the objects and * convert PUBLICATIONOBJ_CONTINUATION into appropriate PublicationObjSpecType. + * Also flattens except_tables from TABLES IN SCHEMA nodes into the list so + * that ObjectsInPublicationToOids() sees them as top-level EXCEPT_TABLE entries. */ static void preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) @@ -20812,6 +20819,13 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLE) { + /* EXCEPT is not valid for table objects */ + if (pubobj->except_tables != NIL) + ereport(ERROR, + errcode(ERRCODE_SYNTAX_ERROR), + errmsg("EXCEPT is not allowed for TABLE publication objects"), + parser_errposition(pubobj->location)); + /* relation name or pubtable must be set for this type of object */ if (!pubobj->name && !pubobj->pubtable) ereport(ERROR, @@ -20860,6 +20874,36 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) errcode(ERRCODE_SYNTAX_ERROR), errmsg("invalid schema name"), parser_errposition(pubobj->location)); + + /* + * For TABLES_IN_SCHEMA, qualify unqualified EXCEPT table names + * with the parent schema and reject cross-schema entries at parse + * time, then flatten into the top-level list. + * + * For TABLES_IN_CUR_SCHEMA the schema name is not yet known, so + * skip both steps here; ObjectsInPublicationToOids() will + * qualify names and validate schema membership at execution time. + */ + if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLES_IN_SCHEMA) + { + foreach_ptr(PublicationObjSpec, eobj, pubobj->except_tables) + { + const char *eobj_schemaname = eobj->pubtable->relation->schemaname; + const char *eobj_relname = eobj->pubtable->relation->relname; + + if (eobj_schemaname == NULL) + eobj->pubtable->relation->schemaname = pubobj->name; + else if (strcmp(eobj_schemaname, pubobj->name) != 0) + ereport(ERROR, + errcode(ERRCODE_INVALID_OBJECT_DEFINITION), + errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", + quote_qualified_identifier(eobj_schemaname, eobj_relname), + pubobj->name), + parser_errposition(eobj->location)); + } + pubobjspec_list = list_concat(pubobjspec_list, pubobj->except_tables); + pubobj->except_tables = NIL; + } } prevobjtype = pubobj->pubobjtype; diff --git a/src/backend/replication/pgoutput/pgoutput.c b/src/backend/replication/pgoutput/pgoutput.c index 4ecfcbff7ab..7ee84ec1c83 100644 --- a/src/backend/replication/pgoutput/pgoutput.c +++ b/src/backend/replication/pgoutput/pgoutput.c @@ -2097,6 +2097,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) * are absorbed while decoding WAL. */ List *schemaPubids = GetSchemaPublications(schemaId); + List *except_pubids; ListCell *lc; Oid publish_as_relid = relid; int publish_ancestor_level = 0; @@ -2104,6 +2105,28 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) char relkind = get_rel_relkind(relid); List *rel_publications = NIL; + /* + * For the schema EXCEPT check, we must look up the top-most ancestor + * rather than the relation itself. check_publication_add_relation() + * prevents individual partitions from appearing in the EXCEPT clause, + * so only a root (non-partition) table can have prexcept = true. + * Using the partition's own OID would always return NIL and miss the + * exclusion. + */ + Oid root_relid; + + if (am_partition) + { + List *ancestors = get_partition_ancestors(relid); + + root_relid = llast_oid(ancestors); + list_free(ancestors); + } + else + root_relid = relid; + + except_pubids = GetRelationExcludedPublications(root_relid); + /* Reload publications if needed before use. */ if (!publications_valid) { @@ -2267,7 +2290,8 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) ancestor = GetTopMostAncestorInPublication(pub->oid, ancestors, - &level); + &level, + except_pubids); if (ancestor != InvalidOid) { @@ -2281,7 +2305,8 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) } if (list_member_oid(pubids, pub->oid) || - list_member_oid(schemaPubids, pub->oid) || + (list_member_oid(schemaPubids, pub->oid) && + !list_member_oid(except_pubids, pub->oid)) || ancestor_published) publish = true; } @@ -2360,6 +2385,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) list_free(pubids); list_free(schemaPubids); + list_free(except_pubids); list_free(rel_publications); entry->replicate_valid = true; diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c index af3935b0078..9470a0bbf5e 100644 --- a/src/bin/psql/describe.c +++ b/src/bin/psql/describe.c @@ -7038,6 +7038,24 @@ describePublications(const char *pattern) if (!addFooterToPublicationDesc(&buf, _("Tables from schemas:"), true, &cont)) goto error_return; + + if (pset.sversion >= 190000) + { + /* + * Get tables in the EXCEPT clause for this schema + * publication. + */ + printfPQExpBuffer(&buf, + "SELECT concat(c.relnamespace::regnamespace, '.', c.relname)\n" + "FROM pg_catalog.pg_class c\n" + " JOIN pg_catalog.pg_publication_rel pr ON c.oid = pr.prrelid\n" + "WHERE pr.prpubid = '%s'\n" + " AND pr.prexcept\n" + "ORDER BY 1", pubid); + if (!addFooterToPublicationDesc(&buf, _("Except tables:"), + true, &cont)) + goto error_return; + } } } else diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index de547a8cb37..53bb7c8679b 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -1065,6 +1065,24 @@ static const SchemaQuery Query_for_trigger_of_table = { "SELECT nspname FROM pg_catalog.pg_namespace "\ " WHERE nspname LIKE '%s'" +#define Query_for_list_of_tables_in_schema \ +"SELECT n.nspname || '.' || c.relname "\ +" FROM pg_catalog.pg_class c "\ +" JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "\ +" WHERE c.relkind IN (" CppAsString2(RELKIND_RELATION) ", " \ + CppAsString2(RELKIND_PARTITIONED_TABLE) ") "\ +" AND (n.nspname || '.' || c.relname) LIKE '%s' "\ +" AND n.nspname = '%s'" + +#define Query_for_list_of_tables_in_current_schema \ +"SELECT c.relname "\ +" FROM pg_catalog.pg_class c "\ +" JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "\ +" WHERE c.relkind IN (" CppAsString2(RELKIND_RELATION) ", " \ + CppAsString2(RELKIND_PARTITIONED_TABLE) ") "\ +" AND c.relname LIKE '%s' "\ +" AND n.nspname = pg_catalog.current_schema()" + /* Use COMPLETE_WITH_QUERY_VERBATIM with these queries for GUC names: */ #define Query_for_list_of_alter_system_set_vars \ "SELECT pg_catalog.lower(name) FROM pg_catalog.pg_settings "\ @@ -3787,8 +3805,21 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); - else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && (!ends_with(prev_wd, ','))) - COMPLETE_WITH("WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE", "WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* Complete "CREATE PUBLICATION <name> [...] WITH" */ else if (Matches("CREATE", "PUBLICATION", MatchAnyN, "WITH", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/include/catalog/pg_publication.h b/src/include/catalog/pg_publication.h index 89b4bb14f62..53e3d7c6f3d 100644 --- a/src/include/catalog/pg_publication.h +++ b/src/include/catalog/pg_publication.h @@ -191,7 +191,8 @@ extern List *GetPubPartitionOptionRelations(List *result, PublicationPartOpt pub_partopt, Oid relid); extern Oid GetTopMostAncestorInPublication(Oid puboid, List *ancestors, - int *ancestor_level); + int *ancestor_level, + List *except_pubids); extern bool is_publishable_relation(Relation rel); extern bool is_schema_publication(Oid pubid); diff --git a/src/include/commands/publicationcmds.h b/src/include/commands/publicationcmds.h index 4cf45c17cc5..fb1703aa675 100644 --- a/src/include/commands/publicationcmds.h +++ b/src/include/commands/publicationcmds.h @@ -27,6 +27,8 @@ extern void AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt); extern void RemovePublicationById(Oid pubid); extern void RemovePublicationRelById(Oid proid); extern void RemovePublicationSchemaById(Oid psoid); +extern void RemoveSchemaPubExceptForRel(Oid relid, Oid oldNspOid, + Oid newNspOid); extern ObjectAddress AlterPublicationOwner(const char *name, Oid newOwnerId); extern void AlterPublicationOwner_oid(Oid pubid, Oid newOwnerId); diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h index 4133c404a6b..1299b0a67a4 100644 --- a/src/include/nodes/parsenodes.h +++ b/src/include/nodes/parsenodes.h @@ -4488,6 +4488,8 @@ typedef struct PublicationObjSpec PublicationObjSpecType pubobjtype; /* type of this publication object */ char *name; PublicationTable *pubtable; + List *except_tables; /* tables specified in the EXCEPT clause (for + * TABLES IN SCHEMA) */ ParseLoc location; /* token location, or -1 if unknown */ } PublicationObjSpec; diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 29e54b214a0..2cf3fa40253 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -270,6 +270,12 @@ CREATE PUBLICATION testpub_foralltables_excepttable2 FOR ALL TABLES EXCEPT (test ERROR: syntax error at or near "testpub_tbl1" LINE 1: ..._foralltables_excepttable2 FOR ALL TABLES EXCEPT (testpub_tb... ^ +-- fail - EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testpub_tbl3); +ERROR: EXCEPT is not allowed for TABLE publication objects +LINE 2: FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testp... + ^ --------------------------------------------- -- SET ALL TABLES/SEQUENCES --------------------------------------------- @@ -470,7 +476,130 @@ HINT: Change the publication's EXCEPT clause using ALTER PUBLICATION ... SET AL RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Create same-named tables in public to verify unqualified EXCEPT entries +-- are qualified with the named schema, not public +CREATE TABLE testpub_nopk (foo int, bar int); +CREATE TABLE testpub_tbl_s1 (a int primary key, b text); +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + Publication testpub_schema_except1 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- Exclude multiple tables using unqualified names; same-named tables exist in +-- public to confirm unqualified names resolve to pub_test, not public +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + Publication testpub_schema_except2 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_nopk" + "pub_test.testpub_tbl_s1" + +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testp... + ^ +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); +ERROR: table "pub_test.testpub_tbl_s1" in EXCEPT clause does not belong to schema "public" +LINE 2: ...R TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.t... + ^ +-- Multiple schemas each with their own EXCEPT clause +CREATE PUBLICATION testpub_schema_except_multi + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_schema_except_multi + Publication testpub_schema_except_multi + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- ALTER TABLE ... SET SCHEMA on a table excluded by a schema publication: +-- the schema-scoped exclusion is no longer meaningful once the table moves +-- out of its schema, so the exclution is auto-dropped. +CREATE PUBLICATION testpub_schema_except_setsch + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_schema_except_setsch + Publication testpub_schema_except_setsch + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s2" + +ALTER TABLE pub_test.testpub_tbl_s2 SET SCHEMA public; +\dRp+ testpub_schema_except_setsch + Publication testpub_schema_except_setsch + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + +-- Restore so the existing cleanup below still works +ALTER TABLE public.testpub_tbl_s2 SET SCHEMA pub_test; +DROP PUBLICATION testpub_schema_except_setsch; +-- fail: table appears in both the explicit table list and the EXCEPT clause +CREATE PUBLICATION testpub_except_conflict + FOR TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot appear in both the table list and the EXCEPT clause +-- fail: nonexistent table in EXCEPT clause +CREATE PUBLICATION testpub_except_norel + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- fail: partition cannot appear in EXCEPT clause; only root tables are allowed +CREATE TABLE pub_test.testpub_parted_s (a int) PARTITION BY LIST (a); +CREATE TABLE pub_test.testpub_part_s PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (1); +CREATE PUBLICATION testpub_except_partition + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); +ERROR: cannot specify relation "pub_test.testpub_part_s" in the publication EXCEPT clause +DETAIL: This operation is not supported for individual partitions. +-- fail: TABLE keyword is required for the first entry in the EXCEPT clause +CREATE PUBLICATION testpub_except_nokw + FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +ERROR: syntax error at or near "testpub_nopk" +LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + ^ +-- Cleanup +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP TABLE pub_test.testpub_parted_s CASCADE; +DROP TABLE testpub_nopk, testpub_tbl_s1; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +--------------------------------------------- +-- Tests for publications with SEQUENCES +--------------------------------------------- CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; -- FOR ALL SEQUENCES @@ -1953,6 +2082,27 @@ ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b); ERROR: column specification not allowed for schema LINE 1: ...TION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b)... ^ +-- EXCEPT clause with CURRENT_SCHEMA: cross-schema entry must be rejected +SET search_path = pub_test1; +-- qualified name from wrong schema -> error +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.tbl1); +ERROR: table "pub_test2.tbl1" in EXCEPT clause does not belong to schema "pub_test1" +-- unqualified name implicitly qualified with current schema (pub_test1.tbl) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl); +RESET client_min_messages; +\dRp+ testpub_cursch_except + Publication testpub_cursch_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test1" +Except tables: + "pub_test1.tbl" + +DROP PUBLICATION testpub_cursch_except; +RESET search_path; -- cleanup pub_test1 schema for invalidation tests ALTER PUBLICATION testpub2_forschema DROP TABLES IN SCHEMA pub_test1; DROP PUBLICATION testpub3_forschema, testpub4_forschema, testpub5_forschema, testpub6_forschema, testpub_fortable; @@ -2304,6 +2454,7 @@ DROP ROLE regress_publication_user_dummy; -- Test pg_get_publication_tables(text[], oid) function CREATE SCHEMA gpt_test_sch; CREATE TABLE gpt_test_sch.tbl_sch (id int); +CREATE TABLE gpt_test_sch.tbl_sch2 (id int); CREATE TABLE tbl_normal (id int); CREATE TABLE tbl_parent (id1 int, id2 int, id3 int) PARTITION BY RANGE (id1); CREATE TABLE tbl_part1 PARTITION OF tbl_parent FOR VALUES FROM (1) TO (10); @@ -2314,6 +2465,7 @@ CREATE PUBLICATION pub_all_no_viaroot FOR ALL TABLES WITH (publish_via_partition CREATE PUBLICATION pub_all_except FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = true); CREATE PUBLICATION pub_all_except_no_viaroot FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_schema FOR TABLES IN SCHEMA gpt_test_sch; +CREATE PUBLICATION pub_schema_except FOR TABLES IN SCHEMA gpt_test_sch EXCEPT (TABLE gpt_test_sch.tbl_sch); CREATE PUBLICATION pub_normal FOR TABLE tbl_normal WHERE (id < 10); CREATE PUBLICATION pub_part_leaf FOR TABLE tbl_part1 WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_part_parent FOR TABLE tbl_parent (id1, id2) WHERE (id1 = 10) WITH (publish_via_partition_root = true); @@ -2465,6 +2617,18 @@ SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_part1'); -- no r ---------+---------+-------+------ (0 rows) +-- test for EXCEPT clause with schema publication +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch'); -- no result (excluded) + pubname | relname | attrs | qual +---------+---------+-------+------ +(0 rows) + +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch2'); -- one row (included via schema) + pubname | relname | attrs | qual +-------------------+----------+-------+------ + pub_schema_except | tbl_sch2 | 1 | +(1 row) + -- two rows with different row filter SELECT * FROM test_gpt(ARRAY['pub_all', 'pub_normal'], 'tbl_normal'); pubname | relname | attrs | qual @@ -2517,6 +2681,7 @@ DROP PUBLICATION pub_all_no_viaroot; DROP PUBLICATION pub_all_except; DROP PUBLICATION pub_all_except_no_viaroot; DROP PUBLICATION pub_schema; +DROP PUBLICATION pub_schema_except; DROP PUBLICATION pub_normal; DROP PUBLICATION pub_part_leaf; DROP PUBLICATION pub_part_parent; @@ -2525,7 +2690,9 @@ DROP PUBLICATION pub_part_parent_child; DROP VIEW gpt_test_view; DROP TABLE tbl_normal, tbl_parent, tbl_part1; DROP SCHEMA gpt_test_sch CASCADE; -NOTICE: drop cascades to table gpt_test_sch.tbl_sch +NOTICE: drop cascades to 2 other objects +DETAIL: drop cascades to table gpt_test_sch.tbl_sch +drop cascades to table gpt_test_sch.tbl_sch2 -- stage objects for pg_dump tests CREATE SCHEMA pubme CREATE TABLE t0 (c int, d int) CREATE TABLE t1 (c int); CREATE SCHEMA pubme2 CREATE TABLE t0 (c int, d int); diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 041e14a4de6..a96527adf94 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -123,6 +123,9 @@ CREATE PUBLICATION testpub_foralltables_excepttable1 FOR ALL TABLES EXCEPT (TABL \d testpub_tbl1 -- fail - first table in the EXCEPT list should use TABLE keyword CREATE PUBLICATION testpub_foralltables_excepttable2 FOR ALL TABLES EXCEPT (testpub_tbl1, testpub_tbl2); +-- fail - EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testpub_tbl3); --------------------------------------------- -- SET ALL TABLES/SEQUENCES @@ -220,7 +223,83 @@ RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Create same-named tables in public to verify unqualified EXCEPT entries +-- are qualified with the named schema, not public +CREATE TABLE testpub_nopk (foo int, bar int); +CREATE TABLE testpub_tbl_s1 (a int primary key, b text); + +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + +-- Exclude multiple tables using unqualified names; same-named tables exist in +-- public to confirm unqualified names resolve to pub_test, not public +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); + +-- Multiple schemas each with their own EXCEPT clause +CREATE PUBLICATION testpub_schema_except_multi + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_schema_except_multi + +-- ALTER TABLE ... SET SCHEMA on a table excluded by a schema publication: +-- the schema-scoped exclusion is no longer meaningful once the table moves +-- out of its schema, so the exclution is auto-dropped. +CREATE PUBLICATION testpub_schema_except_setsch + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_schema_except_setsch +ALTER TABLE pub_test.testpub_tbl_s2 SET SCHEMA public; +\dRp+ testpub_schema_except_setsch +-- Restore so the existing cleanup below still works +ALTER TABLE public.testpub_tbl_s2 SET SCHEMA pub_test; +DROP PUBLICATION testpub_schema_except_setsch; + +-- fail: table appears in both the explicit table list and the EXCEPT clause +CREATE PUBLICATION testpub_except_conflict + FOR TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: nonexistent table in EXCEPT clause +CREATE PUBLICATION testpub_except_norel + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- fail: partition cannot appear in EXCEPT clause; only root tables are allowed +CREATE TABLE pub_test.testpub_parted_s (a int) PARTITION BY LIST (a); +CREATE TABLE pub_test.testpub_part_s PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (1); +CREATE PUBLICATION testpub_except_partition + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); + +-- fail: TABLE keyword is required for the first entry in the EXCEPT clause +CREATE PUBLICATION testpub_except_nokw + FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + +-- Cleanup +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP TABLE pub_test.testpub_parted_s CASCADE; +DROP TABLE testpub_nopk, testpub_tbl_s1; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; + +--------------------------------------------- +-- Tests for publications with SEQUENCES +--------------------------------------------- CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; @@ -1189,6 +1268,18 @@ ALTER PUBLICATION testpub1_forschema SET TABLES IN SCHEMA pub_test1, pub_test1; ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo (a, b); ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b); +-- EXCEPT clause with CURRENT_SCHEMA: cross-schema entry must be rejected +SET search_path = pub_test1; +-- qualified name from wrong schema -> error +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.tbl1); +-- unqualified name implicitly qualified with current schema (pub_test1.tbl) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl); +RESET client_min_messages; +\dRp+ testpub_cursch_except +DROP PUBLICATION testpub_cursch_except; +RESET search_path; + -- cleanup pub_test1 schema for invalidation tests ALTER PUBLICATION testpub2_forschema DROP TABLES IN SCHEMA pub_test1; DROP PUBLICATION testpub3_forschema, testpub4_forschema, testpub5_forschema, testpub6_forschema, testpub_fortable; @@ -1443,6 +1534,7 @@ DROP ROLE regress_publication_user_dummy; -- Test pg_get_publication_tables(text[], oid) function CREATE SCHEMA gpt_test_sch; CREATE TABLE gpt_test_sch.tbl_sch (id int); +CREATE TABLE gpt_test_sch.tbl_sch2 (id int); CREATE TABLE tbl_normal (id int); CREATE TABLE tbl_parent (id1 int, id2 int, id3 int) PARTITION BY RANGE (id1); CREATE TABLE tbl_part1 PARTITION OF tbl_parent FOR VALUES FROM (1) TO (10); @@ -1454,6 +1546,7 @@ CREATE PUBLICATION pub_all_no_viaroot FOR ALL TABLES WITH (publish_via_partition CREATE PUBLICATION pub_all_except FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = true); CREATE PUBLICATION pub_all_except_no_viaroot FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_schema FOR TABLES IN SCHEMA gpt_test_sch; +CREATE PUBLICATION pub_schema_except FOR TABLES IN SCHEMA gpt_test_sch EXCEPT (TABLE gpt_test_sch.tbl_sch); CREATE PUBLICATION pub_normal FOR TABLE tbl_normal WHERE (id < 10); CREATE PUBLICATION pub_part_leaf FOR TABLE tbl_part1 WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_part_parent FOR TABLE tbl_parent (id1, id2) WHERE (id1 = 10) WITH (publish_via_partition_root = true); @@ -1510,6 +1603,10 @@ SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'gpt_test_sch.tbl_sch SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_parent'); -- no result (excluded) SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_part1'); -- no result +-- test for EXCEPT clause with schema publication +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch'); -- no result (excluded) +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch2'); -- one row (included via schema) + -- two rows with different row filter SELECT * FROM test_gpt(ARRAY['pub_all', 'pub_normal'], 'tbl_normal'); @@ -1538,6 +1635,7 @@ DROP PUBLICATION pub_all_no_viaroot; DROP PUBLICATION pub_all_except; DROP PUBLICATION pub_all_except_no_viaroot; DROP PUBLICATION pub_schema; +DROP PUBLICATION pub_schema_except; DROP PUBLICATION pub_normal; DROP PUBLICATION pub_part_leaf; DROP PUBLICATION pub_part_parent; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 8c58d282eee..18c7b2c1fca 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -24,14 +24,17 @@ my $result; sub test_except_root_partition { - my ($pubviaroot) = @_; + my ($pubviaroot, $pubsql) = @_; + $pubsql //= + "CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1)"; + $pubsql .= " WITH (publish_via_partition_root = $pubviaroot)"; # If the root partitioned table is in the EXCEPT clause, all its # partitions are excluded from publication, regardless of the # publish_via_partition_root setting. $node_publisher->safe_psql( 'postgres', qq( - CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1) WITH (publish_via_partition_root = $pubviaroot); + $pubsql; INSERT INTO root1 VALUES (1), (101); )); $node_subscriber->safe_psql('postgres', @@ -223,6 +226,131 @@ $node_subscriber->safe_psql( test_except_root_partition('false'); test_except_root_partition('true'); +# Same validation using TABLES IN SCHEMA instead of FOR ALL TABLES. +my $schema_pub = + "CREATE PUBLICATION tap_pub_part FOR TABLES IN SCHEMA public EXCEPT (TABLE public.root1)"; +test_except_root_partition('false', $schema_pub); +test_except_root_partition('true', $schema_pub); + +# ============================================ +# EXCEPT test cases for TABLES IN SCHEMA +# ============================================ + +# Create a dedicated schema with two tables: one to be published and one to be +# excluded. Also create inherited tables to verify ONLY semantics. +$node_publisher->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_published AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.tab_excluded AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.parent (a int); + CREATE TABLE sch1.child (b int) INHERITS (sch1.parent); +)); + +$node_subscriber->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_published (a int); + CREATE TABLE sch1.tab_excluded (a int); + CREATE TABLE sch1.parent (a int); + CREATE TABLE sch1.child (b int) INHERITS (sch1.parent); +)); + +# Basic test: initial sync respects EXCEPT. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_excluded)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: initial sync copies included table'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: initial sync skips excluded table'); + +# DML: only the included table should be replicated. +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (6); + INSERT INTO sch1.tab_excluded VALUES (6); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(6), + 'TABLES IN SCHEMA EXCEPT: DML on included table is replicated'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: DML on excluded table is not replicated'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Inherited tables: excluding the parent (without ONLY) also excludes the child. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.parent)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.child VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.child"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: excluding parent (without ONLY) also excludes child' +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Test that EXCEPT (TABLE ONLY parent) excludes only the parent itself, not its +# child. Truncate child first so rows from the previous test are not copied by +# the initial table sync of the next subscription. +$node_publisher->safe_psql('postgres', 'TRUNCATE sch1.child'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE sch1.child'); +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE ONLY sch1.parent)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.child VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.child"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: ONLY parent in EXCEPT does not exclude child'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Cleanup schema tables before the multi-publication section. +$node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); +$node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); + # ============================================ # Test when a subscription is subscribing to multiple publications # ============================================ @@ -254,6 +382,7 @@ $node_publisher->safe_psql( DROP PUBLICATION tap_pub2; TRUNCATE tab1; )); +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_subscriber->safe_psql('postgres', qq(TRUNCATE tab1)); # OK when a table is excluded by pub1 EXCEPT clause, but it is included by pub2 -- 2.50.1 (Apple Git-155)
v14-0002-Add-EXCEPT-support-to-ALTER-PUBLICATION-ADD-TABL.patch (application/octet-stream, 18.6K) download From 3f82331ea2bd59615293de39d84bb6f415a786ec Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Tue, 16 Jun 2026 11:00:26 +0530 Subject: [PATCH v14 2/4] Add EXCEPT support to ALTER PUBLICATION ADD TABLES IN SCHEMA Extend the EXCEPT clause support to allow tables to be excluded when adding a schema to a publication via ALTER PUBLICATION ... ADD. Syntax: ALTER PUBLICATION pub ADD TABLES IN SCHEMA s EXCEPT (TABLE s.t1); Since pg_dump uses ALTER PUBLICATION ... ADD, support for it is included in this patch. --- src/backend/catalog/pg_publication.c | 19 ++-- src/backend/commands/publicationcmds.c | 107 +++++++++++++++++++++- src/bin/pg_dump/pg_dump.c | 30 +++++- src/bin/pg_dump/t/002_pg_dump.pl | 24 +++++ src/bin/psql/tab-complete.in.c | 17 ++++ src/test/regress/expected/publication.out | 32 ++++++- src/test/regress/sql/publication.sql | 20 +++- src/test/subscription/t/037_except.pl | 32 +++++++ 8 files changed, 267 insertions(+), 14 deletions(-) diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index 4089b505f89..d1ff8839037 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -649,15 +649,18 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, * here, as CreatePublication() function invalidates all relations as part * of defining a FOR ALL TABLES publication. * - * For ALTER PUBLICATION, invalidation is needed only when adding an - * EXCEPT table to a publication already marked as ALL TABLES. For - * publications that were originally empty or defined as ALL SEQUENCES and - * are being converted to ALL TABLES, invalidation is skipped here, as - * AlterPublicationAllFlags() function invalidates all relations while - * marking the publication as ALL TABLES publication. + * For ALTER PUBLICATION, invalidation is needed when adding an EXCEPT + * table to either a FOR ALL TABLES publication (pub->alltables is true) + * or a FOR TABLES IN SCHEMA publication (is_schema_publication is true). + * The exception: when a publication is being converted to FOR ALL TABLES + * (pub->alltables is still false at this point), + * AlterPublicationAllFlags() will perform a full invalidation, so we skip + * it here. */ - inval_except_table = (alter_stmt != NULL) && pub->alltables && - (alter_stmt->for_all_tables && pri->except); + inval_except_table = (alter_stmt != NULL) && pri->except && + (pub->alltables + ? alter_stmt->for_all_tables + : is_schema_publication(pubid)); if (!pri->except || inval_except_table) { diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 85d4b9deefe..34faac57228 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -70,6 +70,13 @@ static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok); static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); +static void AlterPublicationSchemas(AlterPublicationStmt *stmt, + HeapTuple tup, List *schemaidlist, + List *except_pubtables); +static void AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, + List *except_pubtables, + List *schemaidlist); static char defGetGeneratedColsOption(DefElem *def); @@ -1500,7 +1507,8 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, */ static void AlterPublicationSchemas(AlterPublicationStmt *stmt, - HeapTuple tup, List *schemaidlist) + HeapTuple tup, List *schemaidlist, + List *except_pubtables) { Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); @@ -1577,6 +1585,97 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, */ PublicationAddSchemas(pubform->oid, schemaidlist, true, stmt); } + + /* + * Increment the command counter so that is_schema_publication() in + * GetExcludedPublicationTables() can see the just-inserted schema + * rows when AlterPublicationSchemaExceptTables runs next. + */ + if (stmt->action == AP_AddObjects || stmt->action == AP_SetObjects) + CommandCounterIncrement(); + + AlterPublicationSchemaExceptTables(stmt, tup, except_pubtables, schemaidlist); +} + +/* + * Alter the EXCEPT list of a schema-level publication. + * + * Adds, removes, or replaces except-table entries in pg_publication_rel + * (rows with prexcept = true). These entries suppress publication of the + * named tables that would otherwise be covered by a FOR TABLES IN SCHEMA + * clause. + */ +static void +AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, List *except_pubtables, + List *schemaidlist) +{ + Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); + Oid pubid = pubform->oid; + + /* + * Nothing to do if no EXCEPT entries. + */ + if (!except_pubtables) + return; + + /* + * This function handles EXCEPT entries for schema-level publications + * only. For FOR ALL TABLES publications, EXCEPT entries are already + * processed by AlterPublicationTables(). + */ + if (schemaidlist == NIL && !is_schema_publication(pubid)) + return; + + /* + * Dropping a schema from a publication removes all its EXCEPT entries via + * cascade. The concept of "drop all schema tables from the publication + * EXCEPT these ones" is not supported. + */ + if (stmt->action == AP_DropObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); + + /* + * XXX EXCEPT with SET is not currently implemented. Workaround: DROP and + * re-ADD the schema with the desired EXCEPT list. + */ + if (stmt->action == AP_SetObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"), + errhint("Drop and re-add the schema with the desired EXCEPT list."))); + + if (stmt->action == AP_AddObjects) + { + List *rels; + List *explicitrelids; + + rels = OpenTableList(except_pubtables); + + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + /* + * Validate that each excluded table is not also in the explicit table + * list (which would be contradictory). + */ + foreach_ptr(PublicationRelInfo, pri, rels) + { + Oid relid = RelationGetRelid(pri->relation); + + if (list_member_oid(explicitrelids, relid)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" cannot appear in both the table list and the EXCEPT clause", + RelationGetQualifiedRelationName(pri->relation))); + } + + PublicationAddTables(pubid, rels, false, stmt); + + CloseTableList(rels); + } } /* @@ -1786,10 +1885,12 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) errmsg("publication \"%s\" does not exist", stmt->pubname)); - relations = list_concat(relations, except_pubtables); + if (stmt->for_all_tables) + relations = list_concat(relations, except_pubtables); + AlterPublicationTables(stmt, tup, relations, pstate->p_sourcetext, schemaidlist != NIL); - AlterPublicationSchemas(stmt, tup, schemaidlist); + AlterPublicationSchemas(stmt, tup, schemaidlist, except_pubtables); AlterPublicationAllFlags(stmt, rel, tup); } diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c index a0f7f8e2168..85ab3b00875 100644 --- a/src/bin/pg_dump/pg_dump.c +++ b/src/bin/pg_dump/pg_dump.c @@ -5019,6 +5019,7 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) PublicationInfo *pubinfo = pubsinfo->publication; PQExpBuffer query; char *tag; + bool has_except = false; /* Do nothing if not dumping schema */ if (!dopt->dumpSchema) @@ -5029,7 +5030,34 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) query = createPQExpBuffer(); appendPQExpBuffer(query, "ALTER PUBLICATION %s ", fmtId(pubinfo->dobj.name)); - appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s;\n", fmtId(schemainfo->dobj.name)); + appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s", fmtId(schemainfo->dobj.name)); + + /* + * Append EXCEPT clause for any tables that belong to this schema + * and are excluded from the publication. + */ + for (SimplePtrListCell *cell = pubinfo->except_tables.head; cell; cell = cell->next) + { + TableInfo *tbinfo = (TableInfo *) cell->ptr; + + if (strcmp(tbinfo->dobj.namespace->dobj.name, schemainfo->dobj.name) == 0) + { + if (!has_except) + { + appendPQExpBufferStr(query, " EXCEPT ("); + has_except = true; + } + else + appendPQExpBufferStr(query, ", "); + + appendPQExpBuffer(query, "TABLE ONLY %s", fmtId(tbinfo->dobj.name)); + } + } + + if (has_except) + appendPQExpBufferStr(query, ")"); + + appendPQExpBufferStr(query, ";\n"); /* * There is no point in creating drop query as the drop is done by schema diff --git a/src/bin/pg_dump/t/002_pg_dump.pl b/src/bin/pg_dump/t/002_pg_dump.pl index 9258948b583..d18b3b0d7b9 100644 --- a/src/bin/pg_dump/t/002_pg_dump.pl +++ b/src/bin/pg_dump/t/002_pg_dump.pl @@ -3283,6 +3283,30 @@ my %tests = ( like => { %full_runs, section_post_data => 1, }, }, + 'CREATE PUBLICATION pub11' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub11 FOR TABLES IN SCHEMA dump_test EXCEPT (TABLE test_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub11 WITH (publish = 'insert, update, delete, truncate');\E + .*? + \QALTER PUBLICATION pub11 ADD TABLES IN SCHEMA dump_test EXCEPT (TABLE ONLY test_table);\E + /xms, + like => { %full_runs, section_post_data => 1, }, + }, + + 'CREATE PUBLICATION pub12' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub12 FOR TABLES IN SCHEMA dump_test EXCEPT (TABLE test_table, dump_test.test_second_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub12 WITH (publish = 'insert, update, delete, truncate');\E + .*? + \QALTER PUBLICATION pub12 ADD TABLES IN SCHEMA dump_test EXCEPT (TABLE ONLY test_table, TABLE ONLY test_second_table);\E + /xms, + like => { %full_runs, section_post_data => 1, }, + }, + 'CREATE SUBSCRIPTION sub1' => { create_order => 50, create_sql => 'CREATE SUBSCRIPTION sub1 diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index 53bb7c8679b..a290902d61e 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2373,6 +2373,23 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); + /* After a single schema name in ADD context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 2cf3fa40253..7394d60b5f5 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -591,12 +591,42 @@ CREATE PUBLICATION testpub_except_nokw ERROR: syntax error at or near "testpub_nopk" LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); ^ +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; +-- fail: non-existing table in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- fail: EXCEPT table belongs to a different schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 1: ...xcept ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.tes... + ^ +-- fail: TABLE keyword is required for the first entry in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +ERROR: syntax error at or near "testpub_nopk" +LINE 1: ...lter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_no... + ^ +-- ADD: qualified and unqualified names; unqualified is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + "pub_test.testpub_tbl_s2" + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP TABLE pub_test.testpub_parted_s CASCADE; DROP TABLE testpub_nopk, testpub_tbl_s1; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi, testpub_alter_except; --------------------------------------------- -- Tests for publications with SEQUENCES --------------------------------------------- diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index a96527adf94..e497d342abd 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -290,12 +290,30 @@ CREATE PUBLICATION testpub_except_partition CREATE PUBLICATION testpub_except_nokw FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; + +-- fail: non-existing table in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- fail: EXCEPT table belongs to a different schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- fail: TABLE keyword is required for the first entry in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + +-- ADD: qualified and unqualified names; unqualified is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); +\dRp+ testpub_alter_except + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP TABLE pub_test.testpub_parted_s CASCADE; DROP TABLE testpub_nopk, testpub_tbl_s1; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi, testpub_alter_except; --------------------------------------------- -- Tests for publications with SEQUENCES diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 18c7b2c1fca..0ba6d6f8bb2 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -347,6 +347,38 @@ is($result, qq(5), $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); +# ============================================ +# ALTER PUBLICATION EXCEPT for TABLES IN SCHEMA +# ============================================ + +# Truncate subscriber tables to remove data accumulated from previous tests. +$node_subscriber->safe_psql('postgres', + 'TRUNCATE sch1.tab_published, sch1.tab_excluded, sch1.parent, sch1.child'); + +# ADD: add a schema with an excepted table; verify the except entry takes effect. +$node_publisher->safe_psql('postgres', "CREATE PUBLICATION sch_pub"); +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub ADD TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_excluded)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(6), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: included table synced'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + # Cleanup schema tables before the multi-publication section. $node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); $node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); -- 2.50.1 (Apple Git-155)
v14-0003-Add-EXCEPT-support-to-ALTER-PUBLICATION-SET-TABL.patch (application/octet-stream, 23.2K) download From f4b6d1e37c86cb2cd51b2e2c5731764a64e05a8b Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Tue, 16 Jun 2026 11:01:39 +0530 Subject: [PATCH v14 3/4] Add EXCEPT support to ALTER PUBLICATION SET TABLES IN SCHEMA Extend AlterPublicationExceptTables() with the AP_SetObjects case, which redefines the publication and replaces the entire EXCEPT list. Syntax: ALTER PUBLICATION pub SET TABLES IN SCHEMA s EXCEPT (TABLE t1); This patch also cleans up EXCEPT entries when a schema is dropped from the publication. --- src/backend/commands/publicationcmds.c | 135 +++++++++++++++++--- src/backend/replication/pgoutput/pgoutput.c | 10 +- src/bin/psql/tab-complete.in.c | 17 +++ src/test/regress/expected/publication.out | 86 +++++++++++++ src/test/regress/sql/publication.sql | 38 ++++++ src/test/subscription/t/037_except.pl | 85 ++++++++++++ 6 files changed, 350 insertions(+), 21 deletions(-) diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 34faac57228..6c7f150cd73 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -1588,8 +1588,8 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, /* * Increment the command counter so that is_schema_publication() in - * GetExcludedPublicationTables() can see the just-inserted schema - * rows when AlterPublicationSchemaExceptTables runs next. + * GetExcludedPublicationTables() can see the just-inserted schema rows + * when AlterPublicationSchemaExceptTables runs next. */ if (stmt->action == AP_AddObjects || stmt->action == AP_SetObjects) CommandCounterIncrement(); @@ -1607,16 +1607,18 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, */ static void AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, - HeapTuple tup, List *except_pubtables, - List *schemaidlist) + HeapTuple tup, List *except_pubtables, + List *schemaidlist) { Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); Oid pubid = pubform->oid; /* - * Nothing to do if no EXCEPT entries. + * Nothing to do if there are no EXCEPT entries, unless handling the SET + * command, because if the user has removed all exceptions we need to drop + * any existing ones. */ - if (!except_pubtables) + if (!except_pubtables && stmt->action != AP_SetObjects) return; /* @@ -1637,16 +1639,6 @@ AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); - /* - * XXX EXCEPT with SET is not currently implemented. Workaround: DROP and - * re-ADD the schema with the desired EXCEPT list. - */ - if (stmt->action == AP_SetObjects) - ereport(ERROR, - (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"), - errhint("Drop and re-add the schema with the desired EXCEPT list."))); - if (stmt->action == AP_AddObjects) { List *rels; @@ -1674,6 +1666,84 @@ AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, PublicationAddTables(pubid, rels, false, stmt); + CloseTableList(rels); + } + else /* AP_SetObjects */ + { + List *oldexceptrelids = NIL; + List *newexceptrelids = NIL; + List *delrelids = NIL; + List *rels; + List *explicitrelids; + + rels = OpenTableList(except_pubtables); + + /* Collect OIDs of the desired new EXCEPT list. */ + foreach_ptr(PublicationRelInfo, pri, rels) + newexceptrelids = lappend_oid(newexceptrelids, + RelationGetRelid(pri->relation)); + + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + /* + * Validate that each excluded table is not also in the explicit table + * list (which would be contradictory). + */ + foreach_ptr(PublicationRelInfo, pri, rels) + { + Oid relid = RelationGetRelid(pri->relation); + + if (list_member_oid(explicitrelids, relid)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" cannot appear in both the table list and the EXCEPT clause", + RelationGetQualifiedRelationName(pri->relation))); + } + + /* + * Get the current set of EXCEPT entries. Only FOR ALL TABLES and + * schema-level publications can have EXCEPT entries; for any other + * publication type oldexceptrelids stays NIL. + * + * Note: we check is_schema_publication() against the current catalog + * state (before AlterPublicationSchemas has run), so if the caller is + * doing SET TABLE t1 to convert a schema publication into a plain + * table publication, is_schema_publication() still returns true here. + * That is intentional: it lets us discover and clean up any stale + * EXCEPT entries that belong to the old schema definition. + */ + if (GetPublication(pubid)->alltables || is_schema_publication(pubid)) + oldexceptrelids = GetExcludedPublicationTables(pubid, + PUBLICATION_PART_ROOT); + + /* Build a list of old EXCEPT entries not present in the new list. */ + foreach_oid(oldrelid, oldexceptrelids) + { + if (!list_member_oid(newexceptrelids, oldrelid)) + delrelids = lappend_oid(delrelids, oldrelid); + } + + /* Drop old EXCEPT entries not present in the new list. */ + foreach_oid(relid, delrelids) + { + Oid proid; + ObjectAddress obj; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + /* Add new EXCEPT entries, skipping any already present. */ + PublicationAddTables(pubid, rels, true, stmt); + CloseTableList(rels); } } @@ -2372,6 +2442,7 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) foreach(lc, schemas) { Oid schemaid = lfirst_oid(lc); + List *except_relids; psid = GetSysCacheOid2(PUBLICATIONNAMESPACEMAP, Anum_pg_publication_namespace_oid, @@ -2388,8 +2459,40 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) get_namespace_name(schemaid)))); } + /* + * Collect EXCEPT entries for tables belonging to this schema before + * removing the schema entry. + */ + except_relids = GetExcludedPublicationTables(pubid, PUBLICATION_PART_ROOT); + ObjectAddressSet(obj, PublicationNamespaceRelationId, psid); performDeletion(&obj, DROP_CASCADE, 0); + + /* + * Drop any prexcept rows for tables belonging to this schema. These + * rows have no pg_depend entry pointing at the + * pg_publication_namespace row, so they are not cascaded by the + * performDeletion() call above and must be cleaned up explicitly. + */ + foreach_oid(relid, except_relids) + { + Oid proid; + + if (get_rel_namespace(relid) != schemaid) + continue; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + list_free(except_relids); } } diff --git a/src/backend/replication/pgoutput/pgoutput.c b/src/backend/replication/pgoutput/pgoutput.c index 7ee84ec1c83..9831be54b47 100644 --- a/src/backend/replication/pgoutput/pgoutput.c +++ b/src/backend/replication/pgoutput/pgoutput.c @@ -2229,7 +2229,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) */ if (pub->alltables) { - List *exceptpubids = NIL; + List *except_pubids = NIL; if (am_partition) { @@ -2252,7 +2252,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) * clause. Therefore, for a partition, exclusion must be * evaluated at the top-most ancestor. */ - exceptpubids = GetRelationExcludedPublications(last_ancestor_relid); + except_pubids = GetRelationExcludedPublications(last_ancestor_relid); } else { @@ -2260,13 +2260,13 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) * For a regular table or a root partitioned table, check * exclusion on table itself. */ - exceptpubids = GetRelationExcludedPublications(pub_relid); + except_pubids = GetRelationExcludedPublications(pub_relid); } - if (!list_member_oid(exceptpubids, pub->oid)) + if (!list_member_oid(except_pubids, pub->oid)) publish = true; - list_free(exceptpubids); + list_free(except_pubids); if (!publish) continue; diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index a290902d61e..e8bfb36cb1c 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2390,6 +2390,23 @@ match_previous_words(int pattern_id, } else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) COMPLETE_WITH(")"); + /* After a single schema name in SET context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 7394d60b5f5..0ea5b58284b 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -621,6 +621,92 @@ Except tables: "pub_test.testpub_tbl_s1" "pub_test.testpub_tbl_s2" +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s2" + +-- fail: table in EXCEPT clause also appears in the explicit table list +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot appear in both the table list and the EXCEPT clause +-- error: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 1: ...xcept SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.tes... + ^ +-- SET: unqualified name in EXCEPT is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- SET without EXCEPT clears the existing except list +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + +-- SET to a different schema removes old schema's EXCEPT entries +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA public; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "public" + +-- fail: nonexistent table in EXCEPT clause (SET path) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- SET: multiple schemas each with their own EXCEPT clause +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- error: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +ERROR: EXCEPT clause is not supported with DROP in ALTER PUBLICATION +-- DROP TABLES IN SCHEMA removes associated EXCEPT entries +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "public" +Except tables: + "public.testpub_tbl1" + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index e497d342abd..27c8d6f981d 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -308,6 +308,44 @@ ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (tes ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); \dRp+ testpub_alter_except +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + +-- fail: table in EXCEPT clause also appears in the explicit table list +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- error: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- SET: unqualified name in EXCEPT is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +\dRp+ testpub_alter_except + +-- SET without EXCEPT clears the existing except list +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + +-- SET to a different schema removes old schema's EXCEPT entries +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA public; +\dRp+ testpub_alter_except + +-- fail: nonexistent table in EXCEPT clause (SET path) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- SET: multiple schemas each with their own EXCEPT clause +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_alter_except + +-- error: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); + +-- DROP TABLES IN SCHEMA removes associated EXCEPT entries +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 0ba6d6f8bb2..01eafb5b7c8 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -376,6 +376,61 @@ $result = is($result, qq(0), 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); +# SET: replace the except list; tab_excluded is now included and tab_published is excluded. +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_published)" +); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (7); + INSERT INTO sch1.tab_excluded VALUES (7); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded WHERE a = 7"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: newly included table is replicated' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published WHERE a = 7"); +is($result, qq(0), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: now-excluded table is not replicated' +); + +# SET without EXCEPT: clears the except list; both tables are now published. +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1"); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (8); + INSERT INTO sch1.tab_excluded VALUES (8); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published WHERE a = 8"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_published replicated after except list cleared' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded WHERE a = 8"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_excluded replicated after except list cleared' +); + $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); @@ -443,6 +498,36 @@ $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); +# OK when a table is excluded by a TABLES IN SCHEMA EXCEPT publication, +# but is included by another publication. +$node_publisher->safe_psql('postgres', 'TRUNCATE tab1'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE tab1'); + +$node_publisher->safe_psql( + 'postgres', qq( + CREATE PUBLICATION tap_pub1 FOR TABLES IN SCHEMA public EXCEPT (TABLE public.tab1); + CREATE PUBLICATION tap_pub2 FOR TABLE tab1; + INSERT INTO tab1 VALUES(1); +)); +$node_subscriber->psql('postgres', + "CREATE SUBSCRIPTION tap_sub CONNECTION '$publisher_connstr' PUBLICATION tap_pub1, tap_pub2" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'tap_sub'); + +$node_publisher->safe_psql('postgres', qq(INSERT INTO tab1 VALUES(2))); +$node_publisher->wait_for_catchup('tap_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT * FROM tab1 ORDER BY a"); +is( $result, qq(1 +2), + "TABLES IN SCHEMA EXCEPT: table excluded in schema pub but included by another pub is replicated" +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); + $node_publisher->stop('fast'); done_testing(); -- 2.50.1 (Apple Git-155)
v14-0004-Documentation-Patch.patch (application/octet-stream, 10.6K) download From 91754fd3c4d5b0771d9140f5956901b0d5b1a406 Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Tue, 16 Jun 2026 11:12:02 +0530 Subject: [PATCH v14 4/4] Documentation Patch --- doc/src/sgml/logical-replication.sgml | 3 +- doc/src/sgml/ref/alter_publication.sgml | 69 +++++++++++++++++++++++- doc/src/sgml/ref/create_publication.sgml | 24 +++++++-- 3 files changed, 90 insertions(+), 6 deletions(-) diff --git a/doc/src/sgml/logical-replication.sgml b/doc/src/sgml/logical-replication.sgml index 9e7868487de..1433d2660fe 100644 --- a/doc/src/sgml/logical-replication.sgml +++ b/doc/src/sgml/logical-replication.sgml @@ -117,7 +117,8 @@ or <literal>FOR ALL SEQUENCES</literal>. Unlike tables, sequences can be synchronized at any time. For more information, see <xref linkend="logical-replication-sequences"/>. When a publication is - created with <literal>FOR ALL TABLES</literal>, a table or set of tables can + created with <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal>, a table or set of tables can be explicitly excluded from publication using the <link linkend="sql-createpublication-params-for-except-table"><literal>EXCEPT</literal></link> clause. diff --git a/doc/src/sgml/ref/alter_publication.sgml b/doc/src/sgml/ref/alter_publication.sgml index 52114a16a39..152d3279935 100644 --- a/doc/src/sgml/ref/alter_publication.sgml +++ b/doc/src/sgml/ref/alter_publication.sgml @@ -31,7 +31,7 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA <replaceable class="parameter">tables_in_schema</replaceable> [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -47,6 +47,10 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <replaceable class="parameter">table_object</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] [ WHERE ( <replaceable class="parameter">expression</replaceable> ) ] +<phrase>and <replaceable class="parameter">tables_in_schema</replaceable> is:</phrase> + + { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] + <phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> TABLE <replaceable class="parameter">table_object</replaceable> [, ... ] @@ -93,7 +97,11 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r used with a publication defined with <literal>FOR TABLE</literal> or <literal>FOR TABLES IN SCHEMA</literal>, replaces the list of tables/schemas in the publication with the specified list; the existing tables or schemas - that were present in the publication will be removed. + that were present in the publication will be removed. When + <literal>SET TABLES IN SCHEMA</literal> is used with an + <literal>EXCEPT</literal> clause, the excluded tables for each schema are + replaced with the specified list; if <literal>EXCEPT</literal> is omitted + for a schema, any existing exclusions for that schema are cleared. </para> <para> @@ -110,6 +118,12 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <literal>ADD TABLE</literal>. </para> + <para> + The <literal>EXCEPT</literal> clause can be used with + <literal>ADD TABLES IN SCHEMA</literal> to exclude specific tables from a + schema-level publication. + </para> + <para> The fourth variant of this command listed in the synopsis can change all of the publication properties specified in @@ -198,6 +212,35 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r </listitem> </varlistentry> + <varlistentry> + <term><literal>EXCEPT</literal></term> + <listitem> + <para> + When used with <literal>ADD TABLES IN SCHEMA</literal> + or <literal>SET TABLES IN SCHEMA</literal>, specifies + tables to be excluded from the publication. Each named + table must belong to the schema specified in the same + <literal>TABLES IN SCHEMA</literal> clause. Table names may be + schema-qualified or unqualified; unqualified names are implicitly + qualified with the schema named in the same clause. See + <xref linkend="sql-createpublication"/> for further details on the + semantics of <literal>EXCEPT</literal>. + </para> + <para> + For <literal>FOR TABLES IN SCHEMA</literal> publications, the + <literal>EXCEPT</literal> clause is schema-scoped. If a table listed in + the <literal>EXCEPT</literal> clause is later moved to a different schema + using <command>ALTER TABLE ... SET SCHEMA</command>, the exclusion is + removed; the table will then be published if its new schema is part of a + publication. If the table is subsequently moved back to the original + schema, the exclusion is not restored, and must be re-established + explicitly using <command>ALTER PUBLICATION</command>. Dropping a table + always removes it from the <literal>EXCEPT</literal> clause, regardless of + publication type. + </para> + </listitem> + </varlistentry> + <varlistentry> <term><literal>SET ( <replaceable class="parameter">publication_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] )</literal></term> <listitem> @@ -288,6 +331,28 @@ ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA marketing, sales; </programlisting> </para> + <para> + Add schema <structname>sales</structname> to the publication + <structname>sales_publication</structname>, excluding the + <structname>sales.internal</structname> and + <structname>sales.drafts</structname> tables: +<programlisting> +ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA sales EXCEPT (TABLE internal, drafts); +</programlisting> + </para> + + <para> + Replace the schema list of <structname>sales_publication</structname> with + <structname>sales</structname>, excluding only + <structname>sales.drafts</structname>. Other than + <structname>sales.drafts</structname>, any previously excluded tables for schema + <structname>sales</structname> are no longer excluded. Any schemas previously in + <structname>sales_publication</structname> are removed: +<programlisting> +ALTER PUBLICATION sales_publication SET TABLES IN SCHEMA sales EXCEPT (TABLE drafts); +</programlisting> + </para> + <para> Add tables <structname>users</structname>, <structname>departments</structname> and schema diff --git a/doc/src/sgml/ref/create_publication.sgml b/doc/src/sgml/ref/create_publication.sgml index f82d640e6ca..1017396f476 100644 --- a/doc/src/sgml/ref/create_publication.sgml +++ b/doc/src/sgml/ref/create_publication.sgml @@ -28,7 +28,7 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA <replaceable class="parameter">tables_in_schema</replaceable> [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -39,6 +39,10 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <replaceable class="parameter">table_object</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] [ WHERE ( <replaceable class="parameter">expression</replaceable> ) ] +<phrase>and <replaceable class="parameter">tables_in_schema</replaceable> is:</phrase> + + { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] + <phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> TABLE <replaceable class="parameter">table_object</replaceable> [, ... ] @@ -142,6 +146,8 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <para> Marks the publication as one that replicates changes for all tables in the specified list of schemas, including tables created in the future. + Tables listed in the <literal>EXCEPT</literal> clause for a given schema + are excluded from the publication. </para> <para> @@ -173,7 +179,7 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <para> Marks the publication as one that replicates changes for all tables in the database, including tables created in the future. Tables listed in - <literal>EXCEPT</literal> clause are excluded from the publication. + the <literal>EXCEPT</literal> clause are excluded from the publication. </para> </listitem> </varlistentry> @@ -198,7 +204,10 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <listitem> <para> This clause specifies a list of tables to be excluded from the - publication. + publication. It can be used with <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal>. For <literal>FOR TABLES IN + SCHEMA</literal>, the exclusion applies only to tables in the schema + associated with the <literal>EXCEPT</literal>. </para> <para> For inherited tables, if <literal>ONLY</literal> is specified before the @@ -515,6 +524,15 @@ CREATE PUBLICATION production_publication FOR TABLE users, departments, TABLES I CREATE PUBLICATION sales_publication FOR TABLES IN SCHEMA marketing, sales; </programlisting></para> + <para> + Create a publication that publishes all changes for all the tables present in + the schema <structname>sales</structname>, except + <structname>internal</structname> and <structname>drafts</structname>: +<programlisting> +CREATE PUBLICATION sales_filtered FOR TABLES IN SCHEMA sales EXCEPT (TABLE internal, drafts); +</programlisting> + </para> + <para> Create a publication that publishes all changes for table <structname>users</structname>, but replicates only columns <structname>user_id</structname> and -- 2.50.1 (Apple Git-155)
^ permalink raw reply [nested|flat] 196+ messages in thread

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-06-16 11:08  Amit Kapila <amit.kapila16@gmail.com>
  parent: Peter Smith <smithpb2250@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: Amit Kapila @ 2026-06-16 11:08 UTC (permalink / raw)
  To: Peter Smith <smithpb2250@gmail.com>; +Cc: Nisha Moond <nisha.moond412@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Tue, Jun 16, 2026 at 12:06 PM Peter Smith <smithpb2250@gmail.com> wrote:
>
> On Tue, Jun 16, 2026 at 2:36 PM Amit Kapila <amit.kapila16@gmail.com> wrote:
> >
> > No, I don't think this is a bug for PG19 and the new behaviour for
> > PG20 is intentional and required because in this case, the EXCEPT
> > clause is schema-scoped, so once schema is changed, the table should
> > be removed from the exclusion list. OTOH, in PG19, the exclusion list
> > follows the table-level exclusion based on its OID as we can see in
> > the example provided by you. I think we can consider adding a line for
> > this in docs if you and others feel that such explicit mention can
> > avoid ambiguity around this. How about something like the following as
> > a separate para in EXCEPT clause description: Once a table is
> > excluded, the exclusion applies to that table itself, regardless of
> > its name or schema. Renaming the table or moving it to another schema
> > with <command>ALTER TABLE ... SET SCHEMA</command> does not cancel the
> > exclusion."
> >
>
> OK. The explanatory text LGTM.
>
> What's the next step? Should I create a new thread/patch to deal with this?
>

WFM.

-- 
With Regards,
Amit Kapila.





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-06-17 01:53  Peter Smith <smithpb2250@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: Peter Smith @ 2026-06-17 01:53 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

Hi Nisha.

Some review comments for v14-0001.

======
src/test/regress/sql/publication.sql

1.
+-- ALTER TABLE ... SET SCHEMA on a table excluded by a schema publication:
+-- the schema-scoped exclusion is no longer meaningful once the table moves
+-- out of its schema, so the exclution is auto-dropped.

1a.
typo: /exclution/exclusion/

~

1b.
Exclusions cannot be "dropped" (at least, not by a user with the DROP
command). So even though this is correct for what is happening
internally, maybe from the user PoV it is better to say something like
"auto-removed" or just "removed".

(Same comment may also apply to the DEBUG logging when this happened).

~~~

2.
+-- Restore so the existing cleanup below still works
+ALTER TABLE public.testpub_tbl_s2 SET SCHEMA pub_test;
+DROP PUBLICATION testpub_schema_except_setsch;

Why not just fix the cleanup code? It's not "existing cleanup" anyway
-- it's part of this same patch.

////////////////////

Some review comments for v14-0004.

======

doc/src/sgml/ref/alter_publication.sgml:

1.
    used with a publication defined with <literal>FOR TABLE</literal> or
    <literal>FOR TABLES IN SCHEMA</literal>, replaces the list of tables/schemas
    in the publication with the specified list; the existing tables or schemas
-   that were present in the publication will be removed.
+   that were present in the publication will be removed.  When
+   <literal>SET TABLES IN SCHEMA</literal> is used with an
+   <literal>EXCEPT</literal> clause, the excluded tables for each schema are
+   replaced with the specified list; if <literal>EXCEPT</literal> is omitted
+   for a schema, any existing exclusions for that schema are cleared.

"are cleared" or "are removed"... not sure what is better. Maybe
"cleared" is fine.

~~~

2.
+  <para>
+   The <literal>EXCEPT</literal> clause can be used with
+   <literal>ADD TABLES IN SCHEMA</literal> to exclude specific tables from a
+   schema-level publication.
+  </para>
+

This is talking about the 'ADD' variant. So really, it belongs as part
of that 2nd para: "The first two variants modify..." because that is
where ADD is discussed.

~~~

3.
+   <varlistentry>
+    <term><literal>EXCEPT</literal></term>
+    <listitem>
+     <para>
+      When used with <literal>ADD TABLES IN SCHEMA</literal>
+      or <literal>SET TABLES IN SCHEMA</literal>, specifies
+      tables to be excluded from the publication.  Each named
+      table must belong to the schema specified in the same
+      <literal>TABLES IN SCHEMA</literal> clause.  Table names may be
+      schema-qualified or unqualified; unqualified names are implicitly
+      qualified with the schema named in the same clause.  See
+      <xref linkend="sql-createpublication"/> for further details on the
+      semantics of <literal>EXCEPT</literal>.
+     </para>
+     <para>
+      For <literal>FOR TABLES IN SCHEMA</literal> publications, the
+      <literal>EXCEPT</literal> clause is schema-scoped.  If a table listed in
+      the <literal>EXCEPT</literal> clause is later moved to a different schema
+      using <command>ALTER TABLE ... SET SCHEMA</command>, the exclusion is
+      removed; the table will then be published if its new schema is part of a
+      publication.  If the table is subsequently moved back to the original
+      schema, the exclusion is not restored, and must be re-established
+      explicitly using <command>ALTER PUBLICATION</command>.  Dropping a table
+      always removes it from the <literal>EXCEPT</literal> clause,
regardless of
+      publication type.
+     </para>
+    </listitem>
+   </varlistentry>

3a.
TBH, I lost track of what the final decision was about keeping this EXCEPT part.
IIUC, you wanted to defer a decision until later, but I did not
understand the plan:
a) Should the EXCEPT part be present for now, but consider removing it later?
b) Should the EXCEPT part be absent for now, but consider adding it later?

I prefer what you have done, but either way, we need to ensure Shlok's
thread uses the same approach.

~

3b.
I think that last "Dropping a table..." sentence should be a separate
<para>, unrelated to renaming/moving tables. Also, you don't need to
say "regardless of publication type" -- that would be the assumption
unless you say otherwise.

======
Kind Regards,
Peter Smith.
Fujitsu Australia





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-06-17 03:38  Peter Smith <smithpb2250@gmail.com>
  parent: Amit Kapila <amit.kapila16@gmail.com>
  0 siblings, 0 replies; 196+ messages in thread

From: Peter Smith @ 2026-06-17 03:38 UTC (permalink / raw)
  To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: Nisha Moond <nisha.moond412@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Tue, Jun 16, 2026 at 9:08 PM Amit Kapila <amit.kapila16@gmail.com> wrote:
>
> On Tue, Jun 16, 2026 at 12:06 PM Peter Smith <smithpb2250@gmail.com> wrote:
> >
> > On Tue, Jun 16, 2026 at 2:36 PM Amit Kapila <amit.kapila16@gmail.com> wrote:
> > >
> > > No, I don't think this is a bug for PG19 and the new behaviour for
> > > PG20 is intentional and required because in this case, the EXCEPT
> > > clause is schema-scoped, so once schema is changed, the table should
> > > be removed from the exclusion list. OTOH, in PG19, the exclusion list
> > > follows the table-level exclusion based on its OID as we can see in
> > > the example provided by you. I think we can consider adding a line for
> > > this in docs if you and others feel that such explicit mention can
> > > avoid ambiguity around this. How about something like the following as
> > > a separate para in EXCEPT clause description: Once a table is
> > > excluded, the exclusion applies to that table itself, regardless of
> > > its name or schema. Renaming the table or moving it to another schema
> > > with <command>ALTER TABLE ... SET SCHEMA</command> does not cancel the
> > > exclusion."
> > >
> >
> > OK. The explanatory text LGTM.
> >
> > What's the next step? Should I create a new thread/patch to deal with this?
> >
>
> WFM.
>

Done. See new thread/patch [1].

======
[1] https://www.postgresql.org/message-id/flat/CAHut%2BPvQ5BqnawCQd6r1tqqd%2BiAJC-CuRY8wscuXSrpHGUzofA%4...

Kind Regards,
Peter Smith.
Fujitsu Australia





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-06-18 06:35  Nisha Moond <nisha.moond412@gmail.com>
  parent: Peter Smith <smithpb2250@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: Nisha Moond @ 2026-06-18 06:35 UTC (permalink / raw)
  To: Peter Smith <smithpb2250@gmail.com>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Wed, Jun 17, 2026 at 7:24 AM Peter Smith <smithpb2250@gmail.com> wrote:
>
> Hi Nisha.
>
> Some review comments for v14-0001.
>
> ======
> src/test/regress/sql/publication.sql
>
> 1.
> +-- ALTER TABLE ... SET SCHEMA on a table excluded by a schema publication:
> +-- the schema-scoped exclusion is no longer meaningful once the table moves
> +-- out of its schema, so the exclution is auto-dropped.
>
> 1a.
> typo: /exclution/exclusion/
>
> ~
>
> 1b.
> Exclusions cannot be "dropped" (at least, not by a user with the DROP
> command). So even though this is correct for what is happening
> internally, maybe from the user PoV it is better to say something like
> "auto-removed" or just "removed".
>
> (Same comment may also apply to the DEBUG logging when this happened).
>
> ~~~
>
> 2.
> +-- Restore so the existing cleanup below still works
> +ALTER TABLE public.testpub_tbl_s2 SET SCHEMA pub_test;
> +DROP PUBLICATION testpub_schema_except_setsch;
>
> Why not just fix the cleanup code? It's not "existing cleanup" anyway
> -- it's part of this same patch.
>

I restored it here because patches 002 and 003 add tests that depend
on pub_test.testpub_tbl_s2.
I agree the earlier comments were confusing and made it look like it
was only for cleanup purposes. I've reworded the comments, but kept
the restore so the ALTER PUBLICATION tests can be added smoothly.

> ////////////////////
>
> Some review comments for v14-0004.
>
> ======
>
> doc/src/sgml/ref/alter_publication.sgml:
>
> 1.
>     used with a publication defined with <literal>FOR TABLE</literal> or
>     <literal>FOR TABLES IN SCHEMA</literal>, replaces the list of tables/schemas
>     in the publication with the specified list; the existing tables or schemas
> -   that were present in the publication will be removed.
> +   that were present in the publication will be removed.  When
> +   <literal>SET TABLES IN SCHEMA</literal> is used with an
> +   <literal>EXCEPT</literal> clause, the excluded tables for each schema are
> +   replaced with the specified list; if <literal>EXCEPT</literal> is omitted
> +   for a schema, any existing exclusions for that schema are cleared.
>
> "are cleared" or "are removed"... not sure what is better. Maybe
> "cleared" is fine.
>

okay, retained "cleared".

> ~~~
>
> 2.
> +  <para>
> +   The <literal>EXCEPT</literal> clause can be used with
> +   <literal>ADD TABLES IN SCHEMA</literal> to exclude specific tables from a
> +   schema-level publication.
> +  </para>
> +
>
> This is talking about the 'ADD' variant. So really, it belongs as part
> of that 2nd para: "The first two variants modify..." because that is
> where ADD is discussed.
>

Done.

> ~~~
>
> 3.
> +   <varlistentry>
> +    <term><literal>EXCEPT</literal></term>
> +    <listitem>
> +     <para>
> +      When used with <literal>ADD TABLES IN SCHEMA</literal>
> +      or <literal>SET TABLES IN SCHEMA</literal>, specifies
> +      tables to be excluded from the publication.  Each named
> +      table must belong to the schema specified in the same
> +      <literal>TABLES IN SCHEMA</literal> clause.  Table names may be
> +      schema-qualified or unqualified; unqualified names are implicitly
> +      qualified with the schema named in the same clause.  See
> +      <xref linkend="sql-createpublication"/> for further details on the
> +      semantics of <literal>EXCEPT</literal>.
> +     </para>
> +     <para>
> +      For <literal>FOR TABLES IN SCHEMA</literal> publications, the
> +      <literal>EXCEPT</literal> clause is schema-scoped.  If a table listed in
> +      the <literal>EXCEPT</literal> clause is later moved to a different schema
> +      using <command>ALTER TABLE ... SET SCHEMA</command>, the exclusion is
> +      removed; the table will then be published if its new schema is part of a
> +      publication.  If the table is subsequently moved back to the original
> +      schema, the exclusion is not restored, and must be re-established
> +      explicitly using <command>ALTER PUBLICATION</command>.  Dropping a table
> +      always removes it from the <literal>EXCEPT</literal> clause,
> regardless of
> +      publication type.
> +     </para>
> +    </listitem>
> +   </varlistentry>
>
> 3a.
> TBH, I lost track of what the final decision was about keeping this EXCEPT part.
> IIUC, you wanted to defer a decision until later, but I did not
> understand the plan:
> a) Should the EXCEPT part be present for now, but consider removing it later?
> b) Should the EXCEPT part be absent for now, but consider adding it later?
>
> I prefer what you have done, but either way, we need to ensure Shlok's
> thread uses the same approach.
>

I chose (a), keeping EXCEPT part for now so others can provide
feedback and help us reach a consensus on how the documentation should
be updated.

> ~
>
> 3b.
> I think that last "Dropping a table..." sentence should be a separate
> <para>, unrelated to renaming/moving tables. Also, you don't need to
> say "regardless of publication type" -- that would be the assumption
> unless you say otherwise.
>

Fixed.
---

Attached are the updated patches v15.

--
Thanks,
Nisha

Attachments: download all (4 files, .tar.gz)

v15-0001-Support-EXCEPT-clause-for-schema-level-publicati.patch (application/octet-stream, 60.3K) download From 737c15cd12dc38c07968865727ac1af8f66bd5df Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Tue, 16 Jun 2026 10:58:49 +0530 Subject: [PATCH v15 1/4] Support EXCEPT clause for schema-level publications Extend table exclusion support in publications to allow specific tables to be excluded from schema-level publications using an EXCEPT clause in CREATE PUBLICATION. Supported syntax: CREATE PUBLICATION <pub> FOR TABLES IN SCHEMA s EXCEPT (TABLE t1,...); --- src/backend/catalog/pg_publication.c | 161 ++++++++++++++---- src/backend/commands/publicationcmds.c | 146 +++++++++++++++-- src/backend/commands/tablecmds.c | 11 ++ src/backend/parser/gram.y | 54 ++++++- src/backend/replication/pgoutput/pgoutput.c | 30 +++- src/bin/psql/describe.c | 18 +++ src/bin/psql/tab-complete.in.c | 35 +++- src/include/catalog/pg_publication.h | 3 +- src/include/commands/publicationcmds.h | 2 + src/include/nodes/parsenodes.h | 2 + src/test/regress/expected/publication.out | 171 +++++++++++++++++++- src/test/regress/sql/publication.sql | 100 +++++++++++- src/test/subscription/t/037_except.pl | 133 ++++++++++++++- 13 files changed, 813 insertions(+), 53 deletions(-) diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index 5c457d9aca8..4089b505f89 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -444,13 +444,19 @@ GetPubPartitionOptionRelations(List *result, PublicationPartOpt pub_partopt, * * Note that the list of ancestors should be ordered such that the topmost * ancestor is at the end of the list. + * + * except_pubids is a list of publication OIDs whose schema membership + * should be ignored for the ancestor (because the ancestor is in their + * EXCEPT clause). */ Oid -GetTopMostAncestorInPublication(Oid puboid, List *ancestors, int *ancestor_level) +GetTopMostAncestorInPublication(Oid puboid, List *ancestors, + int *ancestor_level, List *except_pubids) { ListCell *lc; Oid topmost_relid = InvalidOid; int level = 0; + bool check_schemas = !list_member_oid(except_pubids, puboid); /* * Find the "topmost" ancestor that is in this publication. @@ -470,7 +476,7 @@ GetTopMostAncestorInPublication(Oid puboid, List *ancestors, int *ancestor_level if (ancestor_level) *ancestor_level = level; } - else + else if (check_schemas) { aschemaPubids = GetSchemaPublications(get_rel_namespace(ancestor)); if (list_member_oid(aschemaPubids, puboid)) @@ -545,18 +551,30 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, * duplicates, it's here just to provide nicer error message in common * case. The real protection is the unique key on the catalog. */ - if (SearchSysCacheExists2(PUBLICATIONRELMAP, ObjectIdGetDatum(relid), - ObjectIdGetDatum(pubid))) + tup = SearchSysCache2(PUBLICATIONRELMAP, ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + + if (HeapTupleIsValid(tup)) { + bool is_except = ((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept; + + ReleaseSysCache(tup); table_close(rel, RowExclusiveLock); if (if_not_exists) return InvalidObjectAddress; - ereport(ERROR, - (errcode(ERRCODE_DUPLICATE_OBJECT), - errmsg("relation \"%s\" is already member of publication \"%s\"", - RelationGetRelationName(targetrel), pub->name))); + if (is_except) + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("table \"%s\" cannot be added because it is excluded from publication \"%s\"", + RelationGetQualifiedRelationName(targetrel), + pub->name))); + else + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("relation \"%s\" is already member of publication \"%s\"", + RelationGetRelationName(targetrel), pub->name))); } check_publication_add_relation(pri); @@ -982,12 +1000,13 @@ GetIncludedPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) * Gets list of table oids that were specified in the EXCEPT clause for a * publication. * - * This should only be used FOR ALL TABLES publications. + * This is used for FOR ALL TABLES and FOR TABLES IN SCHEMA publications, + * both of which support EXCEPT TABLE. */ List * GetExcludedPublicationTables(Oid pubid, PublicationPartOpt pub_partopt) { - Assert(GetPublication(pubid)->alltables); + Assert(GetPublication(pubid)->alltables || is_schema_publication(pubid)); return get_publication_relations(pubid, pub_partopt, true); } @@ -1049,15 +1068,15 @@ GetAllPublicationRelations(Oid pubid, char relkind, bool pubviaroot) TableScanDesc scan; HeapTuple tuple; List *result = NIL; - List *exceptlist = NIL; + List *except_relids = NIL; Assert(!(relkind == RELKIND_SEQUENCE && pubviaroot)); /* EXCEPT filtering applies only to relations, not sequences */ if (relkind == RELKIND_RELATION) - exceptlist = GetExcludedPublicationTables(pubid, pubviaroot ? - PUBLICATION_PART_ROOT : - PUBLICATION_PART_LEAF); + except_relids = GetExcludedPublicationTables(pubid, pubviaroot ? + PUBLICATION_PART_ROOT : + PUBLICATION_PART_LEAF); classRel = table_open(RelationRelationId, AccessShareLock); @@ -1075,7 +1094,7 @@ GetAllPublicationRelations(Oid pubid, char relkind, bool pubviaroot) if (is_publishable_class(relid, relForm) && !(relForm->relispartition && pubviaroot) && - !list_member_oid(exceptlist, relid)) + !list_member_oid(except_relids, relid)) result = lappend_oid(result, relid); } @@ -1097,7 +1116,7 @@ GetAllPublicationRelations(Oid pubid, char relkind, bool pubviaroot) if (is_publishable_class(relid, relForm) && !relForm->relispartition && - !list_member_oid(exceptlist, relid)) + !list_member_oid(except_relids, relid)) result = lappend_oid(result, relid); } @@ -1232,22 +1251,67 @@ GetSchemaPublicationRelations(Oid schemaid, PublicationPartOpt pub_partopt) /* * Gets the list of all relations published by FOR TABLES IN SCHEMA - * publication. + * publication, excluding any tables listed in the EXCEPT clause. */ List * GetAllSchemaPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) { List *result = NIL; List *pubschemalist = GetPublicationSchemas(pubid); + List *except_relids = NIL; ListCell *cell; + /* get the list of tables excluded via EXCEPT TABLE for this publication */ + if (pubschemalist != NIL) + except_relids = GetExcludedPublicationTables(pubid, pub_partopt); + foreach(cell, pubschemalist) { Oid schemaid = lfirst_oid(cell); List *schemaRels = NIL; schemaRels = GetSchemaPublicationRelations(schemaid, pub_partopt); - result = list_concat(result, schemaRels); + + if (except_relids != NIL) + { + /* filter out any tables that appear in the EXCEPT list */ + ListCell *rlc; + + foreach(rlc, schemaRels) + { + Oid relid = lfirst_oid(rlc); + bool excluded = list_member_oid(except_relids, relid); + + /* + * Also exclude any relation whose partition ancestor is in + * the EXCEPT list. This matters when pub_partopt is + * PUBLICATION_PART_ROOT: the except list holds only the root + * OID, but the schema scan may also return individual + * partition relations that live in the same schema. + */ + if (!excluded && get_rel_relispartition(relid)) + { + List *ancestors = get_partition_ancestors(relid); + ListCell *alc; + + foreach(alc, ancestors) + { + if (list_member_oid(except_relids, lfirst_oid(alc))) + { + excluded = true; + break; + } + } + list_free(ancestors); + } + + if (!excluded) + result = lappend_oid(result, relid); + } + list_free(schemaRels); + } + else + result = list_concat(result, schemaRels); } return result; @@ -1324,6 +1388,7 @@ is_table_publishable_in_publication(Oid relid, Publication *pub) { bool relispartition; List *ancestors = NIL; + HeapTuple tup; /* * For non-pubviaroot publications, a partitioned table is never the @@ -1380,20 +1445,62 @@ is_table_publishable_in_publication(Oid relid, Publication *pub) * If it's false, the partition is covered by its ancestor's presence in * the publication, it should be included (return true). */ - if (relispartition && - OidIsValid(GetTopMostAncestorInPublication(pub->oid, ancestors, NULL))) - return !pub->pubviaroot; + if (relispartition) + { + Oid ancestor_oid; + + ancestor_oid = GetTopMostAncestorInPublication(pub->oid, ancestors, NULL, NIL); + if (OidIsValid(ancestor_oid)) + { + /* + * The ancestor was found in the publication (via explicit + * membership or schema membership), but it may be excluded. Check + * for a prexcept row before concluding the partition is + * published. + */ + tup = SearchSysCache2(PUBLICATIONRELMAP, + ObjectIdGetDatum(ancestor_oid), + ObjectIdGetDatum(pub->oid)); + if (HeapTupleIsValid(tup)) + { + bool is_except; + + is_except = ((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept; + ReleaseSysCache(tup); + if (is_except) + return false; + } + return !pub->pubviaroot; + } + } /* * Check whether the table is explicitly published via pg_publication_rel * or pg_publication_namespace. + * + * A pg_publication_rel row with prexcept=true means the table is + * explicitly excluded via EXCEPT and must not be reported as published, + * even if its schema is otherwise included. A row with prexcept=false + * means it is explicitly included. If no pg_publication_rel row exists, + * the table is published iff its schema appears in + * pg_publication_namespace. */ - return (SearchSysCacheExists2(PUBLICATIONRELMAP, - ObjectIdGetDatum(relid), - ObjectIdGetDatum(pub->oid)) || - SearchSysCacheExists2(PUBLICATIONNAMESPACEMAP, - ObjectIdGetDatum(get_rel_namespace(relid)), - ObjectIdGetDatum(pub->oid))); + + tup = SearchSysCache2(PUBLICATIONRELMAP, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pub->oid)); + if (HeapTupleIsValid(tup)) + { + bool is_except; + + is_except = ((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept; + ReleaseSysCache(tup); + return !is_except; + } + + return SearchSysCacheExists2(PUBLICATIONNAMESPACEMAP, + ObjectIdGetDatum(get_rel_namespace(relid)), + ObjectIdGetDatum(pub->oid)); } /* diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 440adb356ad..269f77eeb99 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -181,7 +181,7 @@ parse_publication_options(ParseState *pstate, */ static void ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, - List **rels, List **exceptrels, List **schemas) + List **rels, List **except_pubtables, List **schemas) { ListCell *cell; PublicationObjSpec *pubobj; @@ -200,7 +200,7 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, { case PUBLICATIONOBJ_EXCEPT_TABLE: pubobj->pubtable->except = true; - *exceptrels = lappend(*exceptrels, pubobj->pubtable); + *except_pubtables = lappend(*except_pubtables, pubobj->pubtable); break; case PUBLICATIONOBJ_TABLE: pubobj->pubtable->except = false; @@ -224,6 +224,38 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, /* Filter out duplicates if user specifies "sch1, sch1" */ *schemas = list_append_unique_oid(*schemas, schemaid); + + /* + * Qualify unqualified EXCEPT table names with the resolved + * current schema and reject any explicitly cross-schema + * entries. This mirrors the parse-time handling done for + * TABLES_IN_SCHEMA in preprocess_pubobj_list(), deferred here + * because CURRENT_SCHEMA is not known until execution time. + */ + if (pubobj->except_tables != NIL) + { + char *cur_schema_name = get_namespace_name(schemaid); + + foreach_ptr(PublicationObjSpec, eobj, pubobj->except_tables) + { + const char *eobj_schemaname = + eobj->pubtable->relation->schemaname; + const char *eobj_relname = + eobj->pubtable->relation->relname; + + if (eobj_schemaname == NULL) + eobj->pubtable->relation->schemaname = cur_schema_name; + else if (strcmp(eobj_schemaname, cur_schema_name) != 0) + ereport(ERROR, + errcode(ERRCODE_INVALID_OBJECT_DEFINITION), + errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", + quote_qualified_identifier(eobj_schemaname, eobj_relname), + cur_schema_name)); + + *except_pubtables = lappend(*except_pubtables, + eobj->pubtable); + } + } break; default: /* shouldn't happen */ @@ -305,7 +337,7 @@ pub_rf_contains_invalid_column(Oid pubid, Relation relation, List *ancestors, if (pubviaroot && relation->rd_rel->relispartition) { publish_as_relid - = GetTopMostAncestorInPublication(pubid, ancestors, NULL); + = GetTopMostAncestorInPublication(pubid, ancestors, NULL, NIL); if (!OidIsValid(publish_as_relid)) publish_as_relid = relid; @@ -389,7 +421,7 @@ pub_contains_invalid_column(Oid pubid, Relation relation, List *ancestors, */ if (pubviaroot && relation->rd_rel->relispartition) { - publish_as_relid = GetTopMostAncestorInPublication(pubid, ancestors, NULL); + publish_as_relid = GetTopMostAncestorInPublication(pubid, ancestors, NULL, NIL); if (!OidIsValid(publish_as_relid)) publish_as_relid = relid; @@ -849,7 +881,7 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) char publish_generated_columns; AclResult aclresult; List *relations = NIL; - List *exceptrelations = NIL; + List *except_pubtables = NIL; List *schemaidlist = NIL; /* must have CREATE privilege on database */ @@ -936,16 +968,16 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) /* Associate objects with the publication. */ ObjectsInPublicationToOids(stmt->pubobjects, pstate, &relations, - &exceptrelations, &schemaidlist); + &except_pubtables, &schemaidlist); if (stmt->for_all_tables) { /* Process EXCEPT table list */ - if (exceptrelations != NIL) + if (except_pubtables != NIL) { List *rels; - rels = OpenTableList(exceptrelations); + rels = OpenTableList(except_pubtables); PublicationAddTables(puboid, rels, true, NULL); CloseTableList(rels); } @@ -959,6 +991,8 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) } else if (!stmt->for_all_sequences) { + List *explicitrelids = NIL; + /* FOR TABLES IN SCHEMA requires superuser */ if (schemaidlist != NIL && !superuser()) ereport(ERROR, @@ -977,6 +1011,19 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) schemaidlist != NIL, publish_via_partition_root); + /* + * Collect explicit table OIDs now, before we close the relation + * list, so that except-table validation below can check for + * contradictions without relying on a catalog scan that might not + * yet see the just-inserted rows. + */ + if (except_pubtables != NIL) + { + foreach_ptr(PublicationRelInfo, pri, rels) + explicitrelids = lappend_oid(explicitrelids, + RelationGetRelid(pri->relation)); + } + PublicationAddTables(puboid, rels, true, NULL); CloseTableList(rels); } @@ -989,6 +1036,34 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) */ LockSchemaList(schemaidlist); PublicationAddSchemas(puboid, schemaidlist, true, NULL); + + if (except_pubtables != NIL) + { + List *except_rels; + + except_rels = OpenTableList(except_pubtables); + + /* + * Validate that each excluded table is not also in the + * explicit table list (which would be contradictory). Use the + * in-memory explicitrelids collected above rather than + * re-reading the catalog, which may not yet see the + * just-inserted rows. + */ + foreach_ptr(PublicationRelInfo, pri, except_rels) + { + Oid except_relid = RelationGetRelid(pri->relation); + + if (list_member_oid(explicitrelids, except_relid)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" cannot appear in both the table list and the EXCEPT clause", + RelationGetQualifiedRelationName(pri->relation))); + } + + PublicationAddTables(puboid, except_rels, true, NULL); + CloseTableList(except_rels); + } } } @@ -1683,12 +1758,12 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) else { List *relations = NIL; - List *exceptrelations = NIL; + List *except_pubtables = NIL; List *schemaidlist = NIL; Oid pubid = pubform->oid; ObjectsInPublicationToOids(stmt->pubobjects, pstate, &relations, - &exceptrelations, &schemaidlist); + &except_pubtables, &schemaidlist); CheckAlterPublication(stmt, tup, relations, schemaidlist); @@ -1711,7 +1786,7 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) errmsg("publication \"%s\" does not exist", stmt->pubname)); - relations = list_concat(relations, exceptrelations); + relations = list_concat(relations, except_pubtables); AlterPublicationTables(stmt, tup, relations, pstate->p_sourcetext, schemaidlist != NIL); AlterPublicationSchemas(stmt, tup, schemaidlist); @@ -1829,6 +1904,55 @@ RemovePublicationSchemaById(Oid psoid) table_close(rel, RowExclusiveLock); } +/* + * Remove any EXCEPT clause entries for a relation from schema publications. + * Called when a table changes schema (ALTER TABLE ... SET SCHEMA), so that + * a schema-scoped exclusion does not silently follow the table to its new + * schema. + */ +void +RemoveSchemaPubExceptForRel(Oid relid, Oid oldNspOid, Oid newNspOid) +{ + List *pubids; + + pubids = GetRelationExcludedPublications(relid); + + foreach_oid(pubid, pubids) + { + Oid proid; + + /* + * This problem does not apply to FOR ALL TABLES publications, because + * their EXCEPT clause is publication-scoped, not schema-scoped: the + * exclusion should persist regardless of what schema the table is in. + */ + if (!is_schema_publication(pubid)) + continue; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddress obj; + + ObjectAddressSet(obj, PublicationRelRelationId, proid); + + ereport(DEBUG2, + errmsg_internal("auto-remove exclusion of table \"%s.%s\" from publication \"%s\": table moved to schema \"%s\"", + get_namespace_name(oldNspOid), + get_rel_name(relid), + get_publication_name(pubid, false), + get_namespace_name(newNspOid))); + + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + list_free(pubids); +} + /* * Open relations specified by a PublicationTable list. * The returned tables are locked in ShareUpdateExclusiveLock mode in order to diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..f8b7e6766d9 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -63,6 +63,7 @@ #include "commands/event_trigger.h" #include "commands/extension.h" #include "commands/repack.h" +#include "commands/publicationcmds.h" #include "commands/sequence.h" #include "commands/tablecmds.h" #include "commands/tablespace.h" @@ -19290,6 +19291,16 @@ AlterTableNamespaceInternal(Relation rel, Oid oldNspOid, Oid nspOid, AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid, false, objsMoved); + /* + * Remove any EXCEPT clause entries for this relation from schema + * publications. A schema-scoped exclusion is no longer meaningful once + * the table moves to a different schema. + */ + if (rel->rd_rel->relkind == RELKIND_RELATION || + rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE) + RemoveSchemaPubExceptForRel(RelationGetRelid(rel), oldNspOid, + nspOid); + table_close(classRel, RowExclusiveLock); } diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y index ff4e1388c55..6a7a1bc5f8d 100644 --- a/src/backend/parser/gram.y +++ b/src/backend/parser/gram.y @@ -58,6 +58,7 @@ #include "nodes/makefuncs.h" #include "nodes/nodeFuncs.h" #include "parser/parser.h" +#include "utils/builtins.h" #include "utils/datetime.h" #include "utils/xml.h" @@ -11272,7 +11273,7 @@ AlterOwnerStmt: ALTER AGGREGATE aggregate_with_argtypes OWNER TO RoleSpec * pub_obj is one of: * * TABLE table [, ...] - * TABLES IN SCHEMA schema [, ...] + * TABLES IN SCHEMA schema [EXCEPT (TABLE table [, ...] )] [, ...] * *****************************************************************************/ @@ -11332,23 +11333,26 @@ PublicationObjSpec: $$->pubtable->columns = $3; $$->pubtable->whereClause = $4; } - | TABLES IN_P SCHEMA ColId + | TABLES IN_P SCHEMA ColId opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_SCHEMA; $$->name = $4; + $$->except_tables = $5; $$->location = @4; } - | TABLES IN_P SCHEMA CURRENT_SCHEMA + | TABLES IN_P SCHEMA CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_CUR_SCHEMA; + $$->except_tables = $5; $$->location = @4; } - | ColId opt_column_list OptWhereClause + | ColId opt_column_list OptWhereClause opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $4; /* * If either a row filter or column list is specified, create * a PublicationTable object. @@ -11392,10 +11396,11 @@ PublicationObjSpec: $$->pubtable->columns = $2; $$->pubtable->whereClause = $3; } - | CURRENT_SCHEMA + | CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $2; $$->location = @1; } ; @@ -20784,6 +20789,8 @@ preprocess_pub_all_objtype_list(List *all_objects_list, List **pubobjects, /* * Process pubobjspec_list to check for errors in any of the objects and * convert PUBLICATIONOBJ_CONTINUATION into appropriate PublicationObjSpecType. + * Also flattens except_tables from TABLES IN SCHEMA nodes into the list so + * that ObjectsInPublicationToOids() sees them as top-level EXCEPT_TABLE entries. */ static void preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) @@ -20812,6 +20819,13 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLE) { + /* EXCEPT is not valid for table objects */ + if (pubobj->except_tables != NIL) + ereport(ERROR, + errcode(ERRCODE_SYNTAX_ERROR), + errmsg("EXCEPT is not allowed for TABLE publication objects"), + parser_errposition(pubobj->location)); + /* relation name or pubtable must be set for this type of object */ if (!pubobj->name && !pubobj->pubtable) ereport(ERROR, @@ -20860,6 +20874,36 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) errcode(ERRCODE_SYNTAX_ERROR), errmsg("invalid schema name"), parser_errposition(pubobj->location)); + + /* + * For TABLES_IN_SCHEMA, qualify unqualified EXCEPT table names + * with the parent schema and reject cross-schema entries at parse + * time, then flatten into the top-level list. + * + * For TABLES_IN_CUR_SCHEMA the schema name is not yet known, so + * skip both steps here; ObjectsInPublicationToOids() will + * qualify names and validate schema membership at execution time. + */ + if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLES_IN_SCHEMA) + { + foreach_ptr(PublicationObjSpec, eobj, pubobj->except_tables) + { + const char *eobj_schemaname = eobj->pubtable->relation->schemaname; + const char *eobj_relname = eobj->pubtable->relation->relname; + + if (eobj_schemaname == NULL) + eobj->pubtable->relation->schemaname = pubobj->name; + else if (strcmp(eobj_schemaname, pubobj->name) != 0) + ereport(ERROR, + errcode(ERRCODE_INVALID_OBJECT_DEFINITION), + errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", + quote_qualified_identifier(eobj_schemaname, eobj_relname), + pubobj->name), + parser_errposition(eobj->location)); + } + pubobjspec_list = list_concat(pubobjspec_list, pubobj->except_tables); + pubobj->except_tables = NIL; + } } prevobjtype = pubobj->pubobjtype; diff --git a/src/backend/replication/pgoutput/pgoutput.c b/src/backend/replication/pgoutput/pgoutput.c index 4ecfcbff7ab..7ee84ec1c83 100644 --- a/src/backend/replication/pgoutput/pgoutput.c +++ b/src/backend/replication/pgoutput/pgoutput.c @@ -2097,6 +2097,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) * are absorbed while decoding WAL. */ List *schemaPubids = GetSchemaPublications(schemaId); + List *except_pubids; ListCell *lc; Oid publish_as_relid = relid; int publish_ancestor_level = 0; @@ -2104,6 +2105,28 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) char relkind = get_rel_relkind(relid); List *rel_publications = NIL; + /* + * For the schema EXCEPT check, we must look up the top-most ancestor + * rather than the relation itself. check_publication_add_relation() + * prevents individual partitions from appearing in the EXCEPT clause, + * so only a root (non-partition) table can have prexcept = true. + * Using the partition's own OID would always return NIL and miss the + * exclusion. + */ + Oid root_relid; + + if (am_partition) + { + List *ancestors = get_partition_ancestors(relid); + + root_relid = llast_oid(ancestors); + list_free(ancestors); + } + else + root_relid = relid; + + except_pubids = GetRelationExcludedPublications(root_relid); + /* Reload publications if needed before use. */ if (!publications_valid) { @@ -2267,7 +2290,8 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) ancestor = GetTopMostAncestorInPublication(pub->oid, ancestors, - &level); + &level, + except_pubids); if (ancestor != InvalidOid) { @@ -2281,7 +2305,8 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) } if (list_member_oid(pubids, pub->oid) || - list_member_oid(schemaPubids, pub->oid) || + (list_member_oid(schemaPubids, pub->oid) && + !list_member_oid(except_pubids, pub->oid)) || ancestor_published) publish = true; } @@ -2360,6 +2385,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) list_free(pubids); list_free(schemaPubids); + list_free(except_pubids); list_free(rel_publications); entry->replicate_valid = true; diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c index af3935b0078..9470a0bbf5e 100644 --- a/src/bin/psql/describe.c +++ b/src/bin/psql/describe.c @@ -7038,6 +7038,24 @@ describePublications(const char *pattern) if (!addFooterToPublicationDesc(&buf, _("Tables from schemas:"), true, &cont)) goto error_return; + + if (pset.sversion >= 190000) + { + /* + * Get tables in the EXCEPT clause for this schema + * publication. + */ + printfPQExpBuffer(&buf, + "SELECT concat(c.relnamespace::regnamespace, '.', c.relname)\n" + "FROM pg_catalog.pg_class c\n" + " JOIN pg_catalog.pg_publication_rel pr ON c.oid = pr.prrelid\n" + "WHERE pr.prpubid = '%s'\n" + " AND pr.prexcept\n" + "ORDER BY 1", pubid); + if (!addFooterToPublicationDesc(&buf, _("Except tables:"), + true, &cont)) + goto error_return; + } } } else diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index de547a8cb37..53bb7c8679b 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -1065,6 +1065,24 @@ static const SchemaQuery Query_for_trigger_of_table = { "SELECT nspname FROM pg_catalog.pg_namespace "\ " WHERE nspname LIKE '%s'" +#define Query_for_list_of_tables_in_schema \ +"SELECT n.nspname || '.' || c.relname "\ +" FROM pg_catalog.pg_class c "\ +" JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "\ +" WHERE c.relkind IN (" CppAsString2(RELKIND_RELATION) ", " \ + CppAsString2(RELKIND_PARTITIONED_TABLE) ") "\ +" AND (n.nspname || '.' || c.relname) LIKE '%s' "\ +" AND n.nspname = '%s'" + +#define Query_for_list_of_tables_in_current_schema \ +"SELECT c.relname "\ +" FROM pg_catalog.pg_class c "\ +" JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "\ +" WHERE c.relkind IN (" CppAsString2(RELKIND_RELATION) ", " \ + CppAsString2(RELKIND_PARTITIONED_TABLE) ") "\ +" AND c.relname LIKE '%s' "\ +" AND n.nspname = pg_catalog.current_schema()" + /* Use COMPLETE_WITH_QUERY_VERBATIM with these queries for GUC names: */ #define Query_for_list_of_alter_system_set_vars \ "SELECT pg_catalog.lower(name) FROM pg_catalog.pg_settings "\ @@ -3787,8 +3805,21 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); - else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && (!ends_with(prev_wd, ','))) - COMPLETE_WITH("WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE", "WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* Complete "CREATE PUBLICATION <name> [...] WITH" */ else if (Matches("CREATE", "PUBLICATION", MatchAnyN, "WITH", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/include/catalog/pg_publication.h b/src/include/catalog/pg_publication.h index 89b4bb14f62..53e3d7c6f3d 100644 --- a/src/include/catalog/pg_publication.h +++ b/src/include/catalog/pg_publication.h @@ -191,7 +191,8 @@ extern List *GetPubPartitionOptionRelations(List *result, PublicationPartOpt pub_partopt, Oid relid); extern Oid GetTopMostAncestorInPublication(Oid puboid, List *ancestors, - int *ancestor_level); + int *ancestor_level, + List *except_pubids); extern bool is_publishable_relation(Relation rel); extern bool is_schema_publication(Oid pubid); diff --git a/src/include/commands/publicationcmds.h b/src/include/commands/publicationcmds.h index 4cf45c17cc5..fb1703aa675 100644 --- a/src/include/commands/publicationcmds.h +++ b/src/include/commands/publicationcmds.h @@ -27,6 +27,8 @@ extern void AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt); extern void RemovePublicationById(Oid pubid); extern void RemovePublicationRelById(Oid proid); extern void RemovePublicationSchemaById(Oid psoid); +extern void RemoveSchemaPubExceptForRel(Oid relid, Oid oldNspOid, + Oid newNspOid); extern ObjectAddress AlterPublicationOwner(const char *name, Oid newOwnerId); extern void AlterPublicationOwner_oid(Oid pubid, Oid newOwnerId); diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h index 4133c404a6b..1299b0a67a4 100644 --- a/src/include/nodes/parsenodes.h +++ b/src/include/nodes/parsenodes.h @@ -4488,6 +4488,8 @@ typedef struct PublicationObjSpec PublicationObjSpecType pubobjtype; /* type of this publication object */ char *name; PublicationTable *pubtable; + List *except_tables; /* tables specified in the EXCEPT clause (for + * TABLES IN SCHEMA) */ ParseLoc location; /* token location, or -1 if unknown */ } PublicationObjSpec; diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 29e54b214a0..6efed0a0cce 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -270,6 +270,12 @@ CREATE PUBLICATION testpub_foralltables_excepttable2 FOR ALL TABLES EXCEPT (test ERROR: syntax error at or near "testpub_tbl1" LINE 1: ..._foralltables_excepttable2 FOR ALL TABLES EXCEPT (testpub_tb... ^ +-- fail - EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testpub_tbl3); +ERROR: EXCEPT is not allowed for TABLE publication objects +LINE 2: FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testp... + ^ --------------------------------------------- -- SET ALL TABLES/SEQUENCES --------------------------------------------- @@ -470,7 +476,130 @@ HINT: Change the publication's EXCEPT clause using ALTER PUBLICATION ... SET AL RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Create same-named tables in public to verify unqualified EXCEPT entries +-- are qualified with the named schema, not public +CREATE TABLE testpub_nopk (foo int, bar int); +CREATE TABLE testpub_tbl_s1 (a int primary key, b text); +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + Publication testpub_schema_except1 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- Exclude multiple tables using unqualified names; same-named tables exist in +-- public to confirm unqualified names resolve to pub_test, not public +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + Publication testpub_schema_except2 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_nopk" + "pub_test.testpub_tbl_s1" + +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testp... + ^ +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); +ERROR: table "pub_test.testpub_tbl_s1" in EXCEPT clause does not belong to schema "public" +LINE 2: ...R TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.t... + ^ +-- Multiple schemas each with their own EXCEPT clause +CREATE PUBLICATION testpub_schema_except_multi + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_schema_except_multi + Publication testpub_schema_except_multi + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- ALTER TABLE ... SET SCHEMA on a table excluded by a schema publication: +-- the schema-scoped exclusion is no longer meaningful once the table moves +-- out of its schema, so the exclusion is auto-removed. +CREATE PUBLICATION testpub_schema_except_setsch + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_schema_except_setsch + Publication testpub_schema_except_setsch + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s2" + +ALTER TABLE pub_test.testpub_tbl_s2 SET SCHEMA public; +\dRp+ testpub_schema_except_setsch + Publication testpub_schema_except_setsch + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + +DROP PUBLICATION testpub_schema_except_setsch; +-- Restore for further tests +ALTER TABLE public.testpub_tbl_s2 SET SCHEMA pub_test; +-- fail: table appears in both the explicit table list and the EXCEPT clause +CREATE PUBLICATION testpub_except_conflict + FOR TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot appear in both the table list and the EXCEPT clause +-- fail: nonexistent table in EXCEPT clause +CREATE PUBLICATION testpub_except_norel + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- fail: partition cannot appear in EXCEPT clause; only root tables are allowed +CREATE TABLE pub_test.testpub_parted_s (a int) PARTITION BY LIST (a); +CREATE TABLE pub_test.testpub_part_s PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (1); +CREATE PUBLICATION testpub_except_partition + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); +ERROR: cannot specify relation "pub_test.testpub_part_s" in the publication EXCEPT clause +DETAIL: This operation is not supported for individual partitions. +-- fail: TABLE keyword is required for the first entry in the EXCEPT clause +CREATE PUBLICATION testpub_except_nokw + FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +ERROR: syntax error at or near "testpub_nopk" +LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + ^ +-- Cleanup +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP TABLE pub_test.testpub_parted_s CASCADE; +DROP TABLE testpub_nopk, testpub_tbl_s1; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +--------------------------------------------- +-- Tests for publications with SEQUENCES +--------------------------------------------- CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; -- FOR ALL SEQUENCES @@ -1953,6 +2082,27 @@ ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b); ERROR: column specification not allowed for schema LINE 1: ...TION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b)... ^ +-- EXCEPT clause with CURRENT_SCHEMA: cross-schema entry must be rejected +SET search_path = pub_test1; +-- qualified name from wrong schema -> error +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.tbl1); +ERROR: table "pub_test2.tbl1" in EXCEPT clause does not belong to schema "pub_test1" +-- unqualified name implicitly qualified with current schema (pub_test1.tbl) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl); +RESET client_min_messages; +\dRp+ testpub_cursch_except + Publication testpub_cursch_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test1" +Except tables: + "pub_test1.tbl" + +DROP PUBLICATION testpub_cursch_except; +RESET search_path; -- cleanup pub_test1 schema for invalidation tests ALTER PUBLICATION testpub2_forschema DROP TABLES IN SCHEMA pub_test1; DROP PUBLICATION testpub3_forschema, testpub4_forschema, testpub5_forschema, testpub6_forschema, testpub_fortable; @@ -2304,6 +2454,7 @@ DROP ROLE regress_publication_user_dummy; -- Test pg_get_publication_tables(text[], oid) function CREATE SCHEMA gpt_test_sch; CREATE TABLE gpt_test_sch.tbl_sch (id int); +CREATE TABLE gpt_test_sch.tbl_sch2 (id int); CREATE TABLE tbl_normal (id int); CREATE TABLE tbl_parent (id1 int, id2 int, id3 int) PARTITION BY RANGE (id1); CREATE TABLE tbl_part1 PARTITION OF tbl_parent FOR VALUES FROM (1) TO (10); @@ -2314,6 +2465,7 @@ CREATE PUBLICATION pub_all_no_viaroot FOR ALL TABLES WITH (publish_via_partition CREATE PUBLICATION pub_all_except FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = true); CREATE PUBLICATION pub_all_except_no_viaroot FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_schema FOR TABLES IN SCHEMA gpt_test_sch; +CREATE PUBLICATION pub_schema_except FOR TABLES IN SCHEMA gpt_test_sch EXCEPT (TABLE gpt_test_sch.tbl_sch); CREATE PUBLICATION pub_normal FOR TABLE tbl_normal WHERE (id < 10); CREATE PUBLICATION pub_part_leaf FOR TABLE tbl_part1 WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_part_parent FOR TABLE tbl_parent (id1, id2) WHERE (id1 = 10) WITH (publish_via_partition_root = true); @@ -2465,6 +2617,18 @@ SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_part1'); -- no r ---------+---------+-------+------ (0 rows) +-- test for EXCEPT clause with schema publication +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch'); -- no result (excluded) + pubname | relname | attrs | qual +---------+---------+-------+------ +(0 rows) + +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch2'); -- one row (included via schema) + pubname | relname | attrs | qual +-------------------+----------+-------+------ + pub_schema_except | tbl_sch2 | 1 | +(1 row) + -- two rows with different row filter SELECT * FROM test_gpt(ARRAY['pub_all', 'pub_normal'], 'tbl_normal'); pubname | relname | attrs | qual @@ -2517,6 +2681,7 @@ DROP PUBLICATION pub_all_no_viaroot; DROP PUBLICATION pub_all_except; DROP PUBLICATION pub_all_except_no_viaroot; DROP PUBLICATION pub_schema; +DROP PUBLICATION pub_schema_except; DROP PUBLICATION pub_normal; DROP PUBLICATION pub_part_leaf; DROP PUBLICATION pub_part_parent; @@ -2525,7 +2690,9 @@ DROP PUBLICATION pub_part_parent_child; DROP VIEW gpt_test_view; DROP TABLE tbl_normal, tbl_parent, tbl_part1; DROP SCHEMA gpt_test_sch CASCADE; -NOTICE: drop cascades to table gpt_test_sch.tbl_sch +NOTICE: drop cascades to 2 other objects +DETAIL: drop cascades to table gpt_test_sch.tbl_sch +drop cascades to table gpt_test_sch.tbl_sch2 -- stage objects for pg_dump tests CREATE SCHEMA pubme CREATE TABLE t0 (c int, d int) CREATE TABLE t1 (c int); CREATE SCHEMA pubme2 CREATE TABLE t0 (c int, d int); diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 041e14a4de6..2e79e9e4112 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -123,6 +123,9 @@ CREATE PUBLICATION testpub_foralltables_excepttable1 FOR ALL TABLES EXCEPT (TABL \d testpub_tbl1 -- fail - first table in the EXCEPT list should use TABLE keyword CREATE PUBLICATION testpub_foralltables_excepttable2 FOR ALL TABLES EXCEPT (testpub_tbl1, testpub_tbl2); +-- fail - EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testpub_tbl3); --------------------------------------------- -- SET ALL TABLES/SEQUENCES @@ -220,7 +223,83 @@ RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Create same-named tables in public to verify unqualified EXCEPT entries +-- are qualified with the named schema, not public +CREATE TABLE testpub_nopk (foo int, bar int); +CREATE TABLE testpub_tbl_s1 (a int primary key, b text); + +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + +-- Exclude multiple tables using unqualified names; same-named tables exist in +-- public to confirm unqualified names resolve to pub_test, not public +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); + +-- Multiple schemas each with their own EXCEPT clause +CREATE PUBLICATION testpub_schema_except_multi + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_schema_except_multi + +-- ALTER TABLE ... SET SCHEMA on a table excluded by a schema publication: +-- the schema-scoped exclusion is no longer meaningful once the table moves +-- out of its schema, so the exclusion is auto-removed. +CREATE PUBLICATION testpub_schema_except_setsch + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_schema_except_setsch +ALTER TABLE pub_test.testpub_tbl_s2 SET SCHEMA public; +\dRp+ testpub_schema_except_setsch +DROP PUBLICATION testpub_schema_except_setsch; +-- Restore for further tests +ALTER TABLE public.testpub_tbl_s2 SET SCHEMA pub_test; + +-- fail: table appears in both the explicit table list and the EXCEPT clause +CREATE PUBLICATION testpub_except_conflict + FOR TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: nonexistent table in EXCEPT clause +CREATE PUBLICATION testpub_except_norel + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- fail: partition cannot appear in EXCEPT clause; only root tables are allowed +CREATE TABLE pub_test.testpub_parted_s (a int) PARTITION BY LIST (a); +CREATE TABLE pub_test.testpub_part_s PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (1); +CREATE PUBLICATION testpub_except_partition + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); + +-- fail: TABLE keyword is required for the first entry in the EXCEPT clause +CREATE PUBLICATION testpub_except_nokw + FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + +-- Cleanup +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP TABLE pub_test.testpub_parted_s CASCADE; +DROP TABLE testpub_nopk, testpub_tbl_s1; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; + +--------------------------------------------- +-- Tests for publications with SEQUENCES +--------------------------------------------- CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; @@ -1189,6 +1268,18 @@ ALTER PUBLICATION testpub1_forschema SET TABLES IN SCHEMA pub_test1, pub_test1; ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo (a, b); ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b); +-- EXCEPT clause with CURRENT_SCHEMA: cross-schema entry must be rejected +SET search_path = pub_test1; +-- qualified name from wrong schema -> error +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.tbl1); +-- unqualified name implicitly qualified with current schema (pub_test1.tbl) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl); +RESET client_min_messages; +\dRp+ testpub_cursch_except +DROP PUBLICATION testpub_cursch_except; +RESET search_path; + -- cleanup pub_test1 schema for invalidation tests ALTER PUBLICATION testpub2_forschema DROP TABLES IN SCHEMA pub_test1; DROP PUBLICATION testpub3_forschema, testpub4_forschema, testpub5_forschema, testpub6_forschema, testpub_fortable; @@ -1443,6 +1534,7 @@ DROP ROLE regress_publication_user_dummy; -- Test pg_get_publication_tables(text[], oid) function CREATE SCHEMA gpt_test_sch; CREATE TABLE gpt_test_sch.tbl_sch (id int); +CREATE TABLE gpt_test_sch.tbl_sch2 (id int); CREATE TABLE tbl_normal (id int); CREATE TABLE tbl_parent (id1 int, id2 int, id3 int) PARTITION BY RANGE (id1); CREATE TABLE tbl_part1 PARTITION OF tbl_parent FOR VALUES FROM (1) TO (10); @@ -1454,6 +1546,7 @@ CREATE PUBLICATION pub_all_no_viaroot FOR ALL TABLES WITH (publish_via_partition CREATE PUBLICATION pub_all_except FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = true); CREATE PUBLICATION pub_all_except_no_viaroot FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_schema FOR TABLES IN SCHEMA gpt_test_sch; +CREATE PUBLICATION pub_schema_except FOR TABLES IN SCHEMA gpt_test_sch EXCEPT (TABLE gpt_test_sch.tbl_sch); CREATE PUBLICATION pub_normal FOR TABLE tbl_normal WHERE (id < 10); CREATE PUBLICATION pub_part_leaf FOR TABLE tbl_part1 WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_part_parent FOR TABLE tbl_parent (id1, id2) WHERE (id1 = 10) WITH (publish_via_partition_root = true); @@ -1510,6 +1603,10 @@ SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'gpt_test_sch.tbl_sch SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_parent'); -- no result (excluded) SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_part1'); -- no result +-- test for EXCEPT clause with schema publication +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch'); -- no result (excluded) +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch2'); -- one row (included via schema) + -- two rows with different row filter SELECT * FROM test_gpt(ARRAY['pub_all', 'pub_normal'], 'tbl_normal'); @@ -1538,6 +1635,7 @@ DROP PUBLICATION pub_all_no_viaroot; DROP PUBLICATION pub_all_except; DROP PUBLICATION pub_all_except_no_viaroot; DROP PUBLICATION pub_schema; +DROP PUBLICATION pub_schema_except; DROP PUBLICATION pub_normal; DROP PUBLICATION pub_part_leaf; DROP PUBLICATION pub_part_parent; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 8c58d282eee..18c7b2c1fca 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -24,14 +24,17 @@ my $result; sub test_except_root_partition { - my ($pubviaroot) = @_; + my ($pubviaroot, $pubsql) = @_; + $pubsql //= + "CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1)"; + $pubsql .= " WITH (publish_via_partition_root = $pubviaroot)"; # If the root partitioned table is in the EXCEPT clause, all its # partitions are excluded from publication, regardless of the # publish_via_partition_root setting. $node_publisher->safe_psql( 'postgres', qq( - CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1) WITH (publish_via_partition_root = $pubviaroot); + $pubsql; INSERT INTO root1 VALUES (1), (101); )); $node_subscriber->safe_psql('postgres', @@ -223,6 +226,131 @@ $node_subscriber->safe_psql( test_except_root_partition('false'); test_except_root_partition('true'); +# Same validation using TABLES IN SCHEMA instead of FOR ALL TABLES. +my $schema_pub = + "CREATE PUBLICATION tap_pub_part FOR TABLES IN SCHEMA public EXCEPT (TABLE public.root1)"; +test_except_root_partition('false', $schema_pub); +test_except_root_partition('true', $schema_pub); + +# ============================================ +# EXCEPT test cases for TABLES IN SCHEMA +# ============================================ + +# Create a dedicated schema with two tables: one to be published and one to be +# excluded. Also create inherited tables to verify ONLY semantics. +$node_publisher->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_published AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.tab_excluded AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.parent (a int); + CREATE TABLE sch1.child (b int) INHERITS (sch1.parent); +)); + +$node_subscriber->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_published (a int); + CREATE TABLE sch1.tab_excluded (a int); + CREATE TABLE sch1.parent (a int); + CREATE TABLE sch1.child (b int) INHERITS (sch1.parent); +)); + +# Basic test: initial sync respects EXCEPT. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_excluded)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: initial sync copies included table'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: initial sync skips excluded table'); + +# DML: only the included table should be replicated. +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (6); + INSERT INTO sch1.tab_excluded VALUES (6); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(6), + 'TABLES IN SCHEMA EXCEPT: DML on included table is replicated'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: DML on excluded table is not replicated'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Inherited tables: excluding the parent (without ONLY) also excludes the child. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.parent)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.child VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.child"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: excluding parent (without ONLY) also excludes child' +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Test that EXCEPT (TABLE ONLY parent) excludes only the parent itself, not its +# child. Truncate child first so rows from the previous test are not copied by +# the initial table sync of the next subscription. +$node_publisher->safe_psql('postgres', 'TRUNCATE sch1.child'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE sch1.child'); +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE ONLY sch1.parent)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.child VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.child"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: ONLY parent in EXCEPT does not exclude child'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Cleanup schema tables before the multi-publication section. +$node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); +$node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); + # ============================================ # Test when a subscription is subscribing to multiple publications # ============================================ @@ -254,6 +382,7 @@ $node_publisher->safe_psql( DROP PUBLICATION tap_pub2; TRUNCATE tab1; )); +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_subscriber->safe_psql('postgres', qq(TRUNCATE tab1)); # OK when a table is excluded by pub1 EXCEPT clause, but it is included by pub2 -- 2.50.1 (Apple Git-155)
v15-0002-Add-EXCEPT-support-to-ALTER-PUBLICATION-ADD-TABL.patch (application/octet-stream, 18.6K) download From f34e62abff4e378b00aa2b85918a9487052ce076 Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Thu, 18 Jun 2026 11:30:14 +0530 Subject: [PATCH v15 2/4] Add EXCEPT support to ALTER PUBLICATION ADD TABLES IN SCHEMA Extend the EXCEPT clause support to allow tables to be excluded when adding a schema to a publication via ALTER PUBLICATION ... ADD. Syntax: ALTER PUBLICATION pub ADD TABLES IN SCHEMA s EXCEPT (TABLE s.t1); Since pg_dump uses ALTER PUBLICATION ... ADD, support for it is included in this patch. --- src/backend/catalog/pg_publication.c | 19 ++-- src/backend/commands/publicationcmds.c | 107 +++++++++++++++++++++- src/bin/pg_dump/pg_dump.c | 30 +++++- src/bin/pg_dump/t/002_pg_dump.pl | 24 +++++ src/bin/psql/tab-complete.in.c | 17 ++++ src/test/regress/expected/publication.out | 32 ++++++- src/test/regress/sql/publication.sql | 20 +++- src/test/subscription/t/037_except.pl | 32 +++++++ 8 files changed, 267 insertions(+), 14 deletions(-) diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index 4089b505f89..d1ff8839037 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -649,15 +649,18 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, * here, as CreatePublication() function invalidates all relations as part * of defining a FOR ALL TABLES publication. * - * For ALTER PUBLICATION, invalidation is needed only when adding an - * EXCEPT table to a publication already marked as ALL TABLES. For - * publications that were originally empty or defined as ALL SEQUENCES and - * are being converted to ALL TABLES, invalidation is skipped here, as - * AlterPublicationAllFlags() function invalidates all relations while - * marking the publication as ALL TABLES publication. + * For ALTER PUBLICATION, invalidation is needed when adding an EXCEPT + * table to either a FOR ALL TABLES publication (pub->alltables is true) + * or a FOR TABLES IN SCHEMA publication (is_schema_publication is true). + * The exception: when a publication is being converted to FOR ALL TABLES + * (pub->alltables is still false at this point), + * AlterPublicationAllFlags() will perform a full invalidation, so we skip + * it here. */ - inval_except_table = (alter_stmt != NULL) && pub->alltables && - (alter_stmt->for_all_tables && pri->except); + inval_except_table = (alter_stmt != NULL) && pri->except && + (pub->alltables + ? alter_stmt->for_all_tables + : is_schema_publication(pubid)); if (!pri->except || inval_except_table) { diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 269f77eeb99..c3ecda2ac91 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -70,6 +70,13 @@ static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok); static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); +static void AlterPublicationSchemas(AlterPublicationStmt *stmt, + HeapTuple tup, List *schemaidlist, + List *except_pubtables); +static void AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, + List *except_pubtables, + List *schemaidlist); static char defGetGeneratedColsOption(DefElem *def); @@ -1500,7 +1507,8 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, */ static void AlterPublicationSchemas(AlterPublicationStmt *stmt, - HeapTuple tup, List *schemaidlist) + HeapTuple tup, List *schemaidlist, + List *except_pubtables) { Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); @@ -1577,6 +1585,97 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, */ PublicationAddSchemas(pubform->oid, schemaidlist, true, stmt); } + + /* + * Increment the command counter so that is_schema_publication() in + * GetExcludedPublicationTables() can see the just-inserted schema + * rows when AlterPublicationSchemaExceptTables runs next. + */ + if (stmt->action == AP_AddObjects || stmt->action == AP_SetObjects) + CommandCounterIncrement(); + + AlterPublicationSchemaExceptTables(stmt, tup, except_pubtables, schemaidlist); +} + +/* + * Alter the EXCEPT list of a schema-level publication. + * + * Adds, removes, or replaces except-table entries in pg_publication_rel + * (rows with prexcept = true). These entries suppress publication of the + * named tables that would otherwise be covered by a FOR TABLES IN SCHEMA + * clause. + */ +static void +AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, List *except_pubtables, + List *schemaidlist) +{ + Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); + Oid pubid = pubform->oid; + + /* + * Nothing to do if no EXCEPT entries. + */ + if (!except_pubtables) + return; + + /* + * This function handles EXCEPT entries for schema-level publications + * only. For FOR ALL TABLES publications, EXCEPT entries are already + * processed by AlterPublicationTables(). + */ + if (schemaidlist == NIL && !is_schema_publication(pubid)) + return; + + /* + * Dropping a schema from a publication removes all its EXCEPT entries via + * cascade. The concept of "drop all schema tables from the publication + * EXCEPT these ones" is not supported. + */ + if (stmt->action == AP_DropObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); + + /* + * XXX EXCEPT with SET is not currently implemented. Workaround: DROP and + * re-ADD the schema with the desired EXCEPT list. + */ + if (stmt->action == AP_SetObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"), + errhint("Drop and re-add the schema with the desired EXCEPT list."))); + + if (stmt->action == AP_AddObjects) + { + List *rels; + List *explicitrelids; + + rels = OpenTableList(except_pubtables); + + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + /* + * Validate that each excluded table is not also in the explicit table + * list (which would be contradictory). + */ + foreach_ptr(PublicationRelInfo, pri, rels) + { + Oid relid = RelationGetRelid(pri->relation); + + if (list_member_oid(explicitrelids, relid)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" cannot appear in both the table list and the EXCEPT clause", + RelationGetQualifiedRelationName(pri->relation))); + } + + PublicationAddTables(pubid, rels, false, stmt); + + CloseTableList(rels); + } } /* @@ -1786,10 +1885,12 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) errmsg("publication \"%s\" does not exist", stmt->pubname)); - relations = list_concat(relations, except_pubtables); + if (stmt->for_all_tables) + relations = list_concat(relations, except_pubtables); + AlterPublicationTables(stmt, tup, relations, pstate->p_sourcetext, schemaidlist != NIL); - AlterPublicationSchemas(stmt, tup, schemaidlist); + AlterPublicationSchemas(stmt, tup, schemaidlist, except_pubtables); AlterPublicationAllFlags(stmt, rel, tup); } diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c index a0f7f8e2168..85ab3b00875 100644 --- a/src/bin/pg_dump/pg_dump.c +++ b/src/bin/pg_dump/pg_dump.c @@ -5019,6 +5019,7 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) PublicationInfo *pubinfo = pubsinfo->publication; PQExpBuffer query; char *tag; + bool has_except = false; /* Do nothing if not dumping schema */ if (!dopt->dumpSchema) @@ -5029,7 +5030,34 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) query = createPQExpBuffer(); appendPQExpBuffer(query, "ALTER PUBLICATION %s ", fmtId(pubinfo->dobj.name)); - appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s;\n", fmtId(schemainfo->dobj.name)); + appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s", fmtId(schemainfo->dobj.name)); + + /* + * Append EXCEPT clause for any tables that belong to this schema + * and are excluded from the publication. + */ + for (SimplePtrListCell *cell = pubinfo->except_tables.head; cell; cell = cell->next) + { + TableInfo *tbinfo = (TableInfo *) cell->ptr; + + if (strcmp(tbinfo->dobj.namespace->dobj.name, schemainfo->dobj.name) == 0) + { + if (!has_except) + { + appendPQExpBufferStr(query, " EXCEPT ("); + has_except = true; + } + else + appendPQExpBufferStr(query, ", "); + + appendPQExpBuffer(query, "TABLE ONLY %s", fmtId(tbinfo->dobj.name)); + } + } + + if (has_except) + appendPQExpBufferStr(query, ")"); + + appendPQExpBufferStr(query, ";\n"); /* * There is no point in creating drop query as the drop is done by schema diff --git a/src/bin/pg_dump/t/002_pg_dump.pl b/src/bin/pg_dump/t/002_pg_dump.pl index 9258948b583..d18b3b0d7b9 100644 --- a/src/bin/pg_dump/t/002_pg_dump.pl +++ b/src/bin/pg_dump/t/002_pg_dump.pl @@ -3283,6 +3283,30 @@ my %tests = ( like => { %full_runs, section_post_data => 1, }, }, + 'CREATE PUBLICATION pub11' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub11 FOR TABLES IN SCHEMA dump_test EXCEPT (TABLE test_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub11 WITH (publish = 'insert, update, delete, truncate');\E + .*? + \QALTER PUBLICATION pub11 ADD TABLES IN SCHEMA dump_test EXCEPT (TABLE ONLY test_table);\E + /xms, + like => { %full_runs, section_post_data => 1, }, + }, + + 'CREATE PUBLICATION pub12' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub12 FOR TABLES IN SCHEMA dump_test EXCEPT (TABLE test_table, dump_test.test_second_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub12 WITH (publish = 'insert, update, delete, truncate');\E + .*? + \QALTER PUBLICATION pub12 ADD TABLES IN SCHEMA dump_test EXCEPT (TABLE ONLY test_table, TABLE ONLY test_second_table);\E + /xms, + like => { %full_runs, section_post_data => 1, }, + }, + 'CREATE SUBSCRIPTION sub1' => { create_order => 50, create_sql => 'CREATE SUBSCRIPTION sub1 diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index 53bb7c8679b..a290902d61e 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2373,6 +2373,23 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); + /* After a single schema name in ADD context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 6efed0a0cce..c40a8884a8f 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -591,12 +591,42 @@ CREATE PUBLICATION testpub_except_nokw ERROR: syntax error at or near "testpub_nopk" LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); ^ +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; +-- fail: non-existing table in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- fail: EXCEPT table belongs to a different schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 1: ...xcept ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.tes... + ^ +-- fail: TABLE keyword is required for the first entry in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +ERROR: syntax error at or near "testpub_nopk" +LINE 1: ...lter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_no... + ^ +-- ADD: qualified and unqualified names; unqualified is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + "pub_test.testpub_tbl_s2" + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP TABLE pub_test.testpub_parted_s CASCADE; DROP TABLE testpub_nopk, testpub_tbl_s1; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi, testpub_alter_except; --------------------------------------------- -- Tests for publications with SEQUENCES --------------------------------------------- diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 2e79e9e4112..cd5ed06dcad 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -290,12 +290,30 @@ CREATE PUBLICATION testpub_except_partition CREATE PUBLICATION testpub_except_nokw FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; + +-- fail: non-existing table in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- fail: EXCEPT table belongs to a different schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- fail: TABLE keyword is required for the first entry in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + +-- ADD: qualified and unqualified names; unqualified is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); +\dRp+ testpub_alter_except + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP TABLE pub_test.testpub_parted_s CASCADE; DROP TABLE testpub_nopk, testpub_tbl_s1; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi, testpub_alter_except; --------------------------------------------- -- Tests for publications with SEQUENCES diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 18c7b2c1fca..0ba6d6f8bb2 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -347,6 +347,38 @@ is($result, qq(5), $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); +# ============================================ +# ALTER PUBLICATION EXCEPT for TABLES IN SCHEMA +# ============================================ + +# Truncate subscriber tables to remove data accumulated from previous tests. +$node_subscriber->safe_psql('postgres', + 'TRUNCATE sch1.tab_published, sch1.tab_excluded, sch1.parent, sch1.child'); + +# ADD: add a schema with an excepted table; verify the except entry takes effect. +$node_publisher->safe_psql('postgres', "CREATE PUBLICATION sch_pub"); +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub ADD TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_excluded)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(6), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: included table synced'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + # Cleanup schema tables before the multi-publication section. $node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); $node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); -- 2.50.1 (Apple Git-155)
v15-0003-Add-EXCEPT-support-to-ALTER-PUBLICATION-SET-TABL.patch (application/octet-stream, 23.2K) download From a8361418318acb5e9bf639d4ffc9bf889fdbe06a Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Thu, 18 Jun 2026 11:32:32 +0530 Subject: [PATCH v15 3/4] Add EXCEPT support to ALTER PUBLICATION SET TABLES IN SCHEMA Extend AlterPublicationExceptTables() with the AP_SetObjects case, which redefines the publication and replaces the entire EXCEPT list. Syntax: ALTER PUBLICATION pub SET TABLES IN SCHEMA s EXCEPT (TABLE t1); This patch also cleans up EXCEPT entries when a schema is dropped from the publication. --- src/backend/commands/publicationcmds.c | 135 +++++++++++++++++--- src/backend/replication/pgoutput/pgoutput.c | 10 +- src/bin/psql/tab-complete.in.c | 17 +++ src/test/regress/expected/publication.out | 86 +++++++++++++ src/test/regress/sql/publication.sql | 38 ++++++ src/test/subscription/t/037_except.pl | 85 ++++++++++++ 6 files changed, 350 insertions(+), 21 deletions(-) diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index c3ecda2ac91..a63a84b2c26 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -1588,8 +1588,8 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, /* * Increment the command counter so that is_schema_publication() in - * GetExcludedPublicationTables() can see the just-inserted schema - * rows when AlterPublicationSchemaExceptTables runs next. + * GetExcludedPublicationTables() can see the just-inserted schema rows + * when AlterPublicationSchemaExceptTables runs next. */ if (stmt->action == AP_AddObjects || stmt->action == AP_SetObjects) CommandCounterIncrement(); @@ -1607,16 +1607,18 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, */ static void AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, - HeapTuple tup, List *except_pubtables, - List *schemaidlist) + HeapTuple tup, List *except_pubtables, + List *schemaidlist) { Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); Oid pubid = pubform->oid; /* - * Nothing to do if no EXCEPT entries. + * Nothing to do if there are no EXCEPT entries, unless handling the SET + * command, because if the user has removed all exceptions we need to drop + * any existing ones. */ - if (!except_pubtables) + if (!except_pubtables && stmt->action != AP_SetObjects) return; /* @@ -1637,16 +1639,6 @@ AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); - /* - * XXX EXCEPT with SET is not currently implemented. Workaround: DROP and - * re-ADD the schema with the desired EXCEPT list. - */ - if (stmt->action == AP_SetObjects) - ereport(ERROR, - (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"), - errhint("Drop and re-add the schema with the desired EXCEPT list."))); - if (stmt->action == AP_AddObjects) { List *rels; @@ -1674,6 +1666,84 @@ AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, PublicationAddTables(pubid, rels, false, stmt); + CloseTableList(rels); + } + else /* AP_SetObjects */ + { + List *oldexceptrelids = NIL; + List *newexceptrelids = NIL; + List *delrelids = NIL; + List *rels; + List *explicitrelids; + + rels = OpenTableList(except_pubtables); + + /* Collect OIDs of the desired new EXCEPT list. */ + foreach_ptr(PublicationRelInfo, pri, rels) + newexceptrelids = lappend_oid(newexceptrelids, + RelationGetRelid(pri->relation)); + + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + /* + * Validate that each excluded table is not also in the explicit table + * list (which would be contradictory). + */ + foreach_ptr(PublicationRelInfo, pri, rels) + { + Oid relid = RelationGetRelid(pri->relation); + + if (list_member_oid(explicitrelids, relid)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" cannot appear in both the table list and the EXCEPT clause", + RelationGetQualifiedRelationName(pri->relation))); + } + + /* + * Get the current set of EXCEPT entries. Only FOR ALL TABLES and + * schema-level publications can have EXCEPT entries; for any other + * publication type oldexceptrelids stays NIL. + * + * Note: we check is_schema_publication() against the current catalog + * state (before AlterPublicationSchemas has run), so if the caller is + * doing SET TABLE t1 to convert a schema publication into a plain + * table publication, is_schema_publication() still returns true here. + * That is intentional: it lets us discover and clean up any stale + * EXCEPT entries that belong to the old schema definition. + */ + if (GetPublication(pubid)->alltables || is_schema_publication(pubid)) + oldexceptrelids = GetExcludedPublicationTables(pubid, + PUBLICATION_PART_ROOT); + + /* Build a list of old EXCEPT entries not present in the new list. */ + foreach_oid(oldrelid, oldexceptrelids) + { + if (!list_member_oid(newexceptrelids, oldrelid)) + delrelids = lappend_oid(delrelids, oldrelid); + } + + /* Drop old EXCEPT entries not present in the new list. */ + foreach_oid(relid, delrelids) + { + Oid proid; + ObjectAddress obj; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + /* Add new EXCEPT entries, skipping any already present. */ + PublicationAddTables(pubid, rels, true, stmt); + CloseTableList(rels); } } @@ -2372,6 +2442,7 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) foreach(lc, schemas) { Oid schemaid = lfirst_oid(lc); + List *except_relids; psid = GetSysCacheOid2(PUBLICATIONNAMESPACEMAP, Anum_pg_publication_namespace_oid, @@ -2388,8 +2459,40 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) get_namespace_name(schemaid)))); } + /* + * Collect EXCEPT entries for tables belonging to this schema before + * removing the schema entry. + */ + except_relids = GetExcludedPublicationTables(pubid, PUBLICATION_PART_ROOT); + ObjectAddressSet(obj, PublicationNamespaceRelationId, psid); performDeletion(&obj, DROP_CASCADE, 0); + + /* + * Drop any prexcept rows for tables belonging to this schema. These + * rows have no pg_depend entry pointing at the + * pg_publication_namespace row, so they are not cascaded by the + * performDeletion() call above and must be cleaned up explicitly. + */ + foreach_oid(relid, except_relids) + { + Oid proid; + + if (get_rel_namespace(relid) != schemaid) + continue; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + list_free(except_relids); } } diff --git a/src/backend/replication/pgoutput/pgoutput.c b/src/backend/replication/pgoutput/pgoutput.c index 7ee84ec1c83..9831be54b47 100644 --- a/src/backend/replication/pgoutput/pgoutput.c +++ b/src/backend/replication/pgoutput/pgoutput.c @@ -2229,7 +2229,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) */ if (pub->alltables) { - List *exceptpubids = NIL; + List *except_pubids = NIL; if (am_partition) { @@ -2252,7 +2252,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) * clause. Therefore, for a partition, exclusion must be * evaluated at the top-most ancestor. */ - exceptpubids = GetRelationExcludedPublications(last_ancestor_relid); + except_pubids = GetRelationExcludedPublications(last_ancestor_relid); } else { @@ -2260,13 +2260,13 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) * For a regular table or a root partitioned table, check * exclusion on table itself. */ - exceptpubids = GetRelationExcludedPublications(pub_relid); + except_pubids = GetRelationExcludedPublications(pub_relid); } - if (!list_member_oid(exceptpubids, pub->oid)) + if (!list_member_oid(except_pubids, pub->oid)) publish = true; - list_free(exceptpubids); + list_free(except_pubids); if (!publish) continue; diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index a290902d61e..e8bfb36cb1c 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2390,6 +2390,23 @@ match_previous_words(int pattern_id, } else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) COMPLETE_WITH(")"); + /* After a single schema name in SET context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index c40a8884a8f..1bb3c7db2e0 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -621,6 +621,92 @@ Except tables: "pub_test.testpub_tbl_s1" "pub_test.testpub_tbl_s2" +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s2" + +-- fail: table in EXCEPT clause also appears in the explicit table list +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot appear in both the table list and the EXCEPT clause +-- error: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 1: ...xcept SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.tes... + ^ +-- SET: unqualified name in EXCEPT is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- SET without EXCEPT clears the existing except list +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + +-- SET to a different schema removes old schema's EXCEPT entries +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA public; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "public" + +-- fail: nonexistent table in EXCEPT clause (SET path) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- SET: multiple schemas each with their own EXCEPT clause +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- error: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +ERROR: EXCEPT clause is not supported with DROP in ALTER PUBLICATION +-- DROP TABLES IN SCHEMA removes associated EXCEPT entries +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "public" +Except tables: + "public.testpub_tbl1" + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index cd5ed06dcad..6b672ab5b61 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -308,6 +308,44 @@ ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (tes ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); \dRp+ testpub_alter_except +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + +-- fail: table in EXCEPT clause also appears in the explicit table list +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- error: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- SET: unqualified name in EXCEPT is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +\dRp+ testpub_alter_except + +-- SET without EXCEPT clears the existing except list +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + +-- SET to a different schema removes old schema's EXCEPT entries +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA public; +\dRp+ testpub_alter_except + +-- fail: nonexistent table in EXCEPT clause (SET path) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- SET: multiple schemas each with their own EXCEPT clause +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_alter_except + +-- error: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); + +-- DROP TABLES IN SCHEMA removes associated EXCEPT entries +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 0ba6d6f8bb2..01eafb5b7c8 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -376,6 +376,61 @@ $result = is($result, qq(0), 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); +# SET: replace the except list; tab_excluded is now included and tab_published is excluded. +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_published)" +); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (7); + INSERT INTO sch1.tab_excluded VALUES (7); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded WHERE a = 7"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: newly included table is replicated' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published WHERE a = 7"); +is($result, qq(0), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: now-excluded table is not replicated' +); + +# SET without EXCEPT: clears the except list; both tables are now published. +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1"); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (8); + INSERT INTO sch1.tab_excluded VALUES (8); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published WHERE a = 8"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_published replicated after except list cleared' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded WHERE a = 8"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_excluded replicated after except list cleared' +); + $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); @@ -443,6 +498,36 @@ $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); +# OK when a table is excluded by a TABLES IN SCHEMA EXCEPT publication, +# but is included by another publication. +$node_publisher->safe_psql('postgres', 'TRUNCATE tab1'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE tab1'); + +$node_publisher->safe_psql( + 'postgres', qq( + CREATE PUBLICATION tap_pub1 FOR TABLES IN SCHEMA public EXCEPT (TABLE public.tab1); + CREATE PUBLICATION tap_pub2 FOR TABLE tab1; + INSERT INTO tab1 VALUES(1); +)); +$node_subscriber->psql('postgres', + "CREATE SUBSCRIPTION tap_sub CONNECTION '$publisher_connstr' PUBLICATION tap_pub1, tap_pub2" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'tap_sub'); + +$node_publisher->safe_psql('postgres', qq(INSERT INTO tab1 VALUES(2))); +$node_publisher->wait_for_catchup('tap_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT * FROM tab1 ORDER BY a"); +is( $result, qq(1 +2), + "TABLES IN SCHEMA EXCEPT: table excluded in schema pub but included by another pub is replicated" +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); + $node_publisher->stop('fast'); done_testing(); -- 2.50.1 (Apple Git-155)
v15-0004-Documentation-Patch.patch (application/octet-stream, 10.6K) download From 0241dad2264c23c85ae6f52f8cecc12570b5e81e Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Thu, 18 Jun 2026 09:03:08 +0530 Subject: [PATCH v15 4/4] Documentation Patch --- doc/src/sgml/logical-replication.sgml | 3 +- doc/src/sgml/ref/alter_publication.sgml | 68 +++++++++++++++++++++++- doc/src/sgml/ref/create_publication.sgml | 24 +++++++-- 3 files changed, 89 insertions(+), 6 deletions(-) diff --git a/doc/src/sgml/logical-replication.sgml b/doc/src/sgml/logical-replication.sgml index 9e7868487de..1433d2660fe 100644 --- a/doc/src/sgml/logical-replication.sgml +++ b/doc/src/sgml/logical-replication.sgml @@ -117,7 +117,8 @@ or <literal>FOR ALL SEQUENCES</literal>. Unlike tables, sequences can be synchronized at any time. For more information, see <xref linkend="logical-replication-sequences"/>. When a publication is - created with <literal>FOR ALL TABLES</literal>, a table or set of tables can + created with <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal>, a table or set of tables can be explicitly excluded from publication using the <link linkend="sql-createpublication-params-for-except-table"><literal>EXCEPT</literal></link> clause. diff --git a/doc/src/sgml/ref/alter_publication.sgml b/doc/src/sgml/ref/alter_publication.sgml index 52114a16a39..bf6bddcbb6e 100644 --- a/doc/src/sgml/ref/alter_publication.sgml +++ b/doc/src/sgml/ref/alter_publication.sgml @@ -31,7 +31,7 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA <replaceable class="parameter">tables_in_schema</replaceable> [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -47,6 +47,10 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <replaceable class="parameter">table_object</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] [ WHERE ( <replaceable class="parameter">expression</replaceable> ) ] +<phrase>and <replaceable class="parameter">tables_in_schema</replaceable> is:</phrase> + + { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] + <phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> TABLE <replaceable class="parameter">table_object</replaceable> [, ... ] @@ -69,6 +73,9 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r The first two variants modify which tables/schemas are part of the publication. The <literal>ADD</literal> and <literal>DROP</literal> clauses will add and remove one or more tables/schemas from the publication. + The <literal>EXCEPT</literal> clause can be used with + <literal>ADD TABLES IN SCHEMA</literal> to exclude specific tables from a + schema-level publication. </para> <para> @@ -93,7 +100,11 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r used with a publication defined with <literal>FOR TABLE</literal> or <literal>FOR TABLES IN SCHEMA</literal>, replaces the list of tables/schemas in the publication with the specified list; the existing tables or schemas - that were present in the publication will be removed. + that were present in the publication will be removed. When + <literal>SET TABLES IN SCHEMA</literal> is used with an + <literal>EXCEPT</literal> clause, the excluded tables for each schema are + replaced with the specified list; if <literal>EXCEPT</literal> is omitted + for a schema, any existing exclusions for that schema are cleared. </para> <para> @@ -198,6 +209,37 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r </listitem> </varlistentry> + <varlistentry> + <term><literal>EXCEPT</literal></term> + <listitem> + <para> + When used with <literal>ADD TABLES IN SCHEMA</literal> + or <literal>SET TABLES IN SCHEMA</literal>, specifies + tables to be excluded from the publication. Each named + table must belong to the schema specified in the same + <literal>TABLES IN SCHEMA</literal> clause. Table names may be + schema-qualified or unqualified; unqualified names are implicitly + qualified with the schema named in the same clause. See + <xref linkend="sql-createpublication"/> for further details on the + semantics of <literal>EXCEPT</literal>. + </para> + <para> + For <literal>FOR TABLES IN SCHEMA</literal> publications, the + <literal>EXCEPT</literal> clause is schema-scoped. If a table listed in + the <literal>EXCEPT</literal> clause is later moved to a different schema + using <command>ALTER TABLE ... SET SCHEMA</command>, the exclusion is + removed; the table will then be published if its new schema is part of a + publication. If the table is subsequently moved back to the original + schema, the exclusion is not restored, and must be re-established + explicitly using <command>ALTER PUBLICATION</command>. + </para> + <para> + Dropping a table always removes it from the <literal>EXCEPT</literal> + clause. + </para> + </listitem> + </varlistentry> + <varlistentry> <term><literal>SET ( <replaceable class="parameter">publication_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] )</literal></term> <listitem> @@ -288,6 +330,28 @@ ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA marketing, sales; </programlisting> </para> + <para> + Add schema <structname>sales</structname> to the publication + <structname>sales_publication</structname>, excluding the + <structname>sales.internal</structname> and + <structname>sales.drafts</structname> tables: +<programlisting> +ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA sales EXCEPT (TABLE internal, drafts); +</programlisting> + </para> + + <para> + Replace the schema list of <structname>sales_publication</structname> with + <structname>sales</structname>, excluding only + <structname>sales.drafts</structname>. Other than + <structname>sales.drafts</structname>, any previously excluded tables for schema + <structname>sales</structname> are no longer excluded. Any schemas previously in + <structname>sales_publication</structname> are removed: +<programlisting> +ALTER PUBLICATION sales_publication SET TABLES IN SCHEMA sales EXCEPT (TABLE drafts); +</programlisting> + </para> + <para> Add tables <structname>users</structname>, <structname>departments</structname> and schema diff --git a/doc/src/sgml/ref/create_publication.sgml b/doc/src/sgml/ref/create_publication.sgml index 85cfcaddafa..b68206e4fff 100644 --- a/doc/src/sgml/ref/create_publication.sgml +++ b/doc/src/sgml/ref/create_publication.sgml @@ -28,7 +28,7 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA <replaceable class="parameter">tables_in_schema</replaceable> [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -39,6 +39,10 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <replaceable class="parameter">table_object</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] [ WHERE ( <replaceable class="parameter">expression</replaceable> ) ] +<phrase>and <replaceable class="parameter">tables_in_schema</replaceable> is:</phrase> + + { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] + <phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> TABLE <replaceable class="parameter">table_object</replaceable> [, ... ] @@ -142,6 +146,8 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <para> Marks the publication as one that replicates changes for all tables in the specified list of schemas, including tables created in the future. + Tables listed in the <literal>EXCEPT</literal> clause for a given schema + are excluded from the publication. </para> <para> @@ -173,7 +179,7 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <para> Marks the publication as one that replicates changes for all tables in the database, including tables created in the future. Tables listed in - <literal>EXCEPT</literal> clause are excluded from the publication. + the <literal>EXCEPT</literal> clause are excluded from the publication. </para> </listitem> </varlistentry> @@ -198,7 +204,10 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <listitem> <para> This clause specifies a list of tables to be excluded from the - publication. + publication. It can be used with <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal>. For <literal>FOR TABLES IN + SCHEMA</literal>, the exclusion applies only to tables in the schema + associated with the <literal>EXCEPT</literal>. </para> <para> Once a table is excluded, the exclusion applies to that table @@ -521,6 +530,15 @@ CREATE PUBLICATION production_publication FOR TABLE users, departments, TABLES I CREATE PUBLICATION sales_publication FOR TABLES IN SCHEMA marketing, sales; </programlisting></para> + <para> + Create a publication that publishes all changes for all the tables present in + the schema <structname>sales</structname>, except + <structname>internal</structname> and <structname>drafts</structname>: +<programlisting> +CREATE PUBLICATION sales_filtered FOR TABLES IN SCHEMA sales EXCEPT (TABLE internal, drafts); +</programlisting> + </para> + <para> Create a publication that publishes all changes for table <structname>users</structname>, but replicates only columns <structname>user_id</structname> and -- 2.50.1 (Apple Git-155)
^ permalink raw reply [nested|flat] 196+ messages in thread

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-06-22 02:16  Peter Smith <smithpb2250@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: Peter Smith @ 2026-06-22 02:16 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

Hi Nisha.

No further comments for patches v15-0001,0002,0003.

But, here are some comments for v15-0004.

======
doc/src/sgml/ref/alter_publication.sgml

1.
+     <para>
+      For <literal>FOR TABLES IN SCHEMA</literal> publications, the
+      <literal>EXCEPT</literal> clause is schema-scoped.  If a table listed in
+      the <literal>EXCEPT</literal> clause is later moved to a different schema
+      using <command>ALTER TABLE ... SET SCHEMA</command>, the exclusion is
+      removed; the table will then be published if its new schema is part of a
+      publication.  If the table is subsequently moved back to the original
+      schema, the exclusion is not restored, and must be re-established
+      explicitly using <command>ALTER PUBLICATION</command>.
+     </para>

IIRC the recent commit 77b6dd9 that explained about moving tables to
other schemas, was only on the CREATE PUBLICATION page; not on the
ALTER PUBLICATION page.

So either:
(a) maybe this entire paragraph is not needed, or
(b) keep it, but then the behaviour for FOR ALL TABLES also needs to
be described here

======
doc/src/sgml/ref/alter_publication.sgml

2.
Once a table is excluded, the exclusion applies to that table
regardless of its name or schema. Renaming the table or moving it to
another schema using ALTER TABLE ... SET SCHEMA does not remove the
exclusion.

~~

The recent commit 77b6dd9 added the above text to the CREATE
PUBLICATION page. But, that was correct only for "FOR ALL TABLES" --
after your patch we can't say that unconditionally anymore. Also,
since that is mentioned on the CREATE PUBLICATION page, I guess we
need to say something similar about ALL TABLES IN SCHEMA ... EXCEPT in
the same paragraph.

So, maybe something like below:

SUGGESTION
Once a table is excluded under <literal>FOR ALL TABLES</literal>, the
exclusion applies to that table, the exclusion applies to that table
regardless of its name or schema. Renaming the table or moving it to
another schema using <command>ALTER TABLE ... SET SCHEMA</command>
does not remove the exclusion. However, for <literal>FOR TABLES IN
SCHEMA</literal>, because the <literal>EXCEPT</literal> is
schema-scoped, moving a schema-excluded table to another schema does
remove the exclusion.

======
Kind Regards,
Peter Smith.
Fujitsu Australia





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-06-22 12:49  Nisha Moond <nisha.moond412@gmail.com>
  parent: Peter Smith <smithpb2250@gmail.com>
  0 siblings, 2 replies; 196+ messages in thread

From: Nisha Moond @ 2026-06-22 12:49 UTC (permalink / raw)
  To: Peter Smith <smithpb2250@gmail.com>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Mon, Jun 22, 2026 at 7:46 AM Peter Smith <smithpb2250@gmail.com> wrote:
>
> Hi Nisha.
>
> No further comments for patches v15-0001,0002,0003.
>
> But, here are some comments for v15-0004.
>
> ======
> doc/src/sgml/ref/alter_publication.sgml
>
> 1.
> +     <para>
> +      For <literal>FOR TABLES IN SCHEMA</literal> publications, the
> +      <literal>EXCEPT</literal> clause is schema-scoped.  If a table listed in
> +      the <literal>EXCEPT</literal> clause is later moved to a different schema
> +      using <command>ALTER TABLE ... SET SCHEMA</command>, the exclusion is
> +      removed; the table will then be published if its new schema is part of a
> +      publication.  If the table is subsequently moved back to the original
> +      schema, the exclusion is not restored, and must be re-established
> +      explicitly using <command>ALTER PUBLICATION</command>.
> +     </para>
>
> IIRC the recent commit 77b6dd9 that explained about moving tables to
> other schemas, was only on the CREATE PUBLICATION page; not on the
> ALTER PUBLICATION page.
>
> So either:
> (a) maybe this entire paragraph is not needed, or
> (b) keep it, but then the behaviour for FOR ALL TABLES also needs to
> be described here
>
> ======
> doc/src/sgml/ref/alter_publication.sgml
>
> 2.
> Once a table is excluded, the exclusion applies to that table
> regardless of its name or schema. Renaming the table or moving it to
> another schema using ALTER TABLE ... SET SCHEMA does not remove the
> exclusion.
>
> ~~
>
> The recent commit 77b6dd9 added the above text to the CREATE
> PUBLICATION page. But, that was correct only for "FOR ALL TABLES" --
> after your patch we can't say that unconditionally anymore. Also,
> since that is mentioned on the CREATE PUBLICATION page, I guess we
> need to say something similar about ALL TABLES IN SCHEMA ... EXCEPT in
> the same paragraph.
>
> So, maybe something like below:
>
> SUGGESTION
> Once a table is excluded under <literal>FOR ALL TABLES</literal>, the
> exclusion applies to that table, the exclusion applies to that table
> regardless of its name or schema. Renaming the table or moving it to
> another schema using <command>ALTER TABLE ... SET SCHEMA</command>
> does not remove the exclusion. However, for <literal>FOR TABLES IN
> SCHEMA</literal>, because the <literal>EXCEPT</literal> is
> schema-scoped, moving a schema-excluded table to another schema does
> remove the exclusion.
>

Based on the changes in commit 77b6dd9, I re-analyzed the pointed-out paragraph.

On reconsideration, I think the schema-move behavior is really a
property of EXCEPT itself rather than ALTER PUBLICATION. So we can
keep it only in the CREATE PUBLICATION documentation and drop it from
ALTER PUBLICATION to avoid duplication.
We already have a cross-reference in ALTER PUBLICATION: "See CREATE
PUBLICATION for further details on the semantics of EXCEPT", so users
still have a clear path to the detailed behavior description.
I modified your suggestion slightly to keep the information from the
removed paragraph intact.

Attached updated patches v16. No changes in 0001 to 0003.

--
Thanks,
Nisha

Attachments: download all (4 files, .tar.gz)

v16-0001-Support-EXCEPT-clause-for-schema-level-publicati.patch (application/octet-stream, 60.3K) download From 834ae9992f8402fe6d10c8ebae92a690467a113f Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Tue, 16 Jun 2026 10:58:49 +0530 Subject: [PATCH v16 1/4] Support EXCEPT clause for schema-level publications Extend table exclusion support in publications to allow specific tables to be excluded from schema-level publications using an EXCEPT clause in CREATE PUBLICATION. Supported syntax: CREATE PUBLICATION <pub> FOR TABLES IN SCHEMA s EXCEPT (TABLE t1,...); --- src/backend/catalog/pg_publication.c | 161 ++++++++++++++---- src/backend/commands/publicationcmds.c | 146 +++++++++++++++-- src/backend/commands/tablecmds.c | 11 ++ src/backend/parser/gram.y | 54 ++++++- src/backend/replication/pgoutput/pgoutput.c | 30 +++- src/bin/psql/describe.c | 18 +++ src/bin/psql/tab-complete.in.c | 35 +++- src/include/catalog/pg_publication.h | 3 +- src/include/commands/publicationcmds.h | 2 + src/include/nodes/parsenodes.h | 2 + src/test/regress/expected/publication.out | 171 +++++++++++++++++++- src/test/regress/sql/publication.sql | 100 +++++++++++- src/test/subscription/t/037_except.pl | 133 ++++++++++++++- 13 files changed, 813 insertions(+), 53 deletions(-) diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index 5c457d9aca8..4089b505f89 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -444,13 +444,19 @@ GetPubPartitionOptionRelations(List *result, PublicationPartOpt pub_partopt, * * Note that the list of ancestors should be ordered such that the topmost * ancestor is at the end of the list. + * + * except_pubids is a list of publication OIDs whose schema membership + * should be ignored for the ancestor (because the ancestor is in their + * EXCEPT clause). */ Oid -GetTopMostAncestorInPublication(Oid puboid, List *ancestors, int *ancestor_level) +GetTopMostAncestorInPublication(Oid puboid, List *ancestors, + int *ancestor_level, List *except_pubids) { ListCell *lc; Oid topmost_relid = InvalidOid; int level = 0; + bool check_schemas = !list_member_oid(except_pubids, puboid); /* * Find the "topmost" ancestor that is in this publication. @@ -470,7 +476,7 @@ GetTopMostAncestorInPublication(Oid puboid, List *ancestors, int *ancestor_level if (ancestor_level) *ancestor_level = level; } - else + else if (check_schemas) { aschemaPubids = GetSchemaPublications(get_rel_namespace(ancestor)); if (list_member_oid(aschemaPubids, puboid)) @@ -545,18 +551,30 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, * duplicates, it's here just to provide nicer error message in common * case. The real protection is the unique key on the catalog. */ - if (SearchSysCacheExists2(PUBLICATIONRELMAP, ObjectIdGetDatum(relid), - ObjectIdGetDatum(pubid))) + tup = SearchSysCache2(PUBLICATIONRELMAP, ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + + if (HeapTupleIsValid(tup)) { + bool is_except = ((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept; + + ReleaseSysCache(tup); table_close(rel, RowExclusiveLock); if (if_not_exists) return InvalidObjectAddress; - ereport(ERROR, - (errcode(ERRCODE_DUPLICATE_OBJECT), - errmsg("relation \"%s\" is already member of publication \"%s\"", - RelationGetRelationName(targetrel), pub->name))); + if (is_except) + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("table \"%s\" cannot be added because it is excluded from publication \"%s\"", + RelationGetQualifiedRelationName(targetrel), + pub->name))); + else + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("relation \"%s\" is already member of publication \"%s\"", + RelationGetRelationName(targetrel), pub->name))); } check_publication_add_relation(pri); @@ -982,12 +1000,13 @@ GetIncludedPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) * Gets list of table oids that were specified in the EXCEPT clause for a * publication. * - * This should only be used FOR ALL TABLES publications. + * This is used for FOR ALL TABLES and FOR TABLES IN SCHEMA publications, + * both of which support EXCEPT TABLE. */ List * GetExcludedPublicationTables(Oid pubid, PublicationPartOpt pub_partopt) { - Assert(GetPublication(pubid)->alltables); + Assert(GetPublication(pubid)->alltables || is_schema_publication(pubid)); return get_publication_relations(pubid, pub_partopt, true); } @@ -1049,15 +1068,15 @@ GetAllPublicationRelations(Oid pubid, char relkind, bool pubviaroot) TableScanDesc scan; HeapTuple tuple; List *result = NIL; - List *exceptlist = NIL; + List *except_relids = NIL; Assert(!(relkind == RELKIND_SEQUENCE && pubviaroot)); /* EXCEPT filtering applies only to relations, not sequences */ if (relkind == RELKIND_RELATION) - exceptlist = GetExcludedPublicationTables(pubid, pubviaroot ? - PUBLICATION_PART_ROOT : - PUBLICATION_PART_LEAF); + except_relids = GetExcludedPublicationTables(pubid, pubviaroot ? + PUBLICATION_PART_ROOT : + PUBLICATION_PART_LEAF); classRel = table_open(RelationRelationId, AccessShareLock); @@ -1075,7 +1094,7 @@ GetAllPublicationRelations(Oid pubid, char relkind, bool pubviaroot) if (is_publishable_class(relid, relForm) && !(relForm->relispartition && pubviaroot) && - !list_member_oid(exceptlist, relid)) + !list_member_oid(except_relids, relid)) result = lappend_oid(result, relid); } @@ -1097,7 +1116,7 @@ GetAllPublicationRelations(Oid pubid, char relkind, bool pubviaroot) if (is_publishable_class(relid, relForm) && !relForm->relispartition && - !list_member_oid(exceptlist, relid)) + !list_member_oid(except_relids, relid)) result = lappend_oid(result, relid); } @@ -1232,22 +1251,67 @@ GetSchemaPublicationRelations(Oid schemaid, PublicationPartOpt pub_partopt) /* * Gets the list of all relations published by FOR TABLES IN SCHEMA - * publication. + * publication, excluding any tables listed in the EXCEPT clause. */ List * GetAllSchemaPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) { List *result = NIL; List *pubschemalist = GetPublicationSchemas(pubid); + List *except_relids = NIL; ListCell *cell; + /* get the list of tables excluded via EXCEPT TABLE for this publication */ + if (pubschemalist != NIL) + except_relids = GetExcludedPublicationTables(pubid, pub_partopt); + foreach(cell, pubschemalist) { Oid schemaid = lfirst_oid(cell); List *schemaRels = NIL; schemaRels = GetSchemaPublicationRelations(schemaid, pub_partopt); - result = list_concat(result, schemaRels); + + if (except_relids != NIL) + { + /* filter out any tables that appear in the EXCEPT list */ + ListCell *rlc; + + foreach(rlc, schemaRels) + { + Oid relid = lfirst_oid(rlc); + bool excluded = list_member_oid(except_relids, relid); + + /* + * Also exclude any relation whose partition ancestor is in + * the EXCEPT list. This matters when pub_partopt is + * PUBLICATION_PART_ROOT: the except list holds only the root + * OID, but the schema scan may also return individual + * partition relations that live in the same schema. + */ + if (!excluded && get_rel_relispartition(relid)) + { + List *ancestors = get_partition_ancestors(relid); + ListCell *alc; + + foreach(alc, ancestors) + { + if (list_member_oid(except_relids, lfirst_oid(alc))) + { + excluded = true; + break; + } + } + list_free(ancestors); + } + + if (!excluded) + result = lappend_oid(result, relid); + } + list_free(schemaRels); + } + else + result = list_concat(result, schemaRels); } return result; @@ -1324,6 +1388,7 @@ is_table_publishable_in_publication(Oid relid, Publication *pub) { bool relispartition; List *ancestors = NIL; + HeapTuple tup; /* * For non-pubviaroot publications, a partitioned table is never the @@ -1380,20 +1445,62 @@ is_table_publishable_in_publication(Oid relid, Publication *pub) * If it's false, the partition is covered by its ancestor's presence in * the publication, it should be included (return true). */ - if (relispartition && - OidIsValid(GetTopMostAncestorInPublication(pub->oid, ancestors, NULL))) - return !pub->pubviaroot; + if (relispartition) + { + Oid ancestor_oid; + + ancestor_oid = GetTopMostAncestorInPublication(pub->oid, ancestors, NULL, NIL); + if (OidIsValid(ancestor_oid)) + { + /* + * The ancestor was found in the publication (via explicit + * membership or schema membership), but it may be excluded. Check + * for a prexcept row before concluding the partition is + * published. + */ + tup = SearchSysCache2(PUBLICATIONRELMAP, + ObjectIdGetDatum(ancestor_oid), + ObjectIdGetDatum(pub->oid)); + if (HeapTupleIsValid(tup)) + { + bool is_except; + + is_except = ((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept; + ReleaseSysCache(tup); + if (is_except) + return false; + } + return !pub->pubviaroot; + } + } /* * Check whether the table is explicitly published via pg_publication_rel * or pg_publication_namespace. + * + * A pg_publication_rel row with prexcept=true means the table is + * explicitly excluded via EXCEPT and must not be reported as published, + * even if its schema is otherwise included. A row with prexcept=false + * means it is explicitly included. If no pg_publication_rel row exists, + * the table is published iff its schema appears in + * pg_publication_namespace. */ - return (SearchSysCacheExists2(PUBLICATIONRELMAP, - ObjectIdGetDatum(relid), - ObjectIdGetDatum(pub->oid)) || - SearchSysCacheExists2(PUBLICATIONNAMESPACEMAP, - ObjectIdGetDatum(get_rel_namespace(relid)), - ObjectIdGetDatum(pub->oid))); + + tup = SearchSysCache2(PUBLICATIONRELMAP, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pub->oid)); + if (HeapTupleIsValid(tup)) + { + bool is_except; + + is_except = ((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept; + ReleaseSysCache(tup); + return !is_except; + } + + return SearchSysCacheExists2(PUBLICATIONNAMESPACEMAP, + ObjectIdGetDatum(get_rel_namespace(relid)), + ObjectIdGetDatum(pub->oid)); } /* diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 440adb356ad..269f77eeb99 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -181,7 +181,7 @@ parse_publication_options(ParseState *pstate, */ static void ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, - List **rels, List **exceptrels, List **schemas) + List **rels, List **except_pubtables, List **schemas) { ListCell *cell; PublicationObjSpec *pubobj; @@ -200,7 +200,7 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, { case PUBLICATIONOBJ_EXCEPT_TABLE: pubobj->pubtable->except = true; - *exceptrels = lappend(*exceptrels, pubobj->pubtable); + *except_pubtables = lappend(*except_pubtables, pubobj->pubtable); break; case PUBLICATIONOBJ_TABLE: pubobj->pubtable->except = false; @@ -224,6 +224,38 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, /* Filter out duplicates if user specifies "sch1, sch1" */ *schemas = list_append_unique_oid(*schemas, schemaid); + + /* + * Qualify unqualified EXCEPT table names with the resolved + * current schema and reject any explicitly cross-schema + * entries. This mirrors the parse-time handling done for + * TABLES_IN_SCHEMA in preprocess_pubobj_list(), deferred here + * because CURRENT_SCHEMA is not known until execution time. + */ + if (pubobj->except_tables != NIL) + { + char *cur_schema_name = get_namespace_name(schemaid); + + foreach_ptr(PublicationObjSpec, eobj, pubobj->except_tables) + { + const char *eobj_schemaname = + eobj->pubtable->relation->schemaname; + const char *eobj_relname = + eobj->pubtable->relation->relname; + + if (eobj_schemaname == NULL) + eobj->pubtable->relation->schemaname = cur_schema_name; + else if (strcmp(eobj_schemaname, cur_schema_name) != 0) + ereport(ERROR, + errcode(ERRCODE_INVALID_OBJECT_DEFINITION), + errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", + quote_qualified_identifier(eobj_schemaname, eobj_relname), + cur_schema_name)); + + *except_pubtables = lappend(*except_pubtables, + eobj->pubtable); + } + } break; default: /* shouldn't happen */ @@ -305,7 +337,7 @@ pub_rf_contains_invalid_column(Oid pubid, Relation relation, List *ancestors, if (pubviaroot && relation->rd_rel->relispartition) { publish_as_relid - = GetTopMostAncestorInPublication(pubid, ancestors, NULL); + = GetTopMostAncestorInPublication(pubid, ancestors, NULL, NIL); if (!OidIsValid(publish_as_relid)) publish_as_relid = relid; @@ -389,7 +421,7 @@ pub_contains_invalid_column(Oid pubid, Relation relation, List *ancestors, */ if (pubviaroot && relation->rd_rel->relispartition) { - publish_as_relid = GetTopMostAncestorInPublication(pubid, ancestors, NULL); + publish_as_relid = GetTopMostAncestorInPublication(pubid, ancestors, NULL, NIL); if (!OidIsValid(publish_as_relid)) publish_as_relid = relid; @@ -849,7 +881,7 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) char publish_generated_columns; AclResult aclresult; List *relations = NIL; - List *exceptrelations = NIL; + List *except_pubtables = NIL; List *schemaidlist = NIL; /* must have CREATE privilege on database */ @@ -936,16 +968,16 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) /* Associate objects with the publication. */ ObjectsInPublicationToOids(stmt->pubobjects, pstate, &relations, - &exceptrelations, &schemaidlist); + &except_pubtables, &schemaidlist); if (stmt->for_all_tables) { /* Process EXCEPT table list */ - if (exceptrelations != NIL) + if (except_pubtables != NIL) { List *rels; - rels = OpenTableList(exceptrelations); + rels = OpenTableList(except_pubtables); PublicationAddTables(puboid, rels, true, NULL); CloseTableList(rels); } @@ -959,6 +991,8 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) } else if (!stmt->for_all_sequences) { + List *explicitrelids = NIL; + /* FOR TABLES IN SCHEMA requires superuser */ if (schemaidlist != NIL && !superuser()) ereport(ERROR, @@ -977,6 +1011,19 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) schemaidlist != NIL, publish_via_partition_root); + /* + * Collect explicit table OIDs now, before we close the relation + * list, so that except-table validation below can check for + * contradictions without relying on a catalog scan that might not + * yet see the just-inserted rows. + */ + if (except_pubtables != NIL) + { + foreach_ptr(PublicationRelInfo, pri, rels) + explicitrelids = lappend_oid(explicitrelids, + RelationGetRelid(pri->relation)); + } + PublicationAddTables(puboid, rels, true, NULL); CloseTableList(rels); } @@ -989,6 +1036,34 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) */ LockSchemaList(schemaidlist); PublicationAddSchemas(puboid, schemaidlist, true, NULL); + + if (except_pubtables != NIL) + { + List *except_rels; + + except_rels = OpenTableList(except_pubtables); + + /* + * Validate that each excluded table is not also in the + * explicit table list (which would be contradictory). Use the + * in-memory explicitrelids collected above rather than + * re-reading the catalog, which may not yet see the + * just-inserted rows. + */ + foreach_ptr(PublicationRelInfo, pri, except_rels) + { + Oid except_relid = RelationGetRelid(pri->relation); + + if (list_member_oid(explicitrelids, except_relid)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" cannot appear in both the table list and the EXCEPT clause", + RelationGetQualifiedRelationName(pri->relation))); + } + + PublicationAddTables(puboid, except_rels, true, NULL); + CloseTableList(except_rels); + } } } @@ -1683,12 +1758,12 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) else { List *relations = NIL; - List *exceptrelations = NIL; + List *except_pubtables = NIL; List *schemaidlist = NIL; Oid pubid = pubform->oid; ObjectsInPublicationToOids(stmt->pubobjects, pstate, &relations, - &exceptrelations, &schemaidlist); + &except_pubtables, &schemaidlist); CheckAlterPublication(stmt, tup, relations, schemaidlist); @@ -1711,7 +1786,7 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) errmsg("publication \"%s\" does not exist", stmt->pubname)); - relations = list_concat(relations, exceptrelations); + relations = list_concat(relations, except_pubtables); AlterPublicationTables(stmt, tup, relations, pstate->p_sourcetext, schemaidlist != NIL); AlterPublicationSchemas(stmt, tup, schemaidlist); @@ -1829,6 +1904,55 @@ RemovePublicationSchemaById(Oid psoid) table_close(rel, RowExclusiveLock); } +/* + * Remove any EXCEPT clause entries for a relation from schema publications. + * Called when a table changes schema (ALTER TABLE ... SET SCHEMA), so that + * a schema-scoped exclusion does not silently follow the table to its new + * schema. + */ +void +RemoveSchemaPubExceptForRel(Oid relid, Oid oldNspOid, Oid newNspOid) +{ + List *pubids; + + pubids = GetRelationExcludedPublications(relid); + + foreach_oid(pubid, pubids) + { + Oid proid; + + /* + * This problem does not apply to FOR ALL TABLES publications, because + * their EXCEPT clause is publication-scoped, not schema-scoped: the + * exclusion should persist regardless of what schema the table is in. + */ + if (!is_schema_publication(pubid)) + continue; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddress obj; + + ObjectAddressSet(obj, PublicationRelRelationId, proid); + + ereport(DEBUG2, + errmsg_internal("auto-remove exclusion of table \"%s.%s\" from publication \"%s\": table moved to schema \"%s\"", + get_namespace_name(oldNspOid), + get_rel_name(relid), + get_publication_name(pubid, false), + get_namespace_name(newNspOid))); + + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + list_free(pubids); +} + /* * Open relations specified by a PublicationTable list. * The returned tables are locked in ShareUpdateExclusiveLock mode in order to diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 265dcfe7fda..e4c7015bd87 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -63,6 +63,7 @@ #include "commands/event_trigger.h" #include "commands/extension.h" #include "commands/repack.h" +#include "commands/publicationcmds.h" #include "commands/sequence.h" #include "commands/tablecmds.h" #include "commands/tablespace.h" @@ -19290,6 +19291,16 @@ AlterTableNamespaceInternal(Relation rel, Oid oldNspOid, Oid nspOid, AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid, false, objsMoved); + /* + * Remove any EXCEPT clause entries for this relation from schema + * publications. A schema-scoped exclusion is no longer meaningful once + * the table moves to a different schema. + */ + if (rel->rd_rel->relkind == RELKIND_RELATION || + rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE) + RemoveSchemaPubExceptForRel(RelationGetRelid(rel), oldNspOid, + nspOid); + table_close(classRel, RowExclusiveLock); } diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y index ff4e1388c55..6a7a1bc5f8d 100644 --- a/src/backend/parser/gram.y +++ b/src/backend/parser/gram.y @@ -58,6 +58,7 @@ #include "nodes/makefuncs.h" #include "nodes/nodeFuncs.h" #include "parser/parser.h" +#include "utils/builtins.h" #include "utils/datetime.h" #include "utils/xml.h" @@ -11272,7 +11273,7 @@ AlterOwnerStmt: ALTER AGGREGATE aggregate_with_argtypes OWNER TO RoleSpec * pub_obj is one of: * * TABLE table [, ...] - * TABLES IN SCHEMA schema [, ...] + * TABLES IN SCHEMA schema [EXCEPT (TABLE table [, ...] )] [, ...] * *****************************************************************************/ @@ -11332,23 +11333,26 @@ PublicationObjSpec: $$->pubtable->columns = $3; $$->pubtable->whereClause = $4; } - | TABLES IN_P SCHEMA ColId + | TABLES IN_P SCHEMA ColId opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_SCHEMA; $$->name = $4; + $$->except_tables = $5; $$->location = @4; } - | TABLES IN_P SCHEMA CURRENT_SCHEMA + | TABLES IN_P SCHEMA CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_CUR_SCHEMA; + $$->except_tables = $5; $$->location = @4; } - | ColId opt_column_list OptWhereClause + | ColId opt_column_list OptWhereClause opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $4; /* * If either a row filter or column list is specified, create * a PublicationTable object. @@ -11392,10 +11396,11 @@ PublicationObjSpec: $$->pubtable->columns = $2; $$->pubtable->whereClause = $3; } - | CURRENT_SCHEMA + | CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $2; $$->location = @1; } ; @@ -20784,6 +20789,8 @@ preprocess_pub_all_objtype_list(List *all_objects_list, List **pubobjects, /* * Process pubobjspec_list to check for errors in any of the objects and * convert PUBLICATIONOBJ_CONTINUATION into appropriate PublicationObjSpecType. + * Also flattens except_tables from TABLES IN SCHEMA nodes into the list so + * that ObjectsInPublicationToOids() sees them as top-level EXCEPT_TABLE entries. */ static void preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) @@ -20812,6 +20819,13 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLE) { + /* EXCEPT is not valid for table objects */ + if (pubobj->except_tables != NIL) + ereport(ERROR, + errcode(ERRCODE_SYNTAX_ERROR), + errmsg("EXCEPT is not allowed for TABLE publication objects"), + parser_errposition(pubobj->location)); + /* relation name or pubtable must be set for this type of object */ if (!pubobj->name && !pubobj->pubtable) ereport(ERROR, @@ -20860,6 +20874,36 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) errcode(ERRCODE_SYNTAX_ERROR), errmsg("invalid schema name"), parser_errposition(pubobj->location)); + + /* + * For TABLES_IN_SCHEMA, qualify unqualified EXCEPT table names + * with the parent schema and reject cross-schema entries at parse + * time, then flatten into the top-level list. + * + * For TABLES_IN_CUR_SCHEMA the schema name is not yet known, so + * skip both steps here; ObjectsInPublicationToOids() will + * qualify names and validate schema membership at execution time. + */ + if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLES_IN_SCHEMA) + { + foreach_ptr(PublicationObjSpec, eobj, pubobj->except_tables) + { + const char *eobj_schemaname = eobj->pubtable->relation->schemaname; + const char *eobj_relname = eobj->pubtable->relation->relname; + + if (eobj_schemaname == NULL) + eobj->pubtable->relation->schemaname = pubobj->name; + else if (strcmp(eobj_schemaname, pubobj->name) != 0) + ereport(ERROR, + errcode(ERRCODE_INVALID_OBJECT_DEFINITION), + errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", + quote_qualified_identifier(eobj_schemaname, eobj_relname), + pubobj->name), + parser_errposition(eobj->location)); + } + pubobjspec_list = list_concat(pubobjspec_list, pubobj->except_tables); + pubobj->except_tables = NIL; + } } prevobjtype = pubobj->pubobjtype; diff --git a/src/backend/replication/pgoutput/pgoutput.c b/src/backend/replication/pgoutput/pgoutput.c index 4ecfcbff7ab..7ee84ec1c83 100644 --- a/src/backend/replication/pgoutput/pgoutput.c +++ b/src/backend/replication/pgoutput/pgoutput.c @@ -2097,6 +2097,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) * are absorbed while decoding WAL. */ List *schemaPubids = GetSchemaPublications(schemaId); + List *except_pubids; ListCell *lc; Oid publish_as_relid = relid; int publish_ancestor_level = 0; @@ -2104,6 +2105,28 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) char relkind = get_rel_relkind(relid); List *rel_publications = NIL; + /* + * For the schema EXCEPT check, we must look up the top-most ancestor + * rather than the relation itself. check_publication_add_relation() + * prevents individual partitions from appearing in the EXCEPT clause, + * so only a root (non-partition) table can have prexcept = true. + * Using the partition's own OID would always return NIL and miss the + * exclusion. + */ + Oid root_relid; + + if (am_partition) + { + List *ancestors = get_partition_ancestors(relid); + + root_relid = llast_oid(ancestors); + list_free(ancestors); + } + else + root_relid = relid; + + except_pubids = GetRelationExcludedPublications(root_relid); + /* Reload publications if needed before use. */ if (!publications_valid) { @@ -2267,7 +2290,8 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) ancestor = GetTopMostAncestorInPublication(pub->oid, ancestors, - &level); + &level, + except_pubids); if (ancestor != InvalidOid) { @@ -2281,7 +2305,8 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) } if (list_member_oid(pubids, pub->oid) || - list_member_oid(schemaPubids, pub->oid) || + (list_member_oid(schemaPubids, pub->oid) && + !list_member_oid(except_pubids, pub->oid)) || ancestor_published) publish = true; } @@ -2360,6 +2385,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) list_free(pubids); list_free(schemaPubids); + list_free(except_pubids); list_free(rel_publications); entry->replicate_valid = true; diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c index af3935b0078..9470a0bbf5e 100644 --- a/src/bin/psql/describe.c +++ b/src/bin/psql/describe.c @@ -7038,6 +7038,24 @@ describePublications(const char *pattern) if (!addFooterToPublicationDesc(&buf, _("Tables from schemas:"), true, &cont)) goto error_return; + + if (pset.sversion >= 190000) + { + /* + * Get tables in the EXCEPT clause for this schema + * publication. + */ + printfPQExpBuffer(&buf, + "SELECT concat(c.relnamespace::regnamespace, '.', c.relname)\n" + "FROM pg_catalog.pg_class c\n" + " JOIN pg_catalog.pg_publication_rel pr ON c.oid = pr.prrelid\n" + "WHERE pr.prpubid = '%s'\n" + " AND pr.prexcept\n" + "ORDER BY 1", pubid); + if (!addFooterToPublicationDesc(&buf, _("Except tables:"), + true, &cont)) + goto error_return; + } } } else diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index de547a8cb37..53bb7c8679b 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -1065,6 +1065,24 @@ static const SchemaQuery Query_for_trigger_of_table = { "SELECT nspname FROM pg_catalog.pg_namespace "\ " WHERE nspname LIKE '%s'" +#define Query_for_list_of_tables_in_schema \ +"SELECT n.nspname || '.' || c.relname "\ +" FROM pg_catalog.pg_class c "\ +" JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "\ +" WHERE c.relkind IN (" CppAsString2(RELKIND_RELATION) ", " \ + CppAsString2(RELKIND_PARTITIONED_TABLE) ") "\ +" AND (n.nspname || '.' || c.relname) LIKE '%s' "\ +" AND n.nspname = '%s'" + +#define Query_for_list_of_tables_in_current_schema \ +"SELECT c.relname "\ +" FROM pg_catalog.pg_class c "\ +" JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "\ +" WHERE c.relkind IN (" CppAsString2(RELKIND_RELATION) ", " \ + CppAsString2(RELKIND_PARTITIONED_TABLE) ") "\ +" AND c.relname LIKE '%s' "\ +" AND n.nspname = pg_catalog.current_schema()" + /* Use COMPLETE_WITH_QUERY_VERBATIM with these queries for GUC names: */ #define Query_for_list_of_alter_system_set_vars \ "SELECT pg_catalog.lower(name) FROM pg_catalog.pg_settings "\ @@ -3787,8 +3805,21 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); - else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && (!ends_with(prev_wd, ','))) - COMPLETE_WITH("WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE", "WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* Complete "CREATE PUBLICATION <name> [...] WITH" */ else if (Matches("CREATE", "PUBLICATION", MatchAnyN, "WITH", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/include/catalog/pg_publication.h b/src/include/catalog/pg_publication.h index 89b4bb14f62..53e3d7c6f3d 100644 --- a/src/include/catalog/pg_publication.h +++ b/src/include/catalog/pg_publication.h @@ -191,7 +191,8 @@ extern List *GetPubPartitionOptionRelations(List *result, PublicationPartOpt pub_partopt, Oid relid); extern Oid GetTopMostAncestorInPublication(Oid puboid, List *ancestors, - int *ancestor_level); + int *ancestor_level, + List *except_pubids); extern bool is_publishable_relation(Relation rel); extern bool is_schema_publication(Oid pubid); diff --git a/src/include/commands/publicationcmds.h b/src/include/commands/publicationcmds.h index 4cf45c17cc5..fb1703aa675 100644 --- a/src/include/commands/publicationcmds.h +++ b/src/include/commands/publicationcmds.h @@ -27,6 +27,8 @@ extern void AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt); extern void RemovePublicationById(Oid pubid); extern void RemovePublicationRelById(Oid proid); extern void RemovePublicationSchemaById(Oid psoid); +extern void RemoveSchemaPubExceptForRel(Oid relid, Oid oldNspOid, + Oid newNspOid); extern ObjectAddress AlterPublicationOwner(const char *name, Oid newOwnerId); extern void AlterPublicationOwner_oid(Oid pubid, Oid newOwnerId); diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h index 4133c404a6b..1299b0a67a4 100644 --- a/src/include/nodes/parsenodes.h +++ b/src/include/nodes/parsenodes.h @@ -4488,6 +4488,8 @@ typedef struct PublicationObjSpec PublicationObjSpecType pubobjtype; /* type of this publication object */ char *name; PublicationTable *pubtable; + List *except_tables; /* tables specified in the EXCEPT clause (for + * TABLES IN SCHEMA) */ ParseLoc location; /* token location, or -1 if unknown */ } PublicationObjSpec; diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 29e54b214a0..6efed0a0cce 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -270,6 +270,12 @@ CREATE PUBLICATION testpub_foralltables_excepttable2 FOR ALL TABLES EXCEPT (test ERROR: syntax error at or near "testpub_tbl1" LINE 1: ..._foralltables_excepttable2 FOR ALL TABLES EXCEPT (testpub_tb... ^ +-- fail - EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testpub_tbl3); +ERROR: EXCEPT is not allowed for TABLE publication objects +LINE 2: FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testp... + ^ --------------------------------------------- -- SET ALL TABLES/SEQUENCES --------------------------------------------- @@ -470,7 +476,130 @@ HINT: Change the publication's EXCEPT clause using ALTER PUBLICATION ... SET AL RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Create same-named tables in public to verify unqualified EXCEPT entries +-- are qualified with the named schema, not public +CREATE TABLE testpub_nopk (foo int, bar int); +CREATE TABLE testpub_tbl_s1 (a int primary key, b text); +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + Publication testpub_schema_except1 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- Exclude multiple tables using unqualified names; same-named tables exist in +-- public to confirm unqualified names resolve to pub_test, not public +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + Publication testpub_schema_except2 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_nopk" + "pub_test.testpub_tbl_s1" + +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testp... + ^ +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); +ERROR: table "pub_test.testpub_tbl_s1" in EXCEPT clause does not belong to schema "public" +LINE 2: ...R TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.t... + ^ +-- Multiple schemas each with their own EXCEPT clause +CREATE PUBLICATION testpub_schema_except_multi + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_schema_except_multi + Publication testpub_schema_except_multi + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- ALTER TABLE ... SET SCHEMA on a table excluded by a schema publication: +-- the schema-scoped exclusion is no longer meaningful once the table moves +-- out of its schema, so the exclusion is auto-removed. +CREATE PUBLICATION testpub_schema_except_setsch + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_schema_except_setsch + Publication testpub_schema_except_setsch + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s2" + +ALTER TABLE pub_test.testpub_tbl_s2 SET SCHEMA public; +\dRp+ testpub_schema_except_setsch + Publication testpub_schema_except_setsch + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + +DROP PUBLICATION testpub_schema_except_setsch; +-- Restore for further tests +ALTER TABLE public.testpub_tbl_s2 SET SCHEMA pub_test; +-- fail: table appears in both the explicit table list and the EXCEPT clause +CREATE PUBLICATION testpub_except_conflict + FOR TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot appear in both the table list and the EXCEPT clause +-- fail: nonexistent table in EXCEPT clause +CREATE PUBLICATION testpub_except_norel + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- fail: partition cannot appear in EXCEPT clause; only root tables are allowed +CREATE TABLE pub_test.testpub_parted_s (a int) PARTITION BY LIST (a); +CREATE TABLE pub_test.testpub_part_s PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (1); +CREATE PUBLICATION testpub_except_partition + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); +ERROR: cannot specify relation "pub_test.testpub_part_s" in the publication EXCEPT clause +DETAIL: This operation is not supported for individual partitions. +-- fail: TABLE keyword is required for the first entry in the EXCEPT clause +CREATE PUBLICATION testpub_except_nokw + FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +ERROR: syntax error at or near "testpub_nopk" +LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + ^ +-- Cleanup +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP TABLE pub_test.testpub_parted_s CASCADE; +DROP TABLE testpub_nopk, testpub_tbl_s1; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +--------------------------------------------- +-- Tests for publications with SEQUENCES +--------------------------------------------- CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; -- FOR ALL SEQUENCES @@ -1953,6 +2082,27 @@ ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b); ERROR: column specification not allowed for schema LINE 1: ...TION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b)... ^ +-- EXCEPT clause with CURRENT_SCHEMA: cross-schema entry must be rejected +SET search_path = pub_test1; +-- qualified name from wrong schema -> error +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.tbl1); +ERROR: table "pub_test2.tbl1" in EXCEPT clause does not belong to schema "pub_test1" +-- unqualified name implicitly qualified with current schema (pub_test1.tbl) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl); +RESET client_min_messages; +\dRp+ testpub_cursch_except + Publication testpub_cursch_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test1" +Except tables: + "pub_test1.tbl" + +DROP PUBLICATION testpub_cursch_except; +RESET search_path; -- cleanup pub_test1 schema for invalidation tests ALTER PUBLICATION testpub2_forschema DROP TABLES IN SCHEMA pub_test1; DROP PUBLICATION testpub3_forschema, testpub4_forschema, testpub5_forschema, testpub6_forschema, testpub_fortable; @@ -2304,6 +2454,7 @@ DROP ROLE regress_publication_user_dummy; -- Test pg_get_publication_tables(text[], oid) function CREATE SCHEMA gpt_test_sch; CREATE TABLE gpt_test_sch.tbl_sch (id int); +CREATE TABLE gpt_test_sch.tbl_sch2 (id int); CREATE TABLE tbl_normal (id int); CREATE TABLE tbl_parent (id1 int, id2 int, id3 int) PARTITION BY RANGE (id1); CREATE TABLE tbl_part1 PARTITION OF tbl_parent FOR VALUES FROM (1) TO (10); @@ -2314,6 +2465,7 @@ CREATE PUBLICATION pub_all_no_viaroot FOR ALL TABLES WITH (publish_via_partition CREATE PUBLICATION pub_all_except FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = true); CREATE PUBLICATION pub_all_except_no_viaroot FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_schema FOR TABLES IN SCHEMA gpt_test_sch; +CREATE PUBLICATION pub_schema_except FOR TABLES IN SCHEMA gpt_test_sch EXCEPT (TABLE gpt_test_sch.tbl_sch); CREATE PUBLICATION pub_normal FOR TABLE tbl_normal WHERE (id < 10); CREATE PUBLICATION pub_part_leaf FOR TABLE tbl_part1 WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_part_parent FOR TABLE tbl_parent (id1, id2) WHERE (id1 = 10) WITH (publish_via_partition_root = true); @@ -2465,6 +2617,18 @@ SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_part1'); -- no r ---------+---------+-------+------ (0 rows) +-- test for EXCEPT clause with schema publication +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch'); -- no result (excluded) + pubname | relname | attrs | qual +---------+---------+-------+------ +(0 rows) + +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch2'); -- one row (included via schema) + pubname | relname | attrs | qual +-------------------+----------+-------+------ + pub_schema_except | tbl_sch2 | 1 | +(1 row) + -- two rows with different row filter SELECT * FROM test_gpt(ARRAY['pub_all', 'pub_normal'], 'tbl_normal'); pubname | relname | attrs | qual @@ -2517,6 +2681,7 @@ DROP PUBLICATION pub_all_no_viaroot; DROP PUBLICATION pub_all_except; DROP PUBLICATION pub_all_except_no_viaroot; DROP PUBLICATION pub_schema; +DROP PUBLICATION pub_schema_except; DROP PUBLICATION pub_normal; DROP PUBLICATION pub_part_leaf; DROP PUBLICATION pub_part_parent; @@ -2525,7 +2690,9 @@ DROP PUBLICATION pub_part_parent_child; DROP VIEW gpt_test_view; DROP TABLE tbl_normal, tbl_parent, tbl_part1; DROP SCHEMA gpt_test_sch CASCADE; -NOTICE: drop cascades to table gpt_test_sch.tbl_sch +NOTICE: drop cascades to 2 other objects +DETAIL: drop cascades to table gpt_test_sch.tbl_sch +drop cascades to table gpt_test_sch.tbl_sch2 -- stage objects for pg_dump tests CREATE SCHEMA pubme CREATE TABLE t0 (c int, d int) CREATE TABLE t1 (c int); CREATE SCHEMA pubme2 CREATE TABLE t0 (c int, d int); diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 041e14a4de6..2e79e9e4112 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -123,6 +123,9 @@ CREATE PUBLICATION testpub_foralltables_excepttable1 FOR ALL TABLES EXCEPT (TABL \d testpub_tbl1 -- fail - first table in the EXCEPT list should use TABLE keyword CREATE PUBLICATION testpub_foralltables_excepttable2 FOR ALL TABLES EXCEPT (testpub_tbl1, testpub_tbl2); +-- fail - EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testpub_tbl3); --------------------------------------------- -- SET ALL TABLES/SEQUENCES @@ -220,7 +223,83 @@ RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Create same-named tables in public to verify unqualified EXCEPT entries +-- are qualified with the named schema, not public +CREATE TABLE testpub_nopk (foo int, bar int); +CREATE TABLE testpub_tbl_s1 (a int primary key, b text); + +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + +-- Exclude multiple tables using unqualified names; same-named tables exist in +-- public to confirm unqualified names resolve to pub_test, not public +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); + +-- Multiple schemas each with their own EXCEPT clause +CREATE PUBLICATION testpub_schema_except_multi + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_schema_except_multi + +-- ALTER TABLE ... SET SCHEMA on a table excluded by a schema publication: +-- the schema-scoped exclusion is no longer meaningful once the table moves +-- out of its schema, so the exclusion is auto-removed. +CREATE PUBLICATION testpub_schema_except_setsch + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_schema_except_setsch +ALTER TABLE pub_test.testpub_tbl_s2 SET SCHEMA public; +\dRp+ testpub_schema_except_setsch +DROP PUBLICATION testpub_schema_except_setsch; +-- Restore for further tests +ALTER TABLE public.testpub_tbl_s2 SET SCHEMA pub_test; + +-- fail: table appears in both the explicit table list and the EXCEPT clause +CREATE PUBLICATION testpub_except_conflict + FOR TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: nonexistent table in EXCEPT clause +CREATE PUBLICATION testpub_except_norel + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- fail: partition cannot appear in EXCEPT clause; only root tables are allowed +CREATE TABLE pub_test.testpub_parted_s (a int) PARTITION BY LIST (a); +CREATE TABLE pub_test.testpub_part_s PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (1); +CREATE PUBLICATION testpub_except_partition + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); + +-- fail: TABLE keyword is required for the first entry in the EXCEPT clause +CREATE PUBLICATION testpub_except_nokw + FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + +-- Cleanup +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP TABLE pub_test.testpub_parted_s CASCADE; +DROP TABLE testpub_nopk, testpub_tbl_s1; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; + +--------------------------------------------- +-- Tests for publications with SEQUENCES +--------------------------------------------- CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; @@ -1189,6 +1268,18 @@ ALTER PUBLICATION testpub1_forschema SET TABLES IN SCHEMA pub_test1, pub_test1; ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo (a, b); ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b); +-- EXCEPT clause with CURRENT_SCHEMA: cross-schema entry must be rejected +SET search_path = pub_test1; +-- qualified name from wrong schema -> error +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.tbl1); +-- unqualified name implicitly qualified with current schema (pub_test1.tbl) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl); +RESET client_min_messages; +\dRp+ testpub_cursch_except +DROP PUBLICATION testpub_cursch_except; +RESET search_path; + -- cleanup pub_test1 schema for invalidation tests ALTER PUBLICATION testpub2_forschema DROP TABLES IN SCHEMA pub_test1; DROP PUBLICATION testpub3_forschema, testpub4_forschema, testpub5_forschema, testpub6_forschema, testpub_fortable; @@ -1443,6 +1534,7 @@ DROP ROLE regress_publication_user_dummy; -- Test pg_get_publication_tables(text[], oid) function CREATE SCHEMA gpt_test_sch; CREATE TABLE gpt_test_sch.tbl_sch (id int); +CREATE TABLE gpt_test_sch.tbl_sch2 (id int); CREATE TABLE tbl_normal (id int); CREATE TABLE tbl_parent (id1 int, id2 int, id3 int) PARTITION BY RANGE (id1); CREATE TABLE tbl_part1 PARTITION OF tbl_parent FOR VALUES FROM (1) TO (10); @@ -1454,6 +1546,7 @@ CREATE PUBLICATION pub_all_no_viaroot FOR ALL TABLES WITH (publish_via_partition CREATE PUBLICATION pub_all_except FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = true); CREATE PUBLICATION pub_all_except_no_viaroot FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_schema FOR TABLES IN SCHEMA gpt_test_sch; +CREATE PUBLICATION pub_schema_except FOR TABLES IN SCHEMA gpt_test_sch EXCEPT (TABLE gpt_test_sch.tbl_sch); CREATE PUBLICATION pub_normal FOR TABLE tbl_normal WHERE (id < 10); CREATE PUBLICATION pub_part_leaf FOR TABLE tbl_part1 WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_part_parent FOR TABLE tbl_parent (id1, id2) WHERE (id1 = 10) WITH (publish_via_partition_root = true); @@ -1510,6 +1603,10 @@ SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'gpt_test_sch.tbl_sch SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_parent'); -- no result (excluded) SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_part1'); -- no result +-- test for EXCEPT clause with schema publication +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch'); -- no result (excluded) +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch2'); -- one row (included via schema) + -- two rows with different row filter SELECT * FROM test_gpt(ARRAY['pub_all', 'pub_normal'], 'tbl_normal'); @@ -1538,6 +1635,7 @@ DROP PUBLICATION pub_all_no_viaroot; DROP PUBLICATION pub_all_except; DROP PUBLICATION pub_all_except_no_viaroot; DROP PUBLICATION pub_schema; +DROP PUBLICATION pub_schema_except; DROP PUBLICATION pub_normal; DROP PUBLICATION pub_part_leaf; DROP PUBLICATION pub_part_parent; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 8c58d282eee..18c7b2c1fca 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -24,14 +24,17 @@ my $result; sub test_except_root_partition { - my ($pubviaroot) = @_; + my ($pubviaroot, $pubsql) = @_; + $pubsql //= + "CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1)"; + $pubsql .= " WITH (publish_via_partition_root = $pubviaroot)"; # If the root partitioned table is in the EXCEPT clause, all its # partitions are excluded from publication, regardless of the # publish_via_partition_root setting. $node_publisher->safe_psql( 'postgres', qq( - CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1) WITH (publish_via_partition_root = $pubviaroot); + $pubsql; INSERT INTO root1 VALUES (1), (101); )); $node_subscriber->safe_psql('postgres', @@ -223,6 +226,131 @@ $node_subscriber->safe_psql( test_except_root_partition('false'); test_except_root_partition('true'); +# Same validation using TABLES IN SCHEMA instead of FOR ALL TABLES. +my $schema_pub = + "CREATE PUBLICATION tap_pub_part FOR TABLES IN SCHEMA public EXCEPT (TABLE public.root1)"; +test_except_root_partition('false', $schema_pub); +test_except_root_partition('true', $schema_pub); + +# ============================================ +# EXCEPT test cases for TABLES IN SCHEMA +# ============================================ + +# Create a dedicated schema with two tables: one to be published and one to be +# excluded. Also create inherited tables to verify ONLY semantics. +$node_publisher->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_published AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.tab_excluded AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.parent (a int); + CREATE TABLE sch1.child (b int) INHERITS (sch1.parent); +)); + +$node_subscriber->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_published (a int); + CREATE TABLE sch1.tab_excluded (a int); + CREATE TABLE sch1.parent (a int); + CREATE TABLE sch1.child (b int) INHERITS (sch1.parent); +)); + +# Basic test: initial sync respects EXCEPT. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_excluded)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: initial sync copies included table'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: initial sync skips excluded table'); + +# DML: only the included table should be replicated. +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (6); + INSERT INTO sch1.tab_excluded VALUES (6); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(6), + 'TABLES IN SCHEMA EXCEPT: DML on included table is replicated'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: DML on excluded table is not replicated'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Inherited tables: excluding the parent (without ONLY) also excludes the child. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.parent)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.child VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.child"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: excluding parent (without ONLY) also excludes child' +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Test that EXCEPT (TABLE ONLY parent) excludes only the parent itself, not its +# child. Truncate child first so rows from the previous test are not copied by +# the initial table sync of the next subscription. +$node_publisher->safe_psql('postgres', 'TRUNCATE sch1.child'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE sch1.child'); +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE ONLY sch1.parent)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.child VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.child"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: ONLY parent in EXCEPT does not exclude child'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Cleanup schema tables before the multi-publication section. +$node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); +$node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); + # ============================================ # Test when a subscription is subscribing to multiple publications # ============================================ @@ -254,6 +382,7 @@ $node_publisher->safe_psql( DROP PUBLICATION tap_pub2; TRUNCATE tab1; )); +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_subscriber->safe_psql('postgres', qq(TRUNCATE tab1)); # OK when a table is excluded by pub1 EXCEPT clause, but it is included by pub2 -- 2.50.1 (Apple Git-155)
v16-0002-Add-EXCEPT-support-to-ALTER-PUBLICATION-ADD-TABL.patch (application/octet-stream, 18.6K) download From 5284e2f9fab74e974f5b094c3a962e3ef8ae3c19 Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Thu, 18 Jun 2026 11:30:14 +0530 Subject: [PATCH v16 2/4] Add EXCEPT support to ALTER PUBLICATION ADD TABLES IN SCHEMA Extend the EXCEPT clause support to allow tables to be excluded when adding a schema to a publication via ALTER PUBLICATION ... ADD. Syntax: ALTER PUBLICATION pub ADD TABLES IN SCHEMA s EXCEPT (TABLE s.t1); Since pg_dump uses ALTER PUBLICATION ... ADD, support for it is included in this patch. --- src/backend/catalog/pg_publication.c | 19 ++-- src/backend/commands/publicationcmds.c | 107 +++++++++++++++++++++- src/bin/pg_dump/pg_dump.c | 30 +++++- src/bin/pg_dump/t/002_pg_dump.pl | 24 +++++ src/bin/psql/tab-complete.in.c | 17 ++++ src/test/regress/expected/publication.out | 32 ++++++- src/test/regress/sql/publication.sql | 20 +++- src/test/subscription/t/037_except.pl | 32 +++++++ 8 files changed, 267 insertions(+), 14 deletions(-) diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index 4089b505f89..d1ff8839037 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -649,15 +649,18 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, * here, as CreatePublication() function invalidates all relations as part * of defining a FOR ALL TABLES publication. * - * For ALTER PUBLICATION, invalidation is needed only when adding an - * EXCEPT table to a publication already marked as ALL TABLES. For - * publications that were originally empty or defined as ALL SEQUENCES and - * are being converted to ALL TABLES, invalidation is skipped here, as - * AlterPublicationAllFlags() function invalidates all relations while - * marking the publication as ALL TABLES publication. + * For ALTER PUBLICATION, invalidation is needed when adding an EXCEPT + * table to either a FOR ALL TABLES publication (pub->alltables is true) + * or a FOR TABLES IN SCHEMA publication (is_schema_publication is true). + * The exception: when a publication is being converted to FOR ALL TABLES + * (pub->alltables is still false at this point), + * AlterPublicationAllFlags() will perform a full invalidation, so we skip + * it here. */ - inval_except_table = (alter_stmt != NULL) && pub->alltables && - (alter_stmt->for_all_tables && pri->except); + inval_except_table = (alter_stmt != NULL) && pri->except && + (pub->alltables + ? alter_stmt->for_all_tables + : is_schema_publication(pubid)); if (!pri->except || inval_except_table) { diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 269f77eeb99..c3ecda2ac91 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -70,6 +70,13 @@ static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok); static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); +static void AlterPublicationSchemas(AlterPublicationStmt *stmt, + HeapTuple tup, List *schemaidlist, + List *except_pubtables); +static void AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, + List *except_pubtables, + List *schemaidlist); static char defGetGeneratedColsOption(DefElem *def); @@ -1500,7 +1507,8 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, */ static void AlterPublicationSchemas(AlterPublicationStmt *stmt, - HeapTuple tup, List *schemaidlist) + HeapTuple tup, List *schemaidlist, + List *except_pubtables) { Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); @@ -1577,6 +1585,97 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, */ PublicationAddSchemas(pubform->oid, schemaidlist, true, stmt); } + + /* + * Increment the command counter so that is_schema_publication() in + * GetExcludedPublicationTables() can see the just-inserted schema + * rows when AlterPublicationSchemaExceptTables runs next. + */ + if (stmt->action == AP_AddObjects || stmt->action == AP_SetObjects) + CommandCounterIncrement(); + + AlterPublicationSchemaExceptTables(stmt, tup, except_pubtables, schemaidlist); +} + +/* + * Alter the EXCEPT list of a schema-level publication. + * + * Adds, removes, or replaces except-table entries in pg_publication_rel + * (rows with prexcept = true). These entries suppress publication of the + * named tables that would otherwise be covered by a FOR TABLES IN SCHEMA + * clause. + */ +static void +AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, List *except_pubtables, + List *schemaidlist) +{ + Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); + Oid pubid = pubform->oid; + + /* + * Nothing to do if no EXCEPT entries. + */ + if (!except_pubtables) + return; + + /* + * This function handles EXCEPT entries for schema-level publications + * only. For FOR ALL TABLES publications, EXCEPT entries are already + * processed by AlterPublicationTables(). + */ + if (schemaidlist == NIL && !is_schema_publication(pubid)) + return; + + /* + * Dropping a schema from a publication removes all its EXCEPT entries via + * cascade. The concept of "drop all schema tables from the publication + * EXCEPT these ones" is not supported. + */ + if (stmt->action == AP_DropObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); + + /* + * XXX EXCEPT with SET is not currently implemented. Workaround: DROP and + * re-ADD the schema with the desired EXCEPT list. + */ + if (stmt->action == AP_SetObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"), + errhint("Drop and re-add the schema with the desired EXCEPT list."))); + + if (stmt->action == AP_AddObjects) + { + List *rels; + List *explicitrelids; + + rels = OpenTableList(except_pubtables); + + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + /* + * Validate that each excluded table is not also in the explicit table + * list (which would be contradictory). + */ + foreach_ptr(PublicationRelInfo, pri, rels) + { + Oid relid = RelationGetRelid(pri->relation); + + if (list_member_oid(explicitrelids, relid)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" cannot appear in both the table list and the EXCEPT clause", + RelationGetQualifiedRelationName(pri->relation))); + } + + PublicationAddTables(pubid, rels, false, stmt); + + CloseTableList(rels); + } } /* @@ -1786,10 +1885,12 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) errmsg("publication \"%s\" does not exist", stmt->pubname)); - relations = list_concat(relations, except_pubtables); + if (stmt->for_all_tables) + relations = list_concat(relations, except_pubtables); + AlterPublicationTables(stmt, tup, relations, pstate->p_sourcetext, schemaidlist != NIL); - AlterPublicationSchemas(stmt, tup, schemaidlist); + AlterPublicationSchemas(stmt, tup, schemaidlist, except_pubtables); AlterPublicationAllFlags(stmt, rel, tup); } diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c index c56437d6057..c2b2b88bb6c 100644 --- a/src/bin/pg_dump/pg_dump.c +++ b/src/bin/pg_dump/pg_dump.c @@ -5019,6 +5019,7 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) PublicationInfo *pubinfo = pubsinfo->publication; PQExpBuffer query; char *tag; + bool has_except = false; /* Do nothing if not dumping schema */ if (!dopt->dumpSchema) @@ -5029,7 +5030,34 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) query = createPQExpBuffer(); appendPQExpBuffer(query, "ALTER PUBLICATION %s ", fmtId(pubinfo->dobj.name)); - appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s;\n", fmtId(schemainfo->dobj.name)); + appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s", fmtId(schemainfo->dobj.name)); + + /* + * Append EXCEPT clause for any tables that belong to this schema + * and are excluded from the publication. + */ + for (SimplePtrListCell *cell = pubinfo->except_tables.head; cell; cell = cell->next) + { + TableInfo *tbinfo = (TableInfo *) cell->ptr; + + if (strcmp(tbinfo->dobj.namespace->dobj.name, schemainfo->dobj.name) == 0) + { + if (!has_except) + { + appendPQExpBufferStr(query, " EXCEPT ("); + has_except = true; + } + else + appendPQExpBufferStr(query, ", "); + + appendPQExpBuffer(query, "TABLE ONLY %s", fmtId(tbinfo->dobj.name)); + } + } + + if (has_except) + appendPQExpBufferStr(query, ")"); + + appendPQExpBufferStr(query, ";\n"); /* * There is no point in creating drop query as the drop is done by schema diff --git a/src/bin/pg_dump/t/002_pg_dump.pl b/src/bin/pg_dump/t/002_pg_dump.pl index 9258948b583..d18b3b0d7b9 100644 --- a/src/bin/pg_dump/t/002_pg_dump.pl +++ b/src/bin/pg_dump/t/002_pg_dump.pl @@ -3283,6 +3283,30 @@ my %tests = ( like => { %full_runs, section_post_data => 1, }, }, + 'CREATE PUBLICATION pub11' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub11 FOR TABLES IN SCHEMA dump_test EXCEPT (TABLE test_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub11 WITH (publish = 'insert, update, delete, truncate');\E + .*? + \QALTER PUBLICATION pub11 ADD TABLES IN SCHEMA dump_test EXCEPT (TABLE ONLY test_table);\E + /xms, + like => { %full_runs, section_post_data => 1, }, + }, + + 'CREATE PUBLICATION pub12' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub12 FOR TABLES IN SCHEMA dump_test EXCEPT (TABLE test_table, dump_test.test_second_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub12 WITH (publish = 'insert, update, delete, truncate');\E + .*? + \QALTER PUBLICATION pub12 ADD TABLES IN SCHEMA dump_test EXCEPT (TABLE ONLY test_table, TABLE ONLY test_second_table);\E + /xms, + like => { %full_runs, section_post_data => 1, }, + }, + 'CREATE SUBSCRIPTION sub1' => { create_order => 50, create_sql => 'CREATE SUBSCRIPTION sub1 diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index 53bb7c8679b..a290902d61e 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2373,6 +2373,23 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); + /* After a single schema name in ADD context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 6efed0a0cce..c40a8884a8f 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -591,12 +591,42 @@ CREATE PUBLICATION testpub_except_nokw ERROR: syntax error at or near "testpub_nopk" LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); ^ +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; +-- fail: non-existing table in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- fail: EXCEPT table belongs to a different schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 1: ...xcept ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.tes... + ^ +-- fail: TABLE keyword is required for the first entry in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +ERROR: syntax error at or near "testpub_nopk" +LINE 1: ...lter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_no... + ^ +-- ADD: qualified and unqualified names; unqualified is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + "pub_test.testpub_tbl_s2" + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP TABLE pub_test.testpub_parted_s CASCADE; DROP TABLE testpub_nopk, testpub_tbl_s1; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi, testpub_alter_except; --------------------------------------------- -- Tests for publications with SEQUENCES --------------------------------------------- diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 2e79e9e4112..cd5ed06dcad 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -290,12 +290,30 @@ CREATE PUBLICATION testpub_except_partition CREATE PUBLICATION testpub_except_nokw FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; + +-- fail: non-existing table in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- fail: EXCEPT table belongs to a different schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- fail: TABLE keyword is required for the first entry in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + +-- ADD: qualified and unqualified names; unqualified is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); +\dRp+ testpub_alter_except + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP TABLE pub_test.testpub_parted_s CASCADE; DROP TABLE testpub_nopk, testpub_tbl_s1; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi, testpub_alter_except; --------------------------------------------- -- Tests for publications with SEQUENCES diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 18c7b2c1fca..0ba6d6f8bb2 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -347,6 +347,38 @@ is($result, qq(5), $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); +# ============================================ +# ALTER PUBLICATION EXCEPT for TABLES IN SCHEMA +# ============================================ + +# Truncate subscriber tables to remove data accumulated from previous tests. +$node_subscriber->safe_psql('postgres', + 'TRUNCATE sch1.tab_published, sch1.tab_excluded, sch1.parent, sch1.child'); + +# ADD: add a schema with an excepted table; verify the except entry takes effect. +$node_publisher->safe_psql('postgres', "CREATE PUBLICATION sch_pub"); +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub ADD TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_excluded)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(6), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: included table synced'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + # Cleanup schema tables before the multi-publication section. $node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); $node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); -- 2.50.1 (Apple Git-155)
v16-0003-Add-EXCEPT-support-to-ALTER-PUBLICATION-SET-TABL.patch (application/octet-stream, 23.2K) download From 1b85e4874ec3a8f0eba3f6f2ddf32dc61decd96b Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Thu, 18 Jun 2026 11:32:32 +0530 Subject: [PATCH v16 3/4] Add EXCEPT support to ALTER PUBLICATION SET TABLES IN SCHEMA Extend AlterPublicationExceptTables() with the AP_SetObjects case, which redefines the publication and replaces the entire EXCEPT list. Syntax: ALTER PUBLICATION pub SET TABLES IN SCHEMA s EXCEPT (TABLE t1); This patch also cleans up EXCEPT entries when a schema is dropped from the publication. --- src/backend/commands/publicationcmds.c | 135 +++++++++++++++++--- src/backend/replication/pgoutput/pgoutput.c | 10 +- src/bin/psql/tab-complete.in.c | 17 +++ src/test/regress/expected/publication.out | 86 +++++++++++++ src/test/regress/sql/publication.sql | 38 ++++++ src/test/subscription/t/037_except.pl | 85 ++++++++++++ 6 files changed, 350 insertions(+), 21 deletions(-) diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index c3ecda2ac91..a63a84b2c26 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -1588,8 +1588,8 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, /* * Increment the command counter so that is_schema_publication() in - * GetExcludedPublicationTables() can see the just-inserted schema - * rows when AlterPublicationSchemaExceptTables runs next. + * GetExcludedPublicationTables() can see the just-inserted schema rows + * when AlterPublicationSchemaExceptTables runs next. */ if (stmt->action == AP_AddObjects || stmt->action == AP_SetObjects) CommandCounterIncrement(); @@ -1607,16 +1607,18 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, */ static void AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, - HeapTuple tup, List *except_pubtables, - List *schemaidlist) + HeapTuple tup, List *except_pubtables, + List *schemaidlist) { Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); Oid pubid = pubform->oid; /* - * Nothing to do if no EXCEPT entries. + * Nothing to do if there are no EXCEPT entries, unless handling the SET + * command, because if the user has removed all exceptions we need to drop + * any existing ones. */ - if (!except_pubtables) + if (!except_pubtables && stmt->action != AP_SetObjects) return; /* @@ -1637,16 +1639,6 @@ AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); - /* - * XXX EXCEPT with SET is not currently implemented. Workaround: DROP and - * re-ADD the schema with the desired EXCEPT list. - */ - if (stmt->action == AP_SetObjects) - ereport(ERROR, - (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"), - errhint("Drop and re-add the schema with the desired EXCEPT list."))); - if (stmt->action == AP_AddObjects) { List *rels; @@ -1674,6 +1666,84 @@ AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, PublicationAddTables(pubid, rels, false, stmt); + CloseTableList(rels); + } + else /* AP_SetObjects */ + { + List *oldexceptrelids = NIL; + List *newexceptrelids = NIL; + List *delrelids = NIL; + List *rels; + List *explicitrelids; + + rels = OpenTableList(except_pubtables); + + /* Collect OIDs of the desired new EXCEPT list. */ + foreach_ptr(PublicationRelInfo, pri, rels) + newexceptrelids = lappend_oid(newexceptrelids, + RelationGetRelid(pri->relation)); + + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + /* + * Validate that each excluded table is not also in the explicit table + * list (which would be contradictory). + */ + foreach_ptr(PublicationRelInfo, pri, rels) + { + Oid relid = RelationGetRelid(pri->relation); + + if (list_member_oid(explicitrelids, relid)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" cannot appear in both the table list and the EXCEPT clause", + RelationGetQualifiedRelationName(pri->relation))); + } + + /* + * Get the current set of EXCEPT entries. Only FOR ALL TABLES and + * schema-level publications can have EXCEPT entries; for any other + * publication type oldexceptrelids stays NIL. + * + * Note: we check is_schema_publication() against the current catalog + * state (before AlterPublicationSchemas has run), so if the caller is + * doing SET TABLE t1 to convert a schema publication into a plain + * table publication, is_schema_publication() still returns true here. + * That is intentional: it lets us discover and clean up any stale + * EXCEPT entries that belong to the old schema definition. + */ + if (GetPublication(pubid)->alltables || is_schema_publication(pubid)) + oldexceptrelids = GetExcludedPublicationTables(pubid, + PUBLICATION_PART_ROOT); + + /* Build a list of old EXCEPT entries not present in the new list. */ + foreach_oid(oldrelid, oldexceptrelids) + { + if (!list_member_oid(newexceptrelids, oldrelid)) + delrelids = lappend_oid(delrelids, oldrelid); + } + + /* Drop old EXCEPT entries not present in the new list. */ + foreach_oid(relid, delrelids) + { + Oid proid; + ObjectAddress obj; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + /* Add new EXCEPT entries, skipping any already present. */ + PublicationAddTables(pubid, rels, true, stmt); + CloseTableList(rels); } } @@ -2372,6 +2442,7 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) foreach(lc, schemas) { Oid schemaid = lfirst_oid(lc); + List *except_relids; psid = GetSysCacheOid2(PUBLICATIONNAMESPACEMAP, Anum_pg_publication_namespace_oid, @@ -2388,8 +2459,40 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) get_namespace_name(schemaid)))); } + /* + * Collect EXCEPT entries for tables belonging to this schema before + * removing the schema entry. + */ + except_relids = GetExcludedPublicationTables(pubid, PUBLICATION_PART_ROOT); + ObjectAddressSet(obj, PublicationNamespaceRelationId, psid); performDeletion(&obj, DROP_CASCADE, 0); + + /* + * Drop any prexcept rows for tables belonging to this schema. These + * rows have no pg_depend entry pointing at the + * pg_publication_namespace row, so they are not cascaded by the + * performDeletion() call above and must be cleaned up explicitly. + */ + foreach_oid(relid, except_relids) + { + Oid proid; + + if (get_rel_namespace(relid) != schemaid) + continue; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + list_free(except_relids); } } diff --git a/src/backend/replication/pgoutput/pgoutput.c b/src/backend/replication/pgoutput/pgoutput.c index 7ee84ec1c83..9831be54b47 100644 --- a/src/backend/replication/pgoutput/pgoutput.c +++ b/src/backend/replication/pgoutput/pgoutput.c @@ -2229,7 +2229,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) */ if (pub->alltables) { - List *exceptpubids = NIL; + List *except_pubids = NIL; if (am_partition) { @@ -2252,7 +2252,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) * clause. Therefore, for a partition, exclusion must be * evaluated at the top-most ancestor. */ - exceptpubids = GetRelationExcludedPublications(last_ancestor_relid); + except_pubids = GetRelationExcludedPublications(last_ancestor_relid); } else { @@ -2260,13 +2260,13 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) * For a regular table or a root partitioned table, check * exclusion on table itself. */ - exceptpubids = GetRelationExcludedPublications(pub_relid); + except_pubids = GetRelationExcludedPublications(pub_relid); } - if (!list_member_oid(exceptpubids, pub->oid)) + if (!list_member_oid(except_pubids, pub->oid)) publish = true; - list_free(exceptpubids); + list_free(except_pubids); if (!publish) continue; diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index a290902d61e..e8bfb36cb1c 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2390,6 +2390,23 @@ match_previous_words(int pattern_id, } else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) COMPLETE_WITH(")"); + /* After a single schema name in SET context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index c40a8884a8f..1bb3c7db2e0 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -621,6 +621,92 @@ Except tables: "pub_test.testpub_tbl_s1" "pub_test.testpub_tbl_s2" +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s2" + +-- fail: table in EXCEPT clause also appears in the explicit table list +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot appear in both the table list and the EXCEPT clause +-- error: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 1: ...xcept SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.tes... + ^ +-- SET: unqualified name in EXCEPT is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- SET without EXCEPT clears the existing except list +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + +-- SET to a different schema removes old schema's EXCEPT entries +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA public; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "public" + +-- fail: nonexistent table in EXCEPT clause (SET path) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- SET: multiple schemas each with their own EXCEPT clause +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- error: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +ERROR: EXCEPT clause is not supported with DROP in ALTER PUBLICATION +-- DROP TABLES IN SCHEMA removes associated EXCEPT entries +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "public" +Except tables: + "public.testpub_tbl1" + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index cd5ed06dcad..6b672ab5b61 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -308,6 +308,44 @@ ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (tes ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); \dRp+ testpub_alter_except +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + +-- fail: table in EXCEPT clause also appears in the explicit table list +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- error: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- SET: unqualified name in EXCEPT is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +\dRp+ testpub_alter_except + +-- SET without EXCEPT clears the existing except list +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + +-- SET to a different schema removes old schema's EXCEPT entries +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA public; +\dRp+ testpub_alter_except + +-- fail: nonexistent table in EXCEPT clause (SET path) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- SET: multiple schemas each with their own EXCEPT clause +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_alter_except + +-- error: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); + +-- DROP TABLES IN SCHEMA removes associated EXCEPT entries +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 0ba6d6f8bb2..01eafb5b7c8 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -376,6 +376,61 @@ $result = is($result, qq(0), 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); +# SET: replace the except list; tab_excluded is now included and tab_published is excluded. +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_published)" +); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (7); + INSERT INTO sch1.tab_excluded VALUES (7); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded WHERE a = 7"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: newly included table is replicated' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published WHERE a = 7"); +is($result, qq(0), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: now-excluded table is not replicated' +); + +# SET without EXCEPT: clears the except list; both tables are now published. +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1"); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (8); + INSERT INTO sch1.tab_excluded VALUES (8); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published WHERE a = 8"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_published replicated after except list cleared' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded WHERE a = 8"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_excluded replicated after except list cleared' +); + $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); @@ -443,6 +498,36 @@ $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); +# OK when a table is excluded by a TABLES IN SCHEMA EXCEPT publication, +# but is included by another publication. +$node_publisher->safe_psql('postgres', 'TRUNCATE tab1'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE tab1'); + +$node_publisher->safe_psql( + 'postgres', qq( + CREATE PUBLICATION tap_pub1 FOR TABLES IN SCHEMA public EXCEPT (TABLE public.tab1); + CREATE PUBLICATION tap_pub2 FOR TABLE tab1; + INSERT INTO tab1 VALUES(1); +)); +$node_subscriber->psql('postgres', + "CREATE SUBSCRIPTION tap_sub CONNECTION '$publisher_connstr' PUBLICATION tap_pub1, tap_pub2" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'tap_sub'); + +$node_publisher->safe_psql('postgres', qq(INSERT INTO tab1 VALUES(2))); +$node_publisher->wait_for_catchup('tap_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT * FROM tab1 ORDER BY a"); +is( $result, qq(1 +2), + "TABLES IN SCHEMA EXCEPT: table excluded in schema pub but included by another pub is replicated" +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); + $node_publisher->stop('fast'); done_testing(); -- 2.50.1 (Apple Git-155)
v16-0004-Documentation-Patch.patch (application/octet-stream, 10.9K) download From 37a3e667efa59375863a8e21fd6627b292ab36c2 Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Thu, 18 Jun 2026 09:03:08 +0530 Subject: [PATCH v16 4/4] Documentation Patch --- doc/src/sgml/logical-replication.sgml | 3 +- doc/src/sgml/ref/alter_publication.sgml | 58 +++++++++++++++++++++++- doc/src/sgml/ref/create_publication.sgml | 37 ++++++++++++--- 3 files changed, 88 insertions(+), 10 deletions(-) diff --git a/doc/src/sgml/logical-replication.sgml b/doc/src/sgml/logical-replication.sgml index 9e7868487de..1433d2660fe 100644 --- a/doc/src/sgml/logical-replication.sgml +++ b/doc/src/sgml/logical-replication.sgml @@ -117,7 +117,8 @@ or <literal>FOR ALL SEQUENCES</literal>. Unlike tables, sequences can be synchronized at any time. For more information, see <xref linkend="logical-replication-sequences"/>. When a publication is - created with <literal>FOR ALL TABLES</literal>, a table or set of tables can + created with <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal>, a table or set of tables can be explicitly excluded from publication using the <link linkend="sql-createpublication-params-for-except-table"><literal>EXCEPT</literal></link> clause. diff --git a/doc/src/sgml/ref/alter_publication.sgml b/doc/src/sgml/ref/alter_publication.sgml index 52114a16a39..037ddfa9404 100644 --- a/doc/src/sgml/ref/alter_publication.sgml +++ b/doc/src/sgml/ref/alter_publication.sgml @@ -31,7 +31,7 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA <replaceable class="parameter">tables_in_schema</replaceable> [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -47,6 +47,10 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <replaceable class="parameter">table_object</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] [ WHERE ( <replaceable class="parameter">expression</replaceable> ) ] +<phrase>and <replaceable class="parameter">tables_in_schema</replaceable> is:</phrase> + + { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] + <phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> TABLE <replaceable class="parameter">table_object</replaceable> [, ... ] @@ -69,6 +73,9 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r The first two variants modify which tables/schemas are part of the publication. The <literal>ADD</literal> and <literal>DROP</literal> clauses will add and remove one or more tables/schemas from the publication. + The <literal>EXCEPT</literal> clause can be used with + <literal>ADD TABLES IN SCHEMA</literal> to exclude specific tables from a + schema-level publication. </para> <para> @@ -93,7 +100,11 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r used with a publication defined with <literal>FOR TABLE</literal> or <literal>FOR TABLES IN SCHEMA</literal>, replaces the list of tables/schemas in the publication with the specified list; the existing tables or schemas - that were present in the publication will be removed. + that were present in the publication will be removed. When + <literal>SET TABLES IN SCHEMA</literal> is used with an + <literal>EXCEPT</literal> clause, the excluded tables for each schema are + replaced with the specified list; if <literal>EXCEPT</literal> is omitted + for a schema, any existing exclusions for that schema are cleared. </para> <para> @@ -198,6 +209,27 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r </listitem> </varlistentry> + <varlistentry> + <term><literal>EXCEPT</literal></term> + <listitem> + <para> + When used with <literal>ADD TABLES IN SCHEMA</literal> + or <literal>SET TABLES IN SCHEMA</literal>, specifies + tables to be excluded from the publication. Each named + table must belong to the schema specified in the same + <literal>TABLES IN SCHEMA</literal> clause. Table names may be + schema-qualified or unqualified; unqualified names are implicitly + qualified with the schema named in the same clause. See + <xref linkend="sql-createpublication"/> for further details on the + semantics of <literal>EXCEPT</literal>. + </para> + <para> + Dropping a table always removes it from the <literal>EXCEPT</literal> + clause. + </para> + </listitem> + </varlistentry> + <varlistentry> <term><literal>SET ( <replaceable class="parameter">publication_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] )</literal></term> <listitem> @@ -288,6 +320,28 @@ ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA marketing, sales; </programlisting> </para> + <para> + Add schema <structname>sales</structname> to the publication + <structname>sales_publication</structname>, excluding the + <structname>sales.internal</structname> and + <structname>sales.drafts</structname> tables: +<programlisting> +ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA sales EXCEPT (TABLE internal, drafts); +</programlisting> + </para> + + <para> + Replace the schema list of <structname>sales_publication</structname> with + <structname>sales</structname>, excluding only + <structname>sales.drafts</structname>. Other than + <structname>sales.drafts</structname>, any previously excluded tables for schema + <structname>sales</structname> are no longer excluded. Any schemas previously in + <structname>sales_publication</structname> are removed: +<programlisting> +ALTER PUBLICATION sales_publication SET TABLES IN SCHEMA sales EXCEPT (TABLE drafts); +</programlisting> + </para> + <para> Add tables <structname>users</structname>, <structname>departments</structname> and schema diff --git a/doc/src/sgml/ref/create_publication.sgml b/doc/src/sgml/ref/create_publication.sgml index 85cfcaddafa..5227dd716ed 100644 --- a/doc/src/sgml/ref/create_publication.sgml +++ b/doc/src/sgml/ref/create_publication.sgml @@ -28,7 +28,7 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA <replaceable class="parameter">tables_in_schema</replaceable> [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -39,6 +39,10 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <replaceable class="parameter">table_object</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] [ WHERE ( <replaceable class="parameter">expression</replaceable> ) ] +<phrase>and <replaceable class="parameter">tables_in_schema</replaceable> is:</phrase> + + { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] + <phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> TABLE <replaceable class="parameter">table_object</replaceable> [, ... ] @@ -142,6 +146,8 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <para> Marks the publication as one that replicates changes for all tables in the specified list of schemas, including tables created in the future. + Tables listed in the <literal>EXCEPT</literal> clause for a given schema + are excluded from the publication. </para> <para> @@ -173,7 +179,7 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <para> Marks the publication as one that replicates changes for all tables in the database, including tables created in the future. Tables listed in - <literal>EXCEPT</literal> clause are excluded from the publication. + the <literal>EXCEPT</literal> clause are excluded from the publication. </para> </listitem> </varlistentry> @@ -198,13 +204,21 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <listitem> <para> This clause specifies a list of tables to be excluded from the - publication. + publication. It can be used with <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal>. For <literal>FOR TABLES IN + SCHEMA</literal>, the exclusion applies only to tables in the schema + associated with the <literal>EXCEPT</literal>. </para> <para> - Once a table is excluded, the exclusion applies to that table - regardless of its name or schema. Renaming the table or moving it to - another schema using <command>ALTER TABLE ... SET SCHEMA</command> does - not remove the exclusion. + Once a table is excluded under <literal>FOR ALL TABLES</literal>, the + exclusion applies to that table regardless of its name or schema. + Renaming the table or moving it to another schema using + <command>ALTER TABLE ... SET SCHEMA</command> does not remove the + exclusion. However, for <literal>FOR TABLES IN SCHEMA</literal>, because + the <literal>EXCEPT</literal> is schema-scoped, moving a schema-excluded + table to another schema does remove the exclusion; if the table is later + moved back, the exclusion is not restored and must be re-established + with <command>ALTER PUBLICATION</command>. </para> <para> For inherited tables, if <literal>ONLY</literal> is specified before the @@ -521,6 +535,15 @@ CREATE PUBLICATION production_publication FOR TABLE users, departments, TABLES I CREATE PUBLICATION sales_publication FOR TABLES IN SCHEMA marketing, sales; </programlisting></para> + <para> + Create a publication that publishes all changes for all the tables present in + the schema <structname>sales</structname>, except + <structname>internal</structname> and <structname>drafts</structname>: +<programlisting> +CREATE PUBLICATION sales_filtered FOR TABLES IN SCHEMA sales EXCEPT (TABLE internal, drafts); +</programlisting> + </para> + <para> Create a publication that publishes all changes for table <structname>users</structname>, but replicates only columns <structname>user_id</structname> and -- 2.50.1 (Apple Git-155)
^ permalink raw reply [nested|flat] 196+ messages in thread

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-06-22 23:40  Peter Smith <smithpb2250@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  1 sibling, 0 replies; 196+ messages in thread

From: Peter Smith @ 2026-06-22 23:40 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Tue, Jun 23, 2026 at 12:49 AM Nisha Moond <nisha.moond412@gmail.com> wrote:
>
...
>
> Based on the changes in commit 77b6dd9, I re-analyzed the pointed-out paragraph.
>
> On reconsideration, I think the schema-move behavior is really a
> property of EXCEPT itself rather than ALTER PUBLICATION. So we can
> keep it only in the CREATE PUBLICATION documentation and drop it from
> ALTER PUBLICATION to avoid duplication.
> We already have a cross-reference in ALTER PUBLICATION: "See CREATE
> PUBLICATION for further details on the semantics of EXCEPT", so users
> still have a clear path to the detailed behavior description.
> I modified your suggestion slightly to keep the information from the
> removed paragraph intact.
>
> Attached updated patches v16. No changes in 0001 to 0003.
>

Hi Nisha.

Thanks for all the changes. I don't have any more review comments at this time.

======
Kind Regards,
Peter Smith.
Fujitsu Australia





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-06-30 10:16  shveta malik <shveta.malik@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  1 sibling, 1 reply; 196+ messages in thread

From: shveta malik @ 2026-06-30 10:16 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; shveta malik <shveta.malik@gmail.com>

On Mon, Jun 22, 2026 at 6:20 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
>
> Attached updated patches v16. No changes in 0001 to 0003.
>

Thanks Nisha. I have resumed review of patch. I have not goen through
complete patch yet, but please find a few initial comments:


1)
I get this during compilation:

pgoutput.c:2232:45: warning: declaration of ‘except_pubids’ shadows a
previous local [-Wshadow=compatible-local]
 2232 |                                 List       *except_pubids = NIL;
      |                                             ^~~~~~~~~~~~~
pgoutput.c:2100:29: note: shadowed declaration is here
 2100 |                 List       *except_pubids;


2)
I am checking the flow:
get_rel_sync_entry-->GetTopMostAncestorInPublication

@@ -2267,7 +2290,8 @@ get_rel_sync_entry(PGOutputData *data, Relation relation)

  ancestor = GetTopMostAncestorInPublication(pub->oid,
     ancestors,
-    &level);
+    &level,
+    except_pubids);

a)
For what all publications, flow will come to above point. I guess it
can come for a explict table pub or a schema pub. For a schmea pub,
except_pubids make sense but not for a explicit-table pub alone.
Please add a comment atop GetTopMostAncestorInPublication call here to
explain
the scenario adn then the need of except_pubids.

b)
We have got except_pubids in the begining of the function as:
except_pubids = GetRelationExcludedPublications(root_relid);

Now inside GetTopMostAncestorInPublication(), we are keeping
'except_pubids' as constant while moving through all the ancestors. We
are fetching GetRelationIncludedPublications and GetSchemaPublications
for each ancestor but are not computing
GetRelationExcludedPublications for each ancestor. It may not be
obvious (for many new readers) why 'except_pubids' is not fetched
again for each ancestor. Please add a comment there (perhaps because
EXCEPT list can not have any partition and can have only root)

3)
The error message below and its associated validation logic are
duplicated in three places:

"cannot appear in both the table list and the EXCEPT clause"

Do you think we could factor this into a small helper function and
reuse it everywhere? That would make the code more modular and
simplify future changes to validation or error messages.

thanks
Shveta





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-01 10:07  Nisha Moond <nisha.moond412@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  0 siblings, 2 replies; 196+ messages in thread

From: Nisha Moond @ 2026-07-01 10:07 UTC (permalink / raw)
  To: shveta malik <shveta.malik@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Tue, Jun 30, 2026 at 3:47 PM shveta malik <shveta.malik@gmail.com> wrote:
>
> On Mon, Jun 22, 2026 at 6:20 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
> >
> > Attached updated patches v16. No changes in 0001 to 0003.
> >
>
> Thanks Nisha. I have resumed review of patch. I have not goen through
> complete patch yet, but please find a few initial comments:
>

Thanks for review Shveta.

>
> 1)
> I get this during compilation:
>
> pgoutput.c:2232:45: warning: declaration of ‘except_pubids’ shadows a
> previous local [-Wshadow=compatible-local]
>  2232 |                                 List       *except_pubids = NIL;
>       |                                             ^~~~~~~~~~~~~
> pgoutput.c:2100:29: note: shadowed declaration is here
>  2100 |                 List       *except_pubids;
>

An existing variable exceptpubids was renamed to except_pubids by
mistake while addressing comment #5 at [1].
Fixed now.

>
> 2)
> I am checking the flow:
> get_rel_sync_entry-->GetTopMostAncestorInPublication
>
> @@ -2267,7 +2290,8 @@ get_rel_sync_entry(PGOutputData *data, Relation relation)
>
>   ancestor = GetTopMostAncestorInPublication(pub->oid,
>      ancestors,
> -    &level);
> +    &level,
> +    except_pubids);
>
> a)
> For what all publications, flow will come to above point. I guess it
> can come for a explict table pub or a schema pub. For a schmea pub,
> except_pubids make sense but not for a explicit-table pub alone.
> Please add a comment atop GetTopMostAncestorInPublication call here to
> explain
> the scenario adn then the need of except_pubids.
>
> b)
> We have got except_pubids in the begining of the function as:
> except_pubids = GetRelationExcludedPublications(root_relid);
>
> Now inside GetTopMostAncestorInPublication(), we are keeping
> 'except_pubids' as constant while moving through all the ancestors. We
> are fetching GetRelationIncludedPublications and GetSchemaPublications
> for each ancestor but are not computing
> GetRelationExcludedPublications for each ancestor. It may not be
> obvious (for many new readers) why 'except_pubids' is not fetched
> again for each ancestor. Please add a comment there (perhaps because
> EXCEPT list can not have any partition and can have only root)
>

Added comments for both the cases.

> 3)
> The error message below and its associated validation logic are
> duplicated in three places:
>
> "cannot appear in both the table list and the EXCEPT clause"
>
> Do you think we could factor this into a small helper function and
> reuse it everywhere? That would make the code more modular and
> simplify future changes to validation or error messages.
>

Done.
~~~

Besides the above comments, I found and fixed a few additional issues
during further testing:
1) Fixed an issue where UPDATE/DELETE on an excluded table without
replica identity was still blocked. e.g.,

postgres=# create publication pub_h2 for tables in schema s1 except ( table t1);
postgres=# update s1.t1 set c1=3 where c1=1;
ERROR: cannot update table "t1" because it does not have a replica
identity and publishes updates
HINT: To enable updating the table, set REPLICA IDENTITY using ALTER TABLE.

Excluded tables should not be treated as published for update/delete checks.

2) Fixed a bug in RemoveSchemaPubExceptForRel(), where a no-op command
such as ALTER TABLE s.t SET SCHEMA s incorrectly removed the table
from the EXCEPT list.

3) Fixed is_table_publication() logic. It relied on the first
pg_publication_rel row for a publication, which is no longer reliable
because with this feature we can have multiple rows with different
prexcept values for the same publication.
A publication can have both FOR TABLE (prexcept =false) and FOR TABLES
IN SCHEMA (prexcept=false) entries.

4) Fixed a bug in PublicationDropTables() where "ALTER PUBLICATION p
DROP TABLE t" could silently remove an EXCEPT entry. DROP TABLE should
only apply to explicitly added FOR TABLE members; EXCEPT entries are
not publication members and should not be removed through this path.
For example: Before Fix:
  create publication pub1 for tables in schema s1 except ( table t1);
  alter publication pub1 drop table s1.t1;
  ALTER PUBLICATION
-- the Except tables: entry gets deleted.

After the fix (v17):
  alter publication pub1 drop table s1.t1;
  ERROR:  relation "t1" is not part of the publication
~~~

Attached are the v17 patches.

[1] https://www.postgresql.org/message-id/CAHut%2BPuiK_Pa%3DBkSgBxYzqf1PYh%2BmcUcUQCr8r1e69-y1r%2Bhhw%40...
--
Thanks,
Nisha

Attachments: download all (3 files, .tar.gz)

v17-0001-Support-EXCEPT-clause-for-schema-level-publicati.patch (application/octet-stream, 66.1K) download From e1cd351742545ec07a7c3b9f51cfcaa6f63b1e36 Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Tue, 16 Jun 2026 10:58:49 +0530 Subject: [PATCH v17 1/3] Support EXCEPT clause for schema-level publications Extend table exclusion support in publications to allow specific tables to be excluded from schema-level publications using an EXCEPT clause in CREATE PUBLICATION. Supported syntax: CREATE PUBLICATION <pub> FOR TABLES IN SCHEMA s EXCEPT (TABLE t1,...); --- src/backend/catalog/pg_publication.c | 203 ++++++++++++++++---- src/backend/commands/publicationcmds.c | 162 ++++++++++++++-- src/backend/commands/tablecmds.c | 11 ++ src/backend/parser/gram.y | 54 +++++- src/backend/replication/pgoutput/pgoutput.c | 39 +++- src/backend/utils/cache/relcache.c | 41 ++-- src/bin/psql/describe.c | 18 ++ src/bin/psql/tab-complete.in.c | 35 +++- src/include/catalog/pg_publication.h | 3 +- src/include/commands/publicationcmds.h | 2 + src/include/nodes/parsenodes.h | 2 + src/test/regress/expected/publication.out | 171 ++++++++++++++++- src/test/regress/sql/publication.sql | 100 +++++++++- src/test/subscription/t/037_except.pl | 133 ++++++++++++- 14 files changed, 888 insertions(+), 86 deletions(-) diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index 5c457d9aca8..e7018ff565f 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -330,19 +330,20 @@ is_table_publication(Oid pubid) scan = systable_beginscan(pubrelsrel, PublicationRelPrpubidIndexId, true, NULL, 1, &scankey); - tup = systable_getnext(scan); - if (HeapTupleIsValid(tup)) - { - Form_pg_publication_rel pubrel; - pubrel = (Form_pg_publication_rel) GETSTRUCT(tup); - - /* - * For any publication, pg_publication_rel contains either only EXCEPT - * entries or only explicitly included tables. Therefore, examining - * the first tuple is sufficient to determine table inclusion. - */ - result = !pubrel->prexcept; + /* + * A publication can hold both explicit-include (prexcept=false) + * and EXCEPT (prexcept=true) rows for the same pubid. Scan until + * we find an explicit-include row, rather than relying on the first row's + * prexcept value. + */ + while (HeapTupleIsValid(tup = systable_getnext(scan))) + { + if (!((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept) + { + result = true; + break; + } } systable_endscan(scan); @@ -444,14 +445,27 @@ GetPubPartitionOptionRelations(List *result, PublicationPartOpt pub_partopt, * * Note that the list of ancestors should be ordered such that the topmost * ancestor is at the end of the list. + * + * except_pubids is a list of publication OIDs whose schema membership + * should be ignored for the ancestor (because the ancestor is in their + * EXCEPT clause). */ Oid -GetTopMostAncestorInPublication(Oid puboid, List *ancestors, int *ancestor_level) +GetTopMostAncestorInPublication(Oid puboid, List *ancestors, + int *ancestor_level, List *except_pubids) { ListCell *lc; Oid topmost_relid = InvalidOid; int level = 0; + /* + * except_pubids is computed once from the partition root and reused + * across the ancestor walk. Re-fetching exclusion information for each + * ancestor is unnecessary because only the root can have prexcept=true; + * partitions themselves cannot be added to EXCEPT. + */ + bool check_schemas = !list_member_oid(except_pubids, puboid); + /* * Find the "topmost" ancestor that is in this publication. */ @@ -470,7 +484,7 @@ GetTopMostAncestorInPublication(Oid puboid, List *ancestors, int *ancestor_level if (ancestor_level) *ancestor_level = level; } - else + else if (check_schemas) { aschemaPubids = GetSchemaPublications(get_rel_namespace(ancestor)); if (list_member_oid(aschemaPubids, puboid)) @@ -545,18 +559,30 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, * duplicates, it's here just to provide nicer error message in common * case. The real protection is the unique key on the catalog. */ - if (SearchSysCacheExists2(PUBLICATIONRELMAP, ObjectIdGetDatum(relid), - ObjectIdGetDatum(pubid))) + tup = SearchSysCache2(PUBLICATIONRELMAP, ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + + if (HeapTupleIsValid(tup)) { + bool is_except = ((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept; + + ReleaseSysCache(tup); table_close(rel, RowExclusiveLock); if (if_not_exists) return InvalidObjectAddress; - ereport(ERROR, - (errcode(ERRCODE_DUPLICATE_OBJECT), - errmsg("relation \"%s\" is already member of publication \"%s\"", - RelationGetRelationName(targetrel), pub->name))); + if (is_except) + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("table \"%s\" cannot be added because it is excluded from publication \"%s\"", + RelationGetQualifiedRelationName(targetrel), + pub->name))); + else + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("relation \"%s\" is already member of publication \"%s\"", + RelationGetRelationName(targetrel), pub->name))); } check_publication_add_relation(pri); @@ -982,12 +1008,13 @@ GetIncludedPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) * Gets list of table oids that were specified in the EXCEPT clause for a * publication. * - * This should only be used FOR ALL TABLES publications. + * This is used for FOR ALL TABLES and FOR TABLES IN SCHEMA publications, + * both of which support EXCEPT TABLE. */ List * GetExcludedPublicationTables(Oid pubid, PublicationPartOpt pub_partopt) { - Assert(GetPublication(pubid)->alltables); + Assert(GetPublication(pubid)->alltables || is_schema_publication(pubid)); return get_publication_relations(pubid, pub_partopt, true); } @@ -1049,15 +1076,15 @@ GetAllPublicationRelations(Oid pubid, char relkind, bool pubviaroot) TableScanDesc scan; HeapTuple tuple; List *result = NIL; - List *exceptlist = NIL; + List *except_relids = NIL; Assert(!(relkind == RELKIND_SEQUENCE && pubviaroot)); /* EXCEPT filtering applies only to relations, not sequences */ if (relkind == RELKIND_RELATION) - exceptlist = GetExcludedPublicationTables(pubid, pubviaroot ? - PUBLICATION_PART_ROOT : - PUBLICATION_PART_LEAF); + except_relids = GetExcludedPublicationTables(pubid, pubviaroot ? + PUBLICATION_PART_ROOT : + PUBLICATION_PART_LEAF); classRel = table_open(RelationRelationId, AccessShareLock); @@ -1075,7 +1102,7 @@ GetAllPublicationRelations(Oid pubid, char relkind, bool pubviaroot) if (is_publishable_class(relid, relForm) && !(relForm->relispartition && pubviaroot) && - !list_member_oid(exceptlist, relid)) + !list_member_oid(except_relids, relid)) result = lappend_oid(result, relid); } @@ -1097,7 +1124,7 @@ GetAllPublicationRelations(Oid pubid, char relkind, bool pubviaroot) if (is_publishable_class(relid, relForm) && !relForm->relispartition && - !list_member_oid(exceptlist, relid)) + !list_member_oid(except_relids, relid)) result = lappend_oid(result, relid); } @@ -1232,22 +1259,77 @@ GetSchemaPublicationRelations(Oid schemaid, PublicationPartOpt pub_partopt) /* * Gets the list of all relations published by FOR TABLES IN SCHEMA - * publication. + * publication, excluding any tables listed in the EXCEPT clause. */ List * GetAllSchemaPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) { List *result = NIL; List *pubschemalist = GetPublicationSchemas(pubid); + List *except_relids = NIL; ListCell *cell; + /* get the list of tables excluded via EXCEPT TABLE for this publication */ + if (pubschemalist != NIL) + except_relids = GetExcludedPublicationTables(pubid, pub_partopt); + foreach(cell, pubschemalist) { Oid schemaid = lfirst_oid(cell); List *schemaRels = NIL; schemaRels = GetSchemaPublicationRelations(schemaid, pub_partopt); - result = list_concat(result, schemaRels); + + if (except_relids != NIL) + { + /* filter out any tables that appear in the EXCEPT list */ + ListCell *rlc; + + foreach(rlc, schemaRels) + { + Oid relid = lfirst_oid(rlc); + bool excluded = list_member_oid(except_relids, relid); + + /* + * Also exclude any relation whose partition ancestor is in + * the EXCEPT list. This matters when pub_partopt is + * PUBLICATION_PART_ROOT: the except list holds only the root + * OID, but the schema scan may also return individual + * partition relations that live in the same schema. + * + * XXX: this ancestor check uses the publication-wide + * except_relids and does not consider which schema the EXCEPT + * was bound to. When a publication has multiple schemas + * (e.g. FOR TABLES IN SCHEMA s1, TABLES IN SCHEMA s2 EXCEPT + * (TABLE s2.parent)) and a partition of the EXCEPT'd parent + * lives in a DIFFERENT schema (s1) that is itself + * unconditionally included, we treat that partition as + * excluded because its ancestor matches the global + * except_relids. Need to decide the expected behavior here. + */ + if (!excluded && get_rel_relispartition(relid)) + { + List *ancestors = get_partition_ancestors(relid); + ListCell *alc; + + foreach(alc, ancestors) + { + if (list_member_oid(except_relids, lfirst_oid(alc))) + { + excluded = true; + break; + } + } + list_free(ancestors); + } + + if (!excluded) + result = lappend_oid(result, relid); + } + list_free(schemaRels); + } + else + result = list_concat(result, schemaRels); } return result; @@ -1324,6 +1406,7 @@ is_table_publishable_in_publication(Oid relid, Publication *pub) { bool relispartition; List *ancestors = NIL; + HeapTuple tup; /* * For non-pubviaroot publications, a partitioned table is never the @@ -1380,20 +1463,62 @@ is_table_publishable_in_publication(Oid relid, Publication *pub) * If it's false, the partition is covered by its ancestor's presence in * the publication, it should be included (return true). */ - if (relispartition && - OidIsValid(GetTopMostAncestorInPublication(pub->oid, ancestors, NULL))) - return !pub->pubviaroot; + if (relispartition) + { + Oid ancestor_oid; + + ancestor_oid = GetTopMostAncestorInPublication(pub->oid, ancestors, NULL, NIL); + if (OidIsValid(ancestor_oid)) + { + /* + * The ancestor was found in the publication (via explicit + * membership or schema membership), but it may be excluded. Check + * for a prexcept row before concluding the partition is + * published. + */ + tup = SearchSysCache2(PUBLICATIONRELMAP, + ObjectIdGetDatum(ancestor_oid), + ObjectIdGetDatum(pub->oid)); + if (HeapTupleIsValid(tup)) + { + bool is_except; + + is_except = ((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept; + ReleaseSysCache(tup); + if (is_except) + return false; + } + return !pub->pubviaroot; + } + } /* * Check whether the table is explicitly published via pg_publication_rel * or pg_publication_namespace. + * + * A pg_publication_rel row with prexcept=true means the table is + * explicitly excluded via EXCEPT and must not be reported as published, + * even if its schema is otherwise included. A row with prexcept=false + * means it is explicitly included. If no pg_publication_rel row exists, + * the table is published iff its schema appears in + * pg_publication_namespace. */ - return (SearchSysCacheExists2(PUBLICATIONRELMAP, - ObjectIdGetDatum(relid), - ObjectIdGetDatum(pub->oid)) || - SearchSysCacheExists2(PUBLICATIONNAMESPACEMAP, - ObjectIdGetDatum(get_rel_namespace(relid)), - ObjectIdGetDatum(pub->oid))); + + tup = SearchSysCache2(PUBLICATIONRELMAP, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pub->oid)); + if (HeapTupleIsValid(tup)) + { + bool is_except; + + is_except = ((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept; + ReleaseSysCache(tup); + return !is_except; + } + + return SearchSysCacheExists2(PUBLICATIONNAMESPACEMAP, + ObjectIdGetDatum(get_rel_namespace(relid)), + ObjectIdGetDatum(pub->oid)); } /* diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 440adb356ad..45a8a5c3f71 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -71,6 +71,7 @@ static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); static char defGetGeneratedColsOption(DefElem *def); +static void CheckExceptNotInTableList(List *except_rels, List *explicitrelids); static void @@ -181,7 +182,7 @@ parse_publication_options(ParseState *pstate, */ static void ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, - List **rels, List **exceptrels, List **schemas) + List **rels, List **except_pubtables, List **schemas) { ListCell *cell; PublicationObjSpec *pubobj; @@ -200,7 +201,7 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, { case PUBLICATIONOBJ_EXCEPT_TABLE: pubobj->pubtable->except = true; - *exceptrels = lappend(*exceptrels, pubobj->pubtable); + *except_pubtables = lappend(*except_pubtables, pubobj->pubtable); break; case PUBLICATIONOBJ_TABLE: pubobj->pubtable->except = false; @@ -224,6 +225,38 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, /* Filter out duplicates if user specifies "sch1, sch1" */ *schemas = list_append_unique_oid(*schemas, schemaid); + + /* + * Qualify unqualified EXCEPT table names with the resolved + * current schema and reject any explicitly cross-schema + * entries. This mirrors the parse-time handling done for + * TABLES_IN_SCHEMA in preprocess_pubobj_list(), deferred here + * because CURRENT_SCHEMA is not known until execution time. + */ + if (pubobj->except_tables != NIL) + { + char *cur_schema_name = get_namespace_name(schemaid); + + foreach_ptr(PublicationObjSpec, eobj, pubobj->except_tables) + { + const char *eobj_schemaname = + eobj->pubtable->relation->schemaname; + const char *eobj_relname = + eobj->pubtable->relation->relname; + + if (eobj_schemaname == NULL) + eobj->pubtable->relation->schemaname = cur_schema_name; + else if (strcmp(eobj_schemaname, cur_schema_name) != 0) + ereport(ERROR, + errcode(ERRCODE_INVALID_OBJECT_DEFINITION), + errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", + quote_qualified_identifier(eobj_schemaname, eobj_relname), + cur_schema_name)); + + *except_pubtables = lappend(*except_pubtables, + eobj->pubtable); + } + } break; default: /* shouldn't happen */ @@ -305,7 +338,7 @@ pub_rf_contains_invalid_column(Oid pubid, Relation relation, List *ancestors, if (pubviaroot && relation->rd_rel->relispartition) { publish_as_relid - = GetTopMostAncestorInPublication(pubid, ancestors, NULL); + = GetTopMostAncestorInPublication(pubid, ancestors, NULL, NIL); if (!OidIsValid(publish_as_relid)) publish_as_relid = relid; @@ -389,7 +422,7 @@ pub_contains_invalid_column(Oid pubid, Relation relation, List *ancestors, */ if (pubviaroot && relation->rd_rel->relispartition) { - publish_as_relid = GetTopMostAncestorInPublication(pubid, ancestors, NULL); + publish_as_relid = GetTopMostAncestorInPublication(pubid, ancestors, NULL, NIL); if (!OidIsValid(publish_as_relid)) publish_as_relid = relid; @@ -770,6 +803,23 @@ TransformPubWhereClauses(List *tables, const char *queryString, } } +/* + * Check that no relation in except_rels is also present in explicitrelids, + * the list of OIDs added to the publication by the explicit TABLE list. A + * table cannot be both explicitly published and excluded in the same DDL. + */ +static void +CheckExceptNotInTableList(List *except_rels, List *explicitrelids) +{ + foreach_ptr(PublicationRelInfo, pri, except_rels) + { + if (list_member_oid(explicitrelids, RelationGetRelid(pri->relation))) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" cannot appear in both the table list and the EXCEPT clause", + RelationGetQualifiedRelationName(pri->relation))); + } +} /* * Given a list of tables that are going to be added to a publication, @@ -849,7 +899,7 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) char publish_generated_columns; AclResult aclresult; List *relations = NIL; - List *exceptrelations = NIL; + List *except_pubtables = NIL; List *schemaidlist = NIL; /* must have CREATE privilege on database */ @@ -936,16 +986,16 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) /* Associate objects with the publication. */ ObjectsInPublicationToOids(stmt->pubobjects, pstate, &relations, - &exceptrelations, &schemaidlist); + &except_pubtables, &schemaidlist); if (stmt->for_all_tables) { /* Process EXCEPT table list */ - if (exceptrelations != NIL) + if (except_pubtables != NIL) { List *rels; - rels = OpenTableList(exceptrelations); + rels = OpenTableList(except_pubtables); PublicationAddTables(puboid, rels, true, NULL); CloseTableList(rels); } @@ -959,6 +1009,8 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) } else if (!stmt->for_all_sequences) { + List *explicitrelids = NIL; + /* FOR TABLES IN SCHEMA requires superuser */ if (schemaidlist != NIL && !superuser()) ereport(ERROR, @@ -977,6 +1029,19 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) schemaidlist != NIL, publish_via_partition_root); + /* + * Collect explicit table OIDs now, before we close the relation + * list, so that except-table validation below can check for + * contradictions without relying on a catalog scan that might not + * yet see the just-inserted rows. + */ + if (except_pubtables != NIL) + { + foreach_ptr(PublicationRelInfo, pri, rels) + explicitrelids = lappend_oid(explicitrelids, + RelationGetRelid(pri->relation)); + } + PublicationAddTables(puboid, rels, true, NULL); CloseTableList(rels); } @@ -989,6 +1054,25 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) */ LockSchemaList(schemaidlist); PublicationAddSchemas(puboid, schemaidlist, true, NULL); + + if (except_pubtables != NIL) + { + List *except_rels; + + except_rels = OpenTableList(except_pubtables); + + /* + * Validate that each excluded table is not also in the + * explicit table list (which would be contradictory). Use the + * in-memory explicitrelids collected above rather than + * re-reading the catalog, which may not yet see the + * just-inserted rows. + */ + CheckExceptNotInTableList(except_rels, explicitrelids); + + PublicationAddTables(puboid, except_rels, true, NULL); + CloseTableList(except_rels); + } } } @@ -1683,12 +1767,12 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) else { List *relations = NIL; - List *exceptrelations = NIL; + List *except_pubtables = NIL; List *schemaidlist = NIL; Oid pubid = pubform->oid; ObjectsInPublicationToOids(stmt->pubobjects, pstate, &relations, - &exceptrelations, &schemaidlist); + &except_pubtables, &schemaidlist); CheckAlterPublication(stmt, tup, relations, schemaidlist); @@ -1711,7 +1795,7 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) errmsg("publication \"%s\" does not exist", stmt->pubname)); - relations = list_concat(relations, exceptrelations); + relations = list_concat(relations, except_pubtables); AlterPublicationTables(stmt, tup, relations, pstate->p_sourcetext, schemaidlist != NIL); AlterPublicationSchemas(stmt, tup, schemaidlist); @@ -1829,6 +1913,62 @@ RemovePublicationSchemaById(Oid psoid) table_close(rel, RowExclusiveLock); } +/* + * Remove any EXCEPT clause entries for a relation from schema publications. + * Called when a table changes schema (ALTER TABLE ... SET SCHEMA), so that + * a schema-scoped exclusion does not silently follow the table to its new + * schema. + */ +void +RemoveSchemaPubExceptForRel(Oid relid, Oid oldNspOid, Oid newNspOid) +{ + List *pubids; + + /* + * If the table is not actually moving to a different schema (no-op + * ALTER TABLE ... SET SCHEMA <current_schema>), there is nothing to do. + */ + if (oldNspOid == newNspOid) + return; + + pubids = GetRelationExcludedPublications(relid); + + foreach_oid(pubid, pubids) + { + Oid proid; + + /* + * This problem does not apply to FOR ALL TABLES publications, because + * their EXCEPT clause is publication-scoped, not schema-scoped: the + * exclusion should persist regardless of what schema the table is in. + */ + if (!is_schema_publication(pubid)) + continue; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddress obj; + + ObjectAddressSet(obj, PublicationRelRelationId, proid); + + ereport(DEBUG2, + errmsg_internal("auto-remove exclusion of table \"%s.%s\" from publication \"%s\": table moved to schema \"%s\"", + get_namespace_name(oldNspOid), + get_rel_name(relid), + get_publication_name(pubid, false), + get_namespace_name(newNspOid))); + + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + list_free(pubids); +} + /* * Open relations specified by a PublicationTable list. * The returned tables are locked in ShareUpdateExclusiveLock mode in order to diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 472db112fa7..3681f588f7d 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -63,6 +63,7 @@ #include "commands/event_trigger.h" #include "commands/extension.h" #include "commands/repack.h" +#include "commands/publicationcmds.h" #include "commands/sequence.h" #include "commands/tablecmds.h" #include "commands/tablespace.h" @@ -19508,6 +19509,16 @@ AlterTableNamespaceInternal(Relation rel, Oid oldNspOid, Oid nspOid, AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid, false, objsMoved); + /* + * Remove any EXCEPT clause entries for this relation from schema + * publications. A schema-scoped exclusion is no longer meaningful once + * the table moves to a different schema. + */ + if (rel->rd_rel->relkind == RELKIND_RELATION || + rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE) + RemoveSchemaPubExceptForRel(RelationGetRelid(rel), oldNspOid, + nspOid); + table_close(classRel, RowExclusiveLock); } diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y index ff4e1388c55..6a7a1bc5f8d 100644 --- a/src/backend/parser/gram.y +++ b/src/backend/parser/gram.y @@ -58,6 +58,7 @@ #include "nodes/makefuncs.h" #include "nodes/nodeFuncs.h" #include "parser/parser.h" +#include "utils/builtins.h" #include "utils/datetime.h" #include "utils/xml.h" @@ -11272,7 +11273,7 @@ AlterOwnerStmt: ALTER AGGREGATE aggregate_with_argtypes OWNER TO RoleSpec * pub_obj is one of: * * TABLE table [, ...] - * TABLES IN SCHEMA schema [, ...] + * TABLES IN SCHEMA schema [EXCEPT (TABLE table [, ...] )] [, ...] * *****************************************************************************/ @@ -11332,23 +11333,26 @@ PublicationObjSpec: $$->pubtable->columns = $3; $$->pubtable->whereClause = $4; } - | TABLES IN_P SCHEMA ColId + | TABLES IN_P SCHEMA ColId opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_SCHEMA; $$->name = $4; + $$->except_tables = $5; $$->location = @4; } - | TABLES IN_P SCHEMA CURRENT_SCHEMA + | TABLES IN_P SCHEMA CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_CUR_SCHEMA; + $$->except_tables = $5; $$->location = @4; } - | ColId opt_column_list OptWhereClause + | ColId opt_column_list OptWhereClause opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $4; /* * If either a row filter or column list is specified, create * a PublicationTable object. @@ -11392,10 +11396,11 @@ PublicationObjSpec: $$->pubtable->columns = $2; $$->pubtable->whereClause = $3; } - | CURRENT_SCHEMA + | CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $2; $$->location = @1; } ; @@ -20784,6 +20789,8 @@ preprocess_pub_all_objtype_list(List *all_objects_list, List **pubobjects, /* * Process pubobjspec_list to check for errors in any of the objects and * convert PUBLICATIONOBJ_CONTINUATION into appropriate PublicationObjSpecType. + * Also flattens except_tables from TABLES IN SCHEMA nodes into the list so + * that ObjectsInPublicationToOids() sees them as top-level EXCEPT_TABLE entries. */ static void preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) @@ -20812,6 +20819,13 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLE) { + /* EXCEPT is not valid for table objects */ + if (pubobj->except_tables != NIL) + ereport(ERROR, + errcode(ERRCODE_SYNTAX_ERROR), + errmsg("EXCEPT is not allowed for TABLE publication objects"), + parser_errposition(pubobj->location)); + /* relation name or pubtable must be set for this type of object */ if (!pubobj->name && !pubobj->pubtable) ereport(ERROR, @@ -20860,6 +20874,36 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) errcode(ERRCODE_SYNTAX_ERROR), errmsg("invalid schema name"), parser_errposition(pubobj->location)); + + /* + * For TABLES_IN_SCHEMA, qualify unqualified EXCEPT table names + * with the parent schema and reject cross-schema entries at parse + * time, then flatten into the top-level list. + * + * For TABLES_IN_CUR_SCHEMA the schema name is not yet known, so + * skip both steps here; ObjectsInPublicationToOids() will + * qualify names and validate schema membership at execution time. + */ + if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLES_IN_SCHEMA) + { + foreach_ptr(PublicationObjSpec, eobj, pubobj->except_tables) + { + const char *eobj_schemaname = eobj->pubtable->relation->schemaname; + const char *eobj_relname = eobj->pubtable->relation->relname; + + if (eobj_schemaname == NULL) + eobj->pubtable->relation->schemaname = pubobj->name; + else if (strcmp(eobj_schemaname, pubobj->name) != 0) + ereport(ERROR, + errcode(ERRCODE_INVALID_OBJECT_DEFINITION), + errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", + quote_qualified_identifier(eobj_schemaname, eobj_relname), + pubobj->name), + parser_errposition(eobj->location)); + } + pubobjspec_list = list_concat(pubobjspec_list, pubobj->except_tables); + pubobj->except_tables = NIL; + } } prevobjtype = pubobj->pubobjtype; diff --git a/src/backend/replication/pgoutput/pgoutput.c b/src/backend/replication/pgoutput/pgoutput.c index 4ecfcbff7ab..b0983775a03 100644 --- a/src/backend/replication/pgoutput/pgoutput.c +++ b/src/backend/replication/pgoutput/pgoutput.c @@ -2097,6 +2097,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) * are absorbed while decoding WAL. */ List *schemaPubids = GetSchemaPublications(schemaId); + List *except_pubids; ListCell *lc; Oid publish_as_relid = relid; int publish_ancestor_level = 0; @@ -2104,6 +2105,28 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) char relkind = get_rel_relkind(relid); List *rel_publications = NIL; + /* + * For the schema EXCEPT check, we must look up the top-most ancestor + * rather than the relation itself. check_publication_add_relation() + * prevents individual partitions from appearing in the EXCEPT clause, + * so only a root (non-partition) table can have prexcept = true. + * Using the partition's own OID would always return NIL and miss the + * exclusion. + */ + Oid root_relid; + + if (am_partition) + { + List *ancestors = get_partition_ancestors(relid); + + root_relid = llast_oid(ancestors); + list_free(ancestors); + } + else + root_relid = relid; + + except_pubids = GetRelationExcludedPublications(root_relid); + /* Reload publications if needed before use. */ if (!publications_valid) { @@ -2265,9 +2288,19 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) int level; List *ancestors = get_partition_ancestors(relid); + /* + * Reach here for FOR TABLE, FOR TABLES IN SCHEMA, or + * mixed publications. except_pubids lets + * GetTopMostAncestorInPublication() skip schema-based + * ancestor matches when the partition root is excluded + * via this publication's EXCEPT clause. It has no effect + * for pure FOR TABLE publications, which cannot have + * prexcept rows. + */ ancestor = GetTopMostAncestorInPublication(pub->oid, ancestors, - &level); + &level, + except_pubids); if (ancestor != InvalidOid) { @@ -2281,7 +2314,8 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) } if (list_member_oid(pubids, pub->oid) || - list_member_oid(schemaPubids, pub->oid) || + (list_member_oid(schemaPubids, pub->oid) && + !list_member_oid(except_pubids, pub->oid)) || ancestor_published) publish = true; } @@ -2360,6 +2394,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) list_free(pubids); list_free(schemaPubids); + list_free(except_pubids); list_free(rel_publications); entry->replicate_valid = true; diff --git a/src/backend/utils/cache/relcache.c b/src/backend/utils/cache/relcache.c index fb4e042be8a..92ff89fa2a4 100644 --- a/src/backend/utils/cache/relcache.c +++ b/src/backend/utils/cache/relcache.c @@ -5845,16 +5845,29 @@ RelationBuildPublicationDesc(Relation relation, PublicationDesc *pubdesc) /* Fetch the publication membership info. */ puboids = GetRelationIncludedPublications(relid); schemaid = RelationGetNamespace(relation); - puboids = list_concat_unique_oid(puboids, GetSchemaPublications(schemaid)); if (relation->rd_rel->relispartition) { - Oid last_ancestor_relid; - - /* Add publications that the ancestors are in too. */ ancestors = get_partition_ancestors(relid); - last_ancestor_relid = llast_oid(ancestors); + exceptpuboids = GetRelationExcludedPublications(llast_oid(ancestors)); + } + else + exceptpuboids = GetRelationExcludedPublications(relid); + /* + * Subtract exceptpuboids from the schema-publication contribution so that + * a relation EXCEPT'd from a schema publication does not inherit that + * publication's pubactions. Without this filter, + * CheckCmdReplicaIdentity() would demand REPLICA IDENTITY for + * UPDATE/DELETE even on a explicitly excluded table. + */ + puboids = list_concat_unique_oid(puboids, + list_difference_oid(GetSchemaPublications(schemaid), + exceptpuboids)); + + if (relation->rd_rel->relispartition) + { + /* Add publications that the ancestors are in too. */ foreach(lc, ancestors) { Oid ancestor = lfirst_oid(lc); @@ -5863,23 +5876,9 @@ RelationBuildPublicationDesc(Relation relation, PublicationDesc *pubdesc) GetRelationIncludedPublications(ancestor)); schemaid = get_rel_namespace(ancestor); puboids = list_concat_unique_oid(puboids, - GetSchemaPublications(schemaid)); + list_difference_oid(GetSchemaPublications(schemaid), + exceptpuboids)); } - - /* - * Only the top-most ancestor can appear in the EXCEPT clause. - * Therefore, for a partition, exclusion must be evaluated at the - * top-most ancestor. - */ - exceptpuboids = GetRelationExcludedPublications(last_ancestor_relid); - } - else - { - /* - * For a regular table or a root partitioned table, check exclusion on - * table itself. - */ - exceptpuboids = GetRelationExcludedPublications(relid); } alltablespuboids = GetAllTablesPublications(); diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c index af3935b0078..9470a0bbf5e 100644 --- a/src/bin/psql/describe.c +++ b/src/bin/psql/describe.c @@ -7038,6 +7038,24 @@ describePublications(const char *pattern) if (!addFooterToPublicationDesc(&buf, _("Tables from schemas:"), true, &cont)) goto error_return; + + if (pset.sversion >= 190000) + { + /* + * Get tables in the EXCEPT clause for this schema + * publication. + */ + printfPQExpBuffer(&buf, + "SELECT concat(c.relnamespace::regnamespace, '.', c.relname)\n" + "FROM pg_catalog.pg_class c\n" + " JOIN pg_catalog.pg_publication_rel pr ON c.oid = pr.prrelid\n" + "WHERE pr.prpubid = '%s'\n" + " AND pr.prexcept\n" + "ORDER BY 1", pubid); + if (!addFooterToPublicationDesc(&buf, _("Except tables:"), + true, &cont)) + goto error_return; + } } } else diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index 46b9add0604..c20ba1d8c01 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -1065,6 +1065,24 @@ static const SchemaQuery Query_for_trigger_of_table = { "SELECT nspname FROM pg_catalog.pg_namespace "\ " WHERE nspname LIKE '%s'" +#define Query_for_list_of_tables_in_schema \ +"SELECT n.nspname || '.' || c.relname "\ +" FROM pg_catalog.pg_class c "\ +" JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "\ +" WHERE c.relkind IN (" CppAsString2(RELKIND_RELATION) ", " \ + CppAsString2(RELKIND_PARTITIONED_TABLE) ") "\ +" AND (n.nspname || '.' || c.relname) LIKE '%s' "\ +" AND n.nspname = '%s'" + +#define Query_for_list_of_tables_in_current_schema \ +"SELECT c.relname "\ +" FROM pg_catalog.pg_class c "\ +" JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "\ +" WHERE c.relkind IN (" CppAsString2(RELKIND_RELATION) ", " \ + CppAsString2(RELKIND_PARTITIONED_TABLE) ") "\ +" AND c.relname LIKE '%s' "\ +" AND n.nspname = pg_catalog.current_schema()" + /* Use COMPLETE_WITH_QUERY_VERBATIM with these queries for GUC names: */ #define Query_for_list_of_alter_system_set_vars \ "SELECT pg_catalog.lower(name) FROM pg_catalog.pg_settings "\ @@ -3788,8 +3806,21 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); - else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && (!ends_with(prev_wd, ','))) - COMPLETE_WITH("WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE", "WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* Complete "CREATE PUBLICATION <name> [...] WITH" */ else if (Matches("CREATE", "PUBLICATION", MatchAnyN, "WITH", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/include/catalog/pg_publication.h b/src/include/catalog/pg_publication.h index 89b4bb14f62..53e3d7c6f3d 100644 --- a/src/include/catalog/pg_publication.h +++ b/src/include/catalog/pg_publication.h @@ -191,7 +191,8 @@ extern List *GetPubPartitionOptionRelations(List *result, PublicationPartOpt pub_partopt, Oid relid); extern Oid GetTopMostAncestorInPublication(Oid puboid, List *ancestors, - int *ancestor_level); + int *ancestor_level, + List *except_pubids); extern bool is_publishable_relation(Relation rel); extern bool is_schema_publication(Oid pubid); diff --git a/src/include/commands/publicationcmds.h b/src/include/commands/publicationcmds.h index 4cf45c17cc5..fb1703aa675 100644 --- a/src/include/commands/publicationcmds.h +++ b/src/include/commands/publicationcmds.h @@ -27,6 +27,8 @@ extern void AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt); extern void RemovePublicationById(Oid pubid); extern void RemovePublicationRelById(Oid proid); extern void RemovePublicationSchemaById(Oid psoid); +extern void RemoveSchemaPubExceptForRel(Oid relid, Oid oldNspOid, + Oid newNspOid); extern ObjectAddress AlterPublicationOwner(const char *name, Oid newOwnerId); extern void AlterPublicationOwner_oid(Oid pubid, Oid newOwnerId); diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h index 4133c404a6b..1299b0a67a4 100644 --- a/src/include/nodes/parsenodes.h +++ b/src/include/nodes/parsenodes.h @@ -4488,6 +4488,8 @@ typedef struct PublicationObjSpec PublicationObjSpecType pubobjtype; /* type of this publication object */ char *name; PublicationTable *pubtable; + List *except_tables; /* tables specified in the EXCEPT clause (for + * TABLES IN SCHEMA) */ ParseLoc location; /* token location, or -1 if unknown */ } PublicationObjSpec; diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 29e54b214a0..6efed0a0cce 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -270,6 +270,12 @@ CREATE PUBLICATION testpub_foralltables_excepttable2 FOR ALL TABLES EXCEPT (test ERROR: syntax error at or near "testpub_tbl1" LINE 1: ..._foralltables_excepttable2 FOR ALL TABLES EXCEPT (testpub_tb... ^ +-- fail - EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testpub_tbl3); +ERROR: EXCEPT is not allowed for TABLE publication objects +LINE 2: FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testp... + ^ --------------------------------------------- -- SET ALL TABLES/SEQUENCES --------------------------------------------- @@ -470,7 +476,130 @@ HINT: Change the publication's EXCEPT clause using ALTER PUBLICATION ... SET AL RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Create same-named tables in public to verify unqualified EXCEPT entries +-- are qualified with the named schema, not public +CREATE TABLE testpub_nopk (foo int, bar int); +CREATE TABLE testpub_tbl_s1 (a int primary key, b text); +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + Publication testpub_schema_except1 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- Exclude multiple tables using unqualified names; same-named tables exist in +-- public to confirm unqualified names resolve to pub_test, not public +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + Publication testpub_schema_except2 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_nopk" + "pub_test.testpub_tbl_s1" + +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testp... + ^ +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); +ERROR: table "pub_test.testpub_tbl_s1" in EXCEPT clause does not belong to schema "public" +LINE 2: ...R TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.t... + ^ +-- Multiple schemas each with their own EXCEPT clause +CREATE PUBLICATION testpub_schema_except_multi + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_schema_except_multi + Publication testpub_schema_except_multi + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- ALTER TABLE ... SET SCHEMA on a table excluded by a schema publication: +-- the schema-scoped exclusion is no longer meaningful once the table moves +-- out of its schema, so the exclusion is auto-removed. +CREATE PUBLICATION testpub_schema_except_setsch + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_schema_except_setsch + Publication testpub_schema_except_setsch + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s2" + +ALTER TABLE pub_test.testpub_tbl_s2 SET SCHEMA public; +\dRp+ testpub_schema_except_setsch + Publication testpub_schema_except_setsch + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + +DROP PUBLICATION testpub_schema_except_setsch; +-- Restore for further tests +ALTER TABLE public.testpub_tbl_s2 SET SCHEMA pub_test; +-- fail: table appears in both the explicit table list and the EXCEPT clause +CREATE PUBLICATION testpub_except_conflict + FOR TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot appear in both the table list and the EXCEPT clause +-- fail: nonexistent table in EXCEPT clause +CREATE PUBLICATION testpub_except_norel + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- fail: partition cannot appear in EXCEPT clause; only root tables are allowed +CREATE TABLE pub_test.testpub_parted_s (a int) PARTITION BY LIST (a); +CREATE TABLE pub_test.testpub_part_s PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (1); +CREATE PUBLICATION testpub_except_partition + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); +ERROR: cannot specify relation "pub_test.testpub_part_s" in the publication EXCEPT clause +DETAIL: This operation is not supported for individual partitions. +-- fail: TABLE keyword is required for the first entry in the EXCEPT clause +CREATE PUBLICATION testpub_except_nokw + FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +ERROR: syntax error at or near "testpub_nopk" +LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + ^ +-- Cleanup +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP TABLE pub_test.testpub_parted_s CASCADE; +DROP TABLE testpub_nopk, testpub_tbl_s1; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +--------------------------------------------- +-- Tests for publications with SEQUENCES +--------------------------------------------- CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; -- FOR ALL SEQUENCES @@ -1953,6 +2082,27 @@ ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b); ERROR: column specification not allowed for schema LINE 1: ...TION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b)... ^ +-- EXCEPT clause with CURRENT_SCHEMA: cross-schema entry must be rejected +SET search_path = pub_test1; +-- qualified name from wrong schema -> error +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.tbl1); +ERROR: table "pub_test2.tbl1" in EXCEPT clause does not belong to schema "pub_test1" +-- unqualified name implicitly qualified with current schema (pub_test1.tbl) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl); +RESET client_min_messages; +\dRp+ testpub_cursch_except + Publication testpub_cursch_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test1" +Except tables: + "pub_test1.tbl" + +DROP PUBLICATION testpub_cursch_except; +RESET search_path; -- cleanup pub_test1 schema for invalidation tests ALTER PUBLICATION testpub2_forschema DROP TABLES IN SCHEMA pub_test1; DROP PUBLICATION testpub3_forschema, testpub4_forschema, testpub5_forschema, testpub6_forschema, testpub_fortable; @@ -2304,6 +2454,7 @@ DROP ROLE regress_publication_user_dummy; -- Test pg_get_publication_tables(text[], oid) function CREATE SCHEMA gpt_test_sch; CREATE TABLE gpt_test_sch.tbl_sch (id int); +CREATE TABLE gpt_test_sch.tbl_sch2 (id int); CREATE TABLE tbl_normal (id int); CREATE TABLE tbl_parent (id1 int, id2 int, id3 int) PARTITION BY RANGE (id1); CREATE TABLE tbl_part1 PARTITION OF tbl_parent FOR VALUES FROM (1) TO (10); @@ -2314,6 +2465,7 @@ CREATE PUBLICATION pub_all_no_viaroot FOR ALL TABLES WITH (publish_via_partition CREATE PUBLICATION pub_all_except FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = true); CREATE PUBLICATION pub_all_except_no_viaroot FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_schema FOR TABLES IN SCHEMA gpt_test_sch; +CREATE PUBLICATION pub_schema_except FOR TABLES IN SCHEMA gpt_test_sch EXCEPT (TABLE gpt_test_sch.tbl_sch); CREATE PUBLICATION pub_normal FOR TABLE tbl_normal WHERE (id < 10); CREATE PUBLICATION pub_part_leaf FOR TABLE tbl_part1 WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_part_parent FOR TABLE tbl_parent (id1, id2) WHERE (id1 = 10) WITH (publish_via_partition_root = true); @@ -2465,6 +2617,18 @@ SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_part1'); -- no r ---------+---------+-------+------ (0 rows) +-- test for EXCEPT clause with schema publication +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch'); -- no result (excluded) + pubname | relname | attrs | qual +---------+---------+-------+------ +(0 rows) + +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch2'); -- one row (included via schema) + pubname | relname | attrs | qual +-------------------+----------+-------+------ + pub_schema_except | tbl_sch2 | 1 | +(1 row) + -- two rows with different row filter SELECT * FROM test_gpt(ARRAY['pub_all', 'pub_normal'], 'tbl_normal'); pubname | relname | attrs | qual @@ -2517,6 +2681,7 @@ DROP PUBLICATION pub_all_no_viaroot; DROP PUBLICATION pub_all_except; DROP PUBLICATION pub_all_except_no_viaroot; DROP PUBLICATION pub_schema; +DROP PUBLICATION pub_schema_except; DROP PUBLICATION pub_normal; DROP PUBLICATION pub_part_leaf; DROP PUBLICATION pub_part_parent; @@ -2525,7 +2690,9 @@ DROP PUBLICATION pub_part_parent_child; DROP VIEW gpt_test_view; DROP TABLE tbl_normal, tbl_parent, tbl_part1; DROP SCHEMA gpt_test_sch CASCADE; -NOTICE: drop cascades to table gpt_test_sch.tbl_sch +NOTICE: drop cascades to 2 other objects +DETAIL: drop cascades to table gpt_test_sch.tbl_sch +drop cascades to table gpt_test_sch.tbl_sch2 -- stage objects for pg_dump tests CREATE SCHEMA pubme CREATE TABLE t0 (c int, d int) CREATE TABLE t1 (c int); CREATE SCHEMA pubme2 CREATE TABLE t0 (c int, d int); diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 041e14a4de6..2e79e9e4112 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -123,6 +123,9 @@ CREATE PUBLICATION testpub_foralltables_excepttable1 FOR ALL TABLES EXCEPT (TABL \d testpub_tbl1 -- fail - first table in the EXCEPT list should use TABLE keyword CREATE PUBLICATION testpub_foralltables_excepttable2 FOR ALL TABLES EXCEPT (testpub_tbl1, testpub_tbl2); +-- fail - EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testpub_tbl3); --------------------------------------------- -- SET ALL TABLES/SEQUENCES @@ -220,7 +223,83 @@ RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Create same-named tables in public to verify unqualified EXCEPT entries +-- are qualified with the named schema, not public +CREATE TABLE testpub_nopk (foo int, bar int); +CREATE TABLE testpub_tbl_s1 (a int primary key, b text); + +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + +-- Exclude multiple tables using unqualified names; same-named tables exist in +-- public to confirm unqualified names resolve to pub_test, not public +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); + +-- Multiple schemas each with their own EXCEPT clause +CREATE PUBLICATION testpub_schema_except_multi + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_schema_except_multi + +-- ALTER TABLE ... SET SCHEMA on a table excluded by a schema publication: +-- the schema-scoped exclusion is no longer meaningful once the table moves +-- out of its schema, so the exclusion is auto-removed. +CREATE PUBLICATION testpub_schema_except_setsch + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_schema_except_setsch +ALTER TABLE pub_test.testpub_tbl_s2 SET SCHEMA public; +\dRp+ testpub_schema_except_setsch +DROP PUBLICATION testpub_schema_except_setsch; +-- Restore for further tests +ALTER TABLE public.testpub_tbl_s2 SET SCHEMA pub_test; + +-- fail: table appears in both the explicit table list and the EXCEPT clause +CREATE PUBLICATION testpub_except_conflict + FOR TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: nonexistent table in EXCEPT clause +CREATE PUBLICATION testpub_except_norel + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- fail: partition cannot appear in EXCEPT clause; only root tables are allowed +CREATE TABLE pub_test.testpub_parted_s (a int) PARTITION BY LIST (a); +CREATE TABLE pub_test.testpub_part_s PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (1); +CREATE PUBLICATION testpub_except_partition + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); + +-- fail: TABLE keyword is required for the first entry in the EXCEPT clause +CREATE PUBLICATION testpub_except_nokw + FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + +-- Cleanup +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP TABLE pub_test.testpub_parted_s CASCADE; +DROP TABLE testpub_nopk, testpub_tbl_s1; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; + +--------------------------------------------- +-- Tests for publications with SEQUENCES +--------------------------------------------- CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; @@ -1189,6 +1268,18 @@ ALTER PUBLICATION testpub1_forschema SET TABLES IN SCHEMA pub_test1, pub_test1; ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo (a, b); ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b); +-- EXCEPT clause with CURRENT_SCHEMA: cross-schema entry must be rejected +SET search_path = pub_test1; +-- qualified name from wrong schema -> error +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.tbl1); +-- unqualified name implicitly qualified with current schema (pub_test1.tbl) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl); +RESET client_min_messages; +\dRp+ testpub_cursch_except +DROP PUBLICATION testpub_cursch_except; +RESET search_path; + -- cleanup pub_test1 schema for invalidation tests ALTER PUBLICATION testpub2_forschema DROP TABLES IN SCHEMA pub_test1; DROP PUBLICATION testpub3_forschema, testpub4_forschema, testpub5_forschema, testpub6_forschema, testpub_fortable; @@ -1443,6 +1534,7 @@ DROP ROLE regress_publication_user_dummy; -- Test pg_get_publication_tables(text[], oid) function CREATE SCHEMA gpt_test_sch; CREATE TABLE gpt_test_sch.tbl_sch (id int); +CREATE TABLE gpt_test_sch.tbl_sch2 (id int); CREATE TABLE tbl_normal (id int); CREATE TABLE tbl_parent (id1 int, id2 int, id3 int) PARTITION BY RANGE (id1); CREATE TABLE tbl_part1 PARTITION OF tbl_parent FOR VALUES FROM (1) TO (10); @@ -1454,6 +1546,7 @@ CREATE PUBLICATION pub_all_no_viaroot FOR ALL TABLES WITH (publish_via_partition CREATE PUBLICATION pub_all_except FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = true); CREATE PUBLICATION pub_all_except_no_viaroot FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_schema FOR TABLES IN SCHEMA gpt_test_sch; +CREATE PUBLICATION pub_schema_except FOR TABLES IN SCHEMA gpt_test_sch EXCEPT (TABLE gpt_test_sch.tbl_sch); CREATE PUBLICATION pub_normal FOR TABLE tbl_normal WHERE (id < 10); CREATE PUBLICATION pub_part_leaf FOR TABLE tbl_part1 WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_part_parent FOR TABLE tbl_parent (id1, id2) WHERE (id1 = 10) WITH (publish_via_partition_root = true); @@ -1510,6 +1603,10 @@ SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'gpt_test_sch.tbl_sch SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_parent'); -- no result (excluded) SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_part1'); -- no result +-- test for EXCEPT clause with schema publication +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch'); -- no result (excluded) +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch2'); -- one row (included via schema) + -- two rows with different row filter SELECT * FROM test_gpt(ARRAY['pub_all', 'pub_normal'], 'tbl_normal'); @@ -1538,6 +1635,7 @@ DROP PUBLICATION pub_all_no_viaroot; DROP PUBLICATION pub_all_except; DROP PUBLICATION pub_all_except_no_viaroot; DROP PUBLICATION pub_schema; +DROP PUBLICATION pub_schema_except; DROP PUBLICATION pub_normal; DROP PUBLICATION pub_part_leaf; DROP PUBLICATION pub_part_parent; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 8c58d282eee..18c7b2c1fca 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -24,14 +24,17 @@ my $result; sub test_except_root_partition { - my ($pubviaroot) = @_; + my ($pubviaroot, $pubsql) = @_; + $pubsql //= + "CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1)"; + $pubsql .= " WITH (publish_via_partition_root = $pubviaroot)"; # If the root partitioned table is in the EXCEPT clause, all its # partitions are excluded from publication, regardless of the # publish_via_partition_root setting. $node_publisher->safe_psql( 'postgres', qq( - CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1) WITH (publish_via_partition_root = $pubviaroot); + $pubsql; INSERT INTO root1 VALUES (1), (101); )); $node_subscriber->safe_psql('postgres', @@ -223,6 +226,131 @@ $node_subscriber->safe_psql( test_except_root_partition('false'); test_except_root_partition('true'); +# Same validation using TABLES IN SCHEMA instead of FOR ALL TABLES. +my $schema_pub = + "CREATE PUBLICATION tap_pub_part FOR TABLES IN SCHEMA public EXCEPT (TABLE public.root1)"; +test_except_root_partition('false', $schema_pub); +test_except_root_partition('true', $schema_pub); + +# ============================================ +# EXCEPT test cases for TABLES IN SCHEMA +# ============================================ + +# Create a dedicated schema with two tables: one to be published and one to be +# excluded. Also create inherited tables to verify ONLY semantics. +$node_publisher->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_published AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.tab_excluded AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.parent (a int); + CREATE TABLE sch1.child (b int) INHERITS (sch1.parent); +)); + +$node_subscriber->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_published (a int); + CREATE TABLE sch1.tab_excluded (a int); + CREATE TABLE sch1.parent (a int); + CREATE TABLE sch1.child (b int) INHERITS (sch1.parent); +)); + +# Basic test: initial sync respects EXCEPT. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_excluded)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: initial sync copies included table'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: initial sync skips excluded table'); + +# DML: only the included table should be replicated. +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (6); + INSERT INTO sch1.tab_excluded VALUES (6); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(6), + 'TABLES IN SCHEMA EXCEPT: DML on included table is replicated'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: DML on excluded table is not replicated'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Inherited tables: excluding the parent (without ONLY) also excludes the child. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.parent)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.child VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.child"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: excluding parent (without ONLY) also excludes child' +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Test that EXCEPT (TABLE ONLY parent) excludes only the parent itself, not its +# child. Truncate child first so rows from the previous test are not copied by +# the initial table sync of the next subscription. +$node_publisher->safe_psql('postgres', 'TRUNCATE sch1.child'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE sch1.child'); +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE ONLY sch1.parent)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.child VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.child"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: ONLY parent in EXCEPT does not exclude child'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Cleanup schema tables before the multi-publication section. +$node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); +$node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); + # ============================================ # Test when a subscription is subscribing to multiple publications # ============================================ @@ -254,6 +382,7 @@ $node_publisher->safe_psql( DROP PUBLICATION tap_pub2; TRUNCATE tab1; )); +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_subscriber->safe_psql('postgres', qq(TRUNCATE tab1)); # OK when a table is excluded by pub1 EXCEPT clause, but it is included by pub2 -- 2.50.1 (Apple Git-155)
v17-0002-Add-EXCEPT-support-to-ALTER-PUBLICATION-ADD-TABL.patch (application/octet-stream, 18.4K) download From 582e33e1a4f545c69cb3603167e198cc47fa72ce Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Wed, 1 Jul 2026 14:06:28 +0530 Subject: [PATCH v17 2/3] Add EXCEPT support to ALTER PUBLICATION ADD TABLES IN SCHEMA Extend the EXCEPT clause support to allow tables to be excluded when adding a schema to a publication via ALTER PUBLICATION ... ADD. Syntax: ALTER PUBLICATION pub ADD TABLES IN SCHEMA s EXCEPT (TABLE s.t1); Since pg_dump uses ALTER PUBLICATION ... ADD, support for it is included in this patch. --- src/backend/catalog/pg_publication.c | 19 +++-- src/backend/commands/publicationcmds.c | 98 ++++++++++++++++++++++- src/bin/pg_dump/pg_dump.c | 30 ++++++- src/bin/pg_dump/t/002_pg_dump.pl | 24 ++++++ src/bin/psql/tab-complete.in.c | 17 ++++ src/test/regress/expected/publication.out | 32 +++++++- src/test/regress/sql/publication.sql | 20 ++++- src/test/subscription/t/037_except.pl | 32 ++++++++ 8 files changed, 258 insertions(+), 14 deletions(-) diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index e7018ff565f..16a3b50711b 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -657,15 +657,18 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, * here, as CreatePublication() function invalidates all relations as part * of defining a FOR ALL TABLES publication. * - * For ALTER PUBLICATION, invalidation is needed only when adding an - * EXCEPT table to a publication already marked as ALL TABLES. For - * publications that were originally empty or defined as ALL SEQUENCES and - * are being converted to ALL TABLES, invalidation is skipped here, as - * AlterPublicationAllFlags() function invalidates all relations while - * marking the publication as ALL TABLES publication. + * For ALTER PUBLICATION, invalidation is needed when adding an EXCEPT + * table to either a FOR ALL TABLES publication (pub->alltables is true) + * or a FOR TABLES IN SCHEMA publication (is_schema_publication is true). + * The exception: when a publication is being converted to FOR ALL TABLES + * (pub->alltables is still false at this point), + * AlterPublicationAllFlags() will perform a full invalidation, so we skip + * it here. */ - inval_except_table = (alter_stmt != NULL) && pub->alltables && - (alter_stmt->for_all_tables && pri->except); + inval_except_table = (alter_stmt != NULL) && pri->except && + (pub->alltables + ? alter_stmt->for_all_tables + : is_schema_publication(pubid)); if (!pri->except || inval_except_table) { diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 45a8a5c3f71..542579dae86 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -70,6 +70,13 @@ static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok); static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); +static void AlterPublicationSchemas(AlterPublicationStmt *stmt, + HeapTuple tup, List *schemaidlist, + List *except_pubtables); +static void AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, + List *except_pubtables, + List *schemaidlist); static char defGetGeneratedColsOption(DefElem *def); static void CheckExceptNotInTableList(List *except_rels, List *explicitrelids); @@ -1509,7 +1516,8 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, */ static void AlterPublicationSchemas(AlterPublicationStmt *stmt, - HeapTuple tup, List *schemaidlist) + HeapTuple tup, List *schemaidlist, + List *except_pubtables) { Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); @@ -1586,6 +1594,88 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, */ PublicationAddSchemas(pubform->oid, schemaidlist, true, stmt); } + + /* + * Increment the command counter so that is_schema_publication() in + * GetExcludedPublicationTables() can see the just-inserted schema + * rows when AlterPublicationSchemaExceptTables runs next. + */ + if (stmt->action == AP_AddObjects || stmt->action == AP_SetObjects) + CommandCounterIncrement(); + + AlterPublicationSchemaExceptTables(stmt, tup, except_pubtables, schemaidlist); +} + +/* + * Alter the EXCEPT list of a schema-level publication. + * + * Adds, removes, or replaces except-table entries in pg_publication_rel + * (rows with prexcept = true). These entries suppress publication of the + * named tables that would otherwise be covered by a FOR TABLES IN SCHEMA + * clause. + */ +static void +AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, List *except_pubtables, + List *schemaidlist) +{ + Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); + Oid pubid = pubform->oid; + + /* + * Nothing to do if no EXCEPT entries. + */ + if (!except_pubtables) + return; + + /* + * This function handles EXCEPT entries for schema-level publications + * only. For FOR ALL TABLES publications, EXCEPT entries are already + * processed by AlterPublicationTables(). + */ + if (schemaidlist == NIL && !is_schema_publication(pubid)) + return; + + /* + * Dropping a schema from a publication removes all its EXCEPT entries via + * cascade. The concept of "drop all schema tables from the publication + * EXCEPT these ones" is not supported. + */ + if (stmt->action == AP_DropObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); + + /* + * XXX EXCEPT with SET is not currently implemented. Workaround: DROP and + * re-ADD the schema with the desired EXCEPT list. + */ + if (stmt->action == AP_SetObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"), + errhint("Drop and re-add the schema with the desired EXCEPT list."))); + + if (stmt->action == AP_AddObjects) + { + List *rels; + List *explicitrelids; + + rels = OpenTableList(except_pubtables); + + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + /* + * Validate that each excluded table is not also in the explicit table + * list (which would be contradictory). + */ + CheckExceptNotInTableList(rels, explicitrelids); + + PublicationAddTables(pubid, rels, false, stmt); + + CloseTableList(rels); + } } /* @@ -1795,10 +1885,12 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) errmsg("publication \"%s\" does not exist", stmt->pubname)); - relations = list_concat(relations, except_pubtables); + if (stmt->for_all_tables) + relations = list_concat(relations, except_pubtables); + AlterPublicationTables(stmt, tup, relations, pstate->p_sourcetext, schemaidlist != NIL); - AlterPublicationSchemas(stmt, tup, schemaidlist); + AlterPublicationSchemas(stmt, tup, schemaidlist, except_pubtables); AlterPublicationAllFlags(stmt, rel, tup); } diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c index c56437d6057..c2b2b88bb6c 100644 --- a/src/bin/pg_dump/pg_dump.c +++ b/src/bin/pg_dump/pg_dump.c @@ -5019,6 +5019,7 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) PublicationInfo *pubinfo = pubsinfo->publication; PQExpBuffer query; char *tag; + bool has_except = false; /* Do nothing if not dumping schema */ if (!dopt->dumpSchema) @@ -5029,7 +5030,34 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) query = createPQExpBuffer(); appendPQExpBuffer(query, "ALTER PUBLICATION %s ", fmtId(pubinfo->dobj.name)); - appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s;\n", fmtId(schemainfo->dobj.name)); + appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s", fmtId(schemainfo->dobj.name)); + + /* + * Append EXCEPT clause for any tables that belong to this schema + * and are excluded from the publication. + */ + for (SimplePtrListCell *cell = pubinfo->except_tables.head; cell; cell = cell->next) + { + TableInfo *tbinfo = (TableInfo *) cell->ptr; + + if (strcmp(tbinfo->dobj.namespace->dobj.name, schemainfo->dobj.name) == 0) + { + if (!has_except) + { + appendPQExpBufferStr(query, " EXCEPT ("); + has_except = true; + } + else + appendPQExpBufferStr(query, ", "); + + appendPQExpBuffer(query, "TABLE ONLY %s", fmtId(tbinfo->dobj.name)); + } + } + + if (has_except) + appendPQExpBufferStr(query, ")"); + + appendPQExpBufferStr(query, ";\n"); /* * There is no point in creating drop query as the drop is done by schema diff --git a/src/bin/pg_dump/t/002_pg_dump.pl b/src/bin/pg_dump/t/002_pg_dump.pl index 9258948b583..d18b3b0d7b9 100644 --- a/src/bin/pg_dump/t/002_pg_dump.pl +++ b/src/bin/pg_dump/t/002_pg_dump.pl @@ -3283,6 +3283,30 @@ my %tests = ( like => { %full_runs, section_post_data => 1, }, }, + 'CREATE PUBLICATION pub11' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub11 FOR TABLES IN SCHEMA dump_test EXCEPT (TABLE test_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub11 WITH (publish = 'insert, update, delete, truncate');\E + .*? + \QALTER PUBLICATION pub11 ADD TABLES IN SCHEMA dump_test EXCEPT (TABLE ONLY test_table);\E + /xms, + like => { %full_runs, section_post_data => 1, }, + }, + + 'CREATE PUBLICATION pub12' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub12 FOR TABLES IN SCHEMA dump_test EXCEPT (TABLE test_table, dump_test.test_second_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub12 WITH (publish = 'insert, update, delete, truncate');\E + .*? + \QALTER PUBLICATION pub12 ADD TABLES IN SCHEMA dump_test EXCEPT (TABLE ONLY test_table, TABLE ONLY test_second_table);\E + /xms, + like => { %full_runs, section_post_data => 1, }, + }, + 'CREATE SUBSCRIPTION sub1' => { create_order => 50, create_sql => 'CREATE SUBSCRIPTION sub1 diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index c20ba1d8c01..277ae97ad41 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2373,6 +2373,23 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); + /* After a single schema name in ADD context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 6efed0a0cce..c40a8884a8f 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -591,12 +591,42 @@ CREATE PUBLICATION testpub_except_nokw ERROR: syntax error at or near "testpub_nopk" LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); ^ +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; +-- fail: non-existing table in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- fail: EXCEPT table belongs to a different schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 1: ...xcept ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.tes... + ^ +-- fail: TABLE keyword is required for the first entry in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +ERROR: syntax error at or near "testpub_nopk" +LINE 1: ...lter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_no... + ^ +-- ADD: qualified and unqualified names; unqualified is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + "pub_test.testpub_tbl_s2" + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP TABLE pub_test.testpub_parted_s CASCADE; DROP TABLE testpub_nopk, testpub_tbl_s1; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi, testpub_alter_except; --------------------------------------------- -- Tests for publications with SEQUENCES --------------------------------------------- diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 2e79e9e4112..cd5ed06dcad 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -290,12 +290,30 @@ CREATE PUBLICATION testpub_except_partition CREATE PUBLICATION testpub_except_nokw FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; + +-- fail: non-existing table in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- fail: EXCEPT table belongs to a different schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- fail: TABLE keyword is required for the first entry in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + +-- ADD: qualified and unqualified names; unqualified is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); +\dRp+ testpub_alter_except + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP TABLE pub_test.testpub_parted_s CASCADE; DROP TABLE testpub_nopk, testpub_tbl_s1; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi, testpub_alter_except; --------------------------------------------- -- Tests for publications with SEQUENCES diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 18c7b2c1fca..0ba6d6f8bb2 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -347,6 +347,38 @@ is($result, qq(5), $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); +# ============================================ +# ALTER PUBLICATION EXCEPT for TABLES IN SCHEMA +# ============================================ + +# Truncate subscriber tables to remove data accumulated from previous tests. +$node_subscriber->safe_psql('postgres', + 'TRUNCATE sch1.tab_published, sch1.tab_excluded, sch1.parent, sch1.child'); + +# ADD: add a schema with an excepted table; verify the except entry takes effect. +$node_publisher->safe_psql('postgres', "CREATE PUBLICATION sch_pub"); +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub ADD TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_excluded)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(6), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: included table synced'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + # Cleanup schema tables before the multi-publication section. $node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); $node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); -- 2.50.1 (Apple Git-155)
v17-0003-Add-EXCEPT-support-to-ALTER-PUBLICATION-SET-TABL.patch (application/octet-stream, 26.0K) download From fb1599b790933ec9e3836f14a189fc5148db5cfe Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Thu, 18 Jun 2026 11:32:32 +0530 Subject: [PATCH v17 3/3] Add EXCEPT support to ALTER PUBLICATION SET TABLES IN SCHEMA Extend AlterPublicationExceptTables() with the AP_SetObjects case, which redefines the publication and replaces the entire EXCEPT list. Syntax: ALTER PUBLICATION pub SET TABLES IN SCHEMA s EXCEPT (TABLE t1); This patch also cleans up EXCEPT entries when a schema is dropped from the publication. --- src/backend/commands/publicationcmds.c | 170 ++++++++++++++++++---- src/bin/psql/tab-complete.in.c | 17 +++ src/test/regress/expected/publication.out | 103 +++++++++++++ src/test/regress/sql/publication.sql | 44 ++++++ src/test/subscription/t/037_except.pl | 85 +++++++++++ 5 files changed, 394 insertions(+), 25 deletions(-) diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 542579dae86..00f8d003779 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -66,7 +66,8 @@ static void CloseTableList(List *rels); static void LockSchemaList(List *schemalist); static void PublicationAddTables(Oid pubid, List *rels, bool if_not_exists, AlterPublicationStmt *stmt); -static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok); +static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok, + bool delete_excluded); static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); @@ -1360,7 +1361,7 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, PublicationAddTables(pubid, rels, false, stmt); } else if (stmt->action == AP_DropObjects) - PublicationDropTables(pubid, rels, false); + PublicationDropTables(pubid, rels, false, false); else /* AP_SetObjects */ { List *oldrelids = NIL; @@ -1495,7 +1496,7 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, } /* And drop them. */ - PublicationDropTables(pubid, delrels, true); + PublicationDropTables(pubid, delrels, true, true); /* * Don't bother calculating the difference for adding, we'll catch and @@ -1597,8 +1598,8 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, /* * Increment the command counter so that is_schema_publication() in - * GetExcludedPublicationTables() can see the just-inserted schema - * rows when AlterPublicationSchemaExceptTables runs next. + * GetExcludedPublicationTables() can see the just-inserted schema rows + * when AlterPublicationSchemaExceptTables runs next. */ if (stmt->action == AP_AddObjects || stmt->action == AP_SetObjects) CommandCounterIncrement(); @@ -1616,16 +1617,18 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, */ static void AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, - HeapTuple tup, List *except_pubtables, - List *schemaidlist) + HeapTuple tup, List *except_pubtables, + List *schemaidlist) { Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); Oid pubid = pubform->oid; /* - * Nothing to do if no EXCEPT entries. + * Nothing to do if there are no EXCEPT entries, unless handling the SET + * command, because if the user has removed all exceptions we need to drop + * any existing ones. */ - if (!except_pubtables) + if (!except_pubtables && stmt->action != AP_SetObjects) return; /* @@ -1646,16 +1649,6 @@ AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); - /* - * XXX EXCEPT with SET is not currently implemented. Workaround: DROP and - * re-ADD the schema with the desired EXCEPT list. - */ - if (stmt->action == AP_SetObjects) - ereport(ERROR, - (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"), - errhint("Drop and re-add the schema with the desired EXCEPT list."))); - if (stmt->action == AP_AddObjects) { List *rels; @@ -1674,6 +1667,75 @@ AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, PublicationAddTables(pubid, rels, false, stmt); + CloseTableList(rels); + } + else /* AP_SetObjects */ + { + List *oldexceptrelids = NIL; + List *newexceptrelids = NIL; + List *delrelids = NIL; + List *rels; + List *explicitrelids; + + rels = OpenTableList(except_pubtables); + + /* Collect OIDs of the desired new EXCEPT list. */ + foreach_ptr(PublicationRelInfo, pri, rels) + newexceptrelids = lappend_oid(newexceptrelids, + RelationGetRelid(pri->relation)); + + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + /* + * Validate that each excluded table is not also in the explicit table + * list (which would be contradictory). + */ + CheckExceptNotInTableList(rels, explicitrelids); + + /* + * Get the current set of EXCEPT entries. Only FOR ALL TABLES and + * schema-level publications can have EXCEPT entries; for any other + * publication type oldexceptrelids stays NIL. + * + * Note: we check is_schema_publication() against the current catalog + * state (before AlterPublicationSchemas has run), so if the caller is + * doing SET TABLE t1 to convert a schema publication into a plain + * table publication, is_schema_publication() still returns true here. + * That is intentional: it lets us discover and clean up any stale + * EXCEPT entries that belong to the old schema definition. + */ + if (GetPublication(pubid)->alltables || is_schema_publication(pubid)) + oldexceptrelids = GetExcludedPublicationTables(pubid, + PUBLICATION_PART_ROOT); + + /* Build a list of old EXCEPT entries not present in the new list. */ + foreach_oid(oldrelid, oldexceptrelids) + { + if (!list_member_oid(newexceptrelids, oldrelid)) + delrelids = lappend_oid(delrelids, oldrelid); + } + + /* Drop old EXCEPT entries not present in the new list. */ + foreach_oid(relid, delrelids) + { + Oid proid; + ObjectAddress obj; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + /* Add new EXCEPT entries, skipping any already present. */ + PublicationAddTables(pubid, rels, true, stmt); + CloseTableList(rels); } } @@ -2297,29 +2359,54 @@ PublicationAddTables(Oid pubid, List *rels, bool if_not_exists, /* * Remove listed tables from the publication. + * + * delete_excluded controls how EXCEPT (prexcept=true) rows are handled: + * true - delete them silently. Used by the SET path to clear stale + * EXCEPT rows that are being replaced by a new EXCEPT list. + * false - treat them as "not a member". Used by ALTER ... DROP TABLE: an + * EXCEPT entry is not something DROP TABLE is expected to remove. */ static void -PublicationDropTables(Oid pubid, List *rels, bool missing_ok) +PublicationDropTables(Oid pubid, List *rels, bool missing_ok, + bool delete_excluded) { ObjectAddress obj; ListCell *lc; - Oid prid; foreach(lc, rels) { PublicationRelInfo *pubrel = (PublicationRelInfo *) lfirst(lc); Relation rel = pubrel->relation; Oid relid = RelationGetRelid(rel); + HeapTuple tup; + Form_pg_publication_rel pubrelform; + Oid prid = InvalidOid; + bool is_except = false; if (pubrel->columns) ereport(ERROR, errcode(ERRCODE_SYNTAX_ERROR), errmsg("column list must not be specified in ALTER PUBLICATION ... DROP")); - prid = GetSysCacheOid2(PUBLICATIONRELMAP, Anum_pg_publication_rel_oid, - ObjectIdGetDatum(relid), - ObjectIdGetDatum(pubid)); - if (!OidIsValid(prid)) + tup = SearchSysCache2(PUBLICATIONRELMAP, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (HeapTupleIsValid(tup)) + { + pubrelform = (Form_pg_publication_rel) GETSTRUCT(tup); + is_except = pubrelform->prexcept; + prid = pubrelform->oid; + ReleaseSysCache(tup); + } + + /* + * DROP TABLE operates only on regular member rows. A missing row + * or an EXCEPT row both mean "not a member" from the user's + * perspective, so we treat them the same way. The SET-cleanup + * caller (delete_excluded = true) intends to remove EXCEPT rows + * and so bypasses the EXCEPT half of this check. + */ + if (!OidIsValid(prid) || (is_except && !delete_excluded)) { if (missing_ok) continue; @@ -2379,6 +2466,7 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) foreach(lc, schemas) { Oid schemaid = lfirst_oid(lc); + List *except_relids; psid = GetSysCacheOid2(PUBLICATIONNAMESPACEMAP, Anum_pg_publication_namespace_oid, @@ -2395,8 +2483,40 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) get_namespace_name(schemaid)))); } + /* + * Collect EXCEPT entries for tables belonging to this schema before + * removing the schema entry. + */ + except_relids = GetExcludedPublicationTables(pubid, PUBLICATION_PART_ROOT); + ObjectAddressSet(obj, PublicationNamespaceRelationId, psid); performDeletion(&obj, DROP_CASCADE, 0); + + /* + * Drop any prexcept rows for tables belonging to this schema. These + * rows have no pg_depend entry pointing at the + * pg_publication_namespace row, so they are not cascaded by the + * performDeletion() call above and must be cleaned up explicitly. + */ + foreach_oid(relid, except_relids) + { + Oid proid; + + if (get_rel_namespace(relid) != schemaid) + continue; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + list_free(except_relids); } } diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index 277ae97ad41..b7841503573 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2390,6 +2390,23 @@ match_previous_words(int pattern_id, } else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) COMPLETE_WITH(")"); + /* After a single schema name in SET context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index c40a8884a8f..6be5b163d99 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -621,6 +621,109 @@ Except tables: "pub_test.testpub_tbl_s1" "pub_test.testpub_tbl_s2" +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s2" + +-- fail: table in EXCEPT clause also appears in the explicit table list +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot appear in both the table list and the EXCEPT clause +-- error: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 1: ...xcept SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.tes... + ^ +-- SET: unqualified name in EXCEPT is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- SET without EXCEPT clears the existing except list +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + +-- SET to a different schema removes old schema's EXCEPT entries +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA public; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "public" + +-- fail: nonexistent table in EXCEPT clause (SET path) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- SET: multiple schemas each with their own EXCEPT clause +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- error: ALTER PUBLICATION ... DROP TABLE on an excluded table is rejected +-- with "not part of the publication" — an EXCEPT entry is not a member. +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_tbl_s1; +ERROR: relation "testpub_tbl_s1" is not part of the publication +-- the EXCEPT entry is still present after the rejected DROP TABLE +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- error: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +ERROR: EXCEPT clause is not supported with DROP in ALTER PUBLICATION +-- DROP TABLES IN SCHEMA removes associated EXCEPT entries +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "public" +Except tables: + "public.testpub_tbl1" + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index cd5ed06dcad..f684e75d6f4 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -308,6 +308,50 @@ ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (tes ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); \dRp+ testpub_alter_except +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + +-- fail: table in EXCEPT clause also appears in the explicit table list +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- error: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- SET: unqualified name in EXCEPT is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +\dRp+ testpub_alter_except + +-- SET without EXCEPT clears the existing except list +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + +-- SET to a different schema removes old schema's EXCEPT entries +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA public; +\dRp+ testpub_alter_except + +-- fail: nonexistent table in EXCEPT clause (SET path) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- SET: multiple schemas each with their own EXCEPT clause +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_alter_except + +-- error: ALTER PUBLICATION ... DROP TABLE on an excluded table is rejected +-- with "not part of the publication" — an EXCEPT entry is not a member. +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_tbl_s1; +-- the EXCEPT entry is still present after the rejected DROP TABLE +\dRp+ testpub_alter_except + +-- error: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); + +-- DROP TABLES IN SCHEMA removes associated EXCEPT entries +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 0ba6d6f8bb2..01eafb5b7c8 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -376,6 +376,61 @@ $result = is($result, qq(0), 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); +# SET: replace the except list; tab_excluded is now included and tab_published is excluded. +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_published)" +); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (7); + INSERT INTO sch1.tab_excluded VALUES (7); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded WHERE a = 7"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: newly included table is replicated' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published WHERE a = 7"); +is($result, qq(0), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: now-excluded table is not replicated' +); + +# SET without EXCEPT: clears the except list; both tables are now published. +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1"); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (8); + INSERT INTO sch1.tab_excluded VALUES (8); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published WHERE a = 8"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_published replicated after except list cleared' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded WHERE a = 8"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_excluded replicated after except list cleared' +); + $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); @@ -443,6 +498,36 @@ $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); +# OK when a table is excluded by a TABLES IN SCHEMA EXCEPT publication, +# but is included by another publication. +$node_publisher->safe_psql('postgres', 'TRUNCATE tab1'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE tab1'); + +$node_publisher->safe_psql( + 'postgres', qq( + CREATE PUBLICATION tap_pub1 FOR TABLES IN SCHEMA public EXCEPT (TABLE public.tab1); + CREATE PUBLICATION tap_pub2 FOR TABLE tab1; + INSERT INTO tab1 VALUES(1); +)); +$node_subscriber->psql('postgres', + "CREATE SUBSCRIPTION tap_sub CONNECTION '$publisher_connstr' PUBLICATION tap_pub1, tap_pub2" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'tap_sub'); + +$node_publisher->safe_psql('postgres', qq(INSERT INTO tab1 VALUES(2))); +$node_publisher->wait_for_catchup('tap_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT * FROM tab1 ORDER BY a"); +is( $result, qq(1 +2), + "TABLES IN SCHEMA EXCEPT: table excluded in schema pub but included by another pub is replicated" +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); + $node_publisher->stop('fast'); done_testing(); -- 2.50.1 (Apple Git-155)
^ permalink raw reply [nested|flat] 196+ messages in thread

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-01 10:12  Nisha Moond <nisha.moond412@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  1 sibling, 1 reply; 196+ messages in thread

From: Nisha Moond @ 2026-07-01 10:12 UTC (permalink / raw)
  To: shveta malik <shveta.malik@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

During tests, I found one behavior that needs discussion:

Consider a partition hierarchy where the root table is in schema s2, a
child partition is in schema s1, and the publication includes both
schemas but excludes only the root table.
Test case:
-- Root of the partition tree lives in s2
  CREATE TABLE s2.parent (id int) PARTITION BY LIST (id);

-- Child partition lives in s1
  CREATE TABLE s1.part PARTITION OF s2.parent FOR VALUES IN (1, 2, 3);

-- Publication covers BOTH schemas, but EXCEPTs only s2.parent
  CREATE PUBLICATION p FOR TABLES IN SCHEMA s1, TABLES IN SCHEMA s2
EXCEPT (TABLE s2.parent);

Currently, if the root is excluded, all child partitions are also
excluded, meaning s1.part is not published. However, s1 never excluded
'part' explicitly, so the behavior may not be intuitive.

We need to decide whether child partitions should always remain
excluded when the root is excluded (regardless of schema), or whether
schema membership should still allow publication.

I've added an XXX comment in pg_publication.c to track this until we
conclude on the expected behavior. Suggestions are welcome.

--
Thanks,
Nisha





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-01 10:16  shveta malik <shveta.malik@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  1 sibling, 1 reply; 196+ messages in thread

From: shveta malik @ 2026-07-01 10:16 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; shveta malik <shveta.malik@gmail.com>

On Wed, Jul 1, 2026 at 3:37 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
>
>
> Besides the above comments, I found and fixed a few additional issues
> during further testing:
> 1) Fixed an issue where UPDATE/DELETE on an excluded table without
> replica identity was still blocked. e.g.,
>
> postgres=# create publication pub_h2 for tables in schema s1 except ( table t1);
> postgres=# update s1.t1 set c1=3 where c1=1;
> ERROR: cannot update table "t1" because it does not have a replica
> identity and publishes updates
> HINT: To enable updating the table, set REPLICA IDENTITY using ALTER TABLE.
>
> Excluded tables should not be treated as published for update/delete checks.

Nisha, this bug was introduced by your patch or does it exist in 'ALL
TABLES Except TABLE' too?

thanks
Shveta





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-01 10:24  shveta malik <shveta.malik@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: shveta malik @ 2026-07-01 10:24 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; shveta malik <shveta.malik@gmail.com>

On Wed, Jul 1, 2026 at 3:42 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
>
> During tests, I found one behavior that needs discussion:
>
> Consider a partition hierarchy where the root table is in schema s2, a
> child partition is in schema s1, and the publication includes both
> schemas but excludes only the root table.

This is the exact scenario I had in mind when reviewing
'get_rel_sync_entry-->GetTopMostAncestorInPublication' flow, thus I
suggested adding comments about intentionally fetching the 'Exclude
list' only for the Root. I was about to test it in my next review
cycle.

The first thought is that if root is excluded, the partition should
also be excluded to maintain consistency with the 'ALL TABLES Except
ROOT' behaviour. But then it needs to be documented too. This is my
initial understanding, but I will think more when I resume the review.

> Test case:
> -- Root of the partition tree lives in s2
>   CREATE TABLE s2.parent (id int) PARTITION BY LIST (id);
>
> -- Child partition lives in s1
>   CREATE TABLE s1.part PARTITION OF s2.parent FOR VALUES IN (1, 2, 3);
>
> -- Publication covers BOTH schemas, but EXCEPTs only s2.parent
>   CREATE PUBLICATION p FOR TABLES IN SCHEMA s1, TABLES IN SCHEMA s2
> EXCEPT (TABLE s2.parent);
>
> Currently, if the root is excluded, all child partitions are also
> excluded, meaning s1.part is not published. However, s1 never excluded
> 'part' explicitly, so the behavior may not be intuitive.
>
> We need to decide whether child partitions should always remain
> excluded when the root is excluded (regardless of schema), or whether
> schema membership should still allow publication.
>
> I've added an XXX comment in pg_publication.c to track this until we
> conclude on the expected behavior. Suggestions are welcome.
>
> --
> Thanks,
> Nisha





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-02 04:51  Nisha Moond <nisha.moond412@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: Nisha Moond @ 2026-07-02 04:51 UTC (permalink / raw)
  To: shveta malik <shveta.malik@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Wed, Jul 1, 2026 at 3:46 PM shveta malik <shveta.malik@gmail.com> wrote:
>
> On Wed, Jul 1, 2026 at 3:37 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
> >
> >
> > Besides the above comments, I found and fixed a few additional issues
> > during further testing:
> > 1) Fixed an issue where UPDATE/DELETE on an excluded table without
> > replica identity was still blocked. e.g.,
> >
> > postgres=# create publication pub_h2 for tables in schema s1 except ( table t1);
> > postgres=# update s1.t1 set c1=3 where c1=1;
> > ERROR: cannot update table "t1" because it does not have a replica
> > identity and publishes updates
> > HINT: To enable updating the table, set REPLICA IDENTITY using ALTER TABLE.
> >
> > Excluded tables should not be treated as published for update/delete checks.
>
> Nisha, this bug was introduced by your patch or does it exist in 'ALL
> TABLES Except TABLE' too?
>

The same case for 'ALL TABLES Except Table' was already handled
correctly as part of that feature (Ref
-RelationBuildPublicationDesc()). The bug was only in my patch where I
missed handling it earlier.

--
Thanks,
Nisha





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-02 08:49  shveta malik <shveta.malik@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: shveta malik @ 2026-07-02 08:49 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; shveta malik <shveta.malik@gmail.com>

On Thu, Jul 2, 2026 at 10:21 AM Nisha Moond <nisha.moond412@gmail.com> wrote:
>
> On Wed, Jul 1, 2026 at 3:46 PM shveta malik <shveta.malik@gmail.com> wrote:
> >
> > On Wed, Jul 1, 2026 at 3:37 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
> > >
> > >
> > > Besides the above comments, I found and fixed a few additional issues
> > > during further testing:
> > > 1) Fixed an issue where UPDATE/DELETE on an excluded table without
> > > replica identity was still blocked. e.g.,
> > >
> > > postgres=# create publication pub_h2 for tables in schema s1 except ( table t1);
> > > postgres=# update s1.t1 set c1=3 where c1=1;
> > > ERROR: cannot update table "t1" because it does not have a replica
> > > identity and publishes updates
> > > HINT: To enable updating the table, set REPLICA IDENTITY using ALTER TABLE.
> > >
> > > Excluded tables should not be treated as published for update/delete checks.
> >
> > Nisha, this bug was introduced by your patch or does it exist in 'ALL
> > TABLES Except TABLE' too?
> >
>
> The same case for 'ALL TABLES Except Table' was already handled
> correctly as part of that feature (Ref
> -RelationBuildPublicationDesc()). The bug was only in my patch where I
> missed handling it earlier.
>

Okay, then we are good.

A few comments:

1)
postgres=# alter publication pub1 add table s2.t1;
ERROR:  table "s2.t1" cannot be added because it is excluded from
publication "pub1"

It will be good to add hint in above error.

Suggestion:
ERROR: cannot add table "s2.t1" to publication "pub1"
DETAIL: Table "s2.t1" is currently in EXCEPT list
HINT: Change EXCEPT list using ALTER PUBLICATION ..SET TABLES IN
SCHEMA .. EXCEPT

Please rephrase above as needed. Look earlier such messages/hints
already added for ALL TABLES.

From the user's perspective, it seems slightly odd that if he has
excluded a table from publication, he can not add it back using 'add
table'. Was this point discussed earlier?

2)
Currently:
postgres=# alter publication pub1 drop table s2.t1;
ERROR:  relation "t1" is not part of the publication

s2.t1 is EXCEPT list here.

Should we have below error for this case rather than above generic
error, it will be more intuitive for user. Plus both add and drop
table commands will have similar error-style for EXCEPT list.
Thoughts?

ERROR: cannot drop table "s2.t1" from publication "pub1"
DETAIL: Table "s2.t1" is currently in EXCEPT list
HINT: Change EXCEPT list using ALTER PUBLICATION ..SET TABLES IN
SCHEMA .. EXCEPT

3)
Please see below test:

--Setting Except list for pub1 which has all tables of s2 included:
alter publication pub1 set tables in schema s2 EXCEPT ( TABLE t1, t2);

--pg_publication_rel entries:
pubname | schema_name | table_name | prexcept
--------+-------------+------------+---------
pub1    | s2          | t1         | t
pub1    | s2          | t2         | t


--Then added a partition:
alter publication pub1 add table s2.tab_part_1_p2;

--pg_publication_rel entries:
pubname | schema_name |  table_name   | prexcept
--------+-------------+---------------+---------
pub1    | s2          | t1            | t
pub1    | s2          | t2            | t
pub1    | s2          | tab_part_1_p2 | f


--Then changed pub1 to exclude tab_root (parent of tab_part_1_p2) as well:

alter publication pub1 set tables in schema s2 EXCEPT ( TABLE t1, t2, tab_root);

--pg_publication_rel entries:
pubname | schema_name | table_name | prexcept
--------+-------------+------------+---------
pub1    | s2          | t1         | t
pub1    | s2          | t2         | t
pub1    | s2          | tab_root   | t

Note theoutput above, tab_part_1_p2 is removed internally as part of
earlier command since its parent tab_root is now excluded.

--Now add parition back, it allowed to add it:
alter publication pub1 add table s2.tab_part_1_p2;

pg_publication_rel entries:
pubname | schema_name |  table_name   | prexcept
--------+-------------+---------------+---------
pub1    | s2          | t1            | t
pub1    | s2          | t2            | t
pub1    | s2          | tab_root      | t
pub1    | s2          | tab_part_1_p2 | f


FOR ALL TABLES publicaiton, if root is excluded, there is no way
publication can have parition included independently. Same should hold
true here. Thoughts?

thanks
Shveta





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-02 09:03  Amit Kapila <amit.kapila16@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: Amit Kapila @ 2026-07-02 09:03 UTC (permalink / raw)
  To: shveta malik <shveta.malik@gmail.com>; +Cc: Nisha Moond <nisha.moond412@gmail.com>; Peter Smith <smithpb2250@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Wed, Jul 1, 2026 at 3:54 PM shveta malik <shveta.malik@gmail.com> wrote:
>
> On Wed, Jul 1, 2026 at 3:42 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
> >
> > During tests, I found one behavior that needs discussion:
> >
> > Consider a partition hierarchy where the root table is in schema s2, a
> > child partition is in schema s1, and the publication includes both
> > schemas but excludes only the root table.
>
> This is the exact scenario I had in mind when reviewing
> 'get_rel_sync_entry-->GetTopMostAncestorInPublication' flow, thus I
> suggested adding comments about intentionally fetching the 'Exclude
> list' only for the Root. I was about to test it in my next review
> cycle.
>
> The first thought is that if root is excluded, the partition should
> also be excluded to maintain consistency with the 'ALL TABLES Except
> ROOT' behaviour. But then it needs to be documented too.
>

+1. It is good to be consistent here with similar ALL TABLES case.
BTW, as we can't exclude the child table explicitly, this anyway seems
like the only option because otherwise, users won't have any way to
exclude the child table.

-- 
With Regards,
Amit Kapila.





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-03 16:45  Nisha Moond <nisha.moond412@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  0 siblings, 4 replies; 196+ messages in thread

From: Nisha Moond @ 2026-07-03 16:45 UTC (permalink / raw)
  To: shveta malik <shveta.malik@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Thu, Jul 2, 2026 at 2:19 PM shveta malik <shveta.malik@gmail.com> wrote:
>
> A few comments:
>
> 1)
> postgres=# alter publication pub1 add table s2.t1;
> ERROR:  table "s2.t1" cannot be added because it is excluded from
> publication "pub1"
>
> It will be good to add hint in above error.
>
> Suggestion:
> ERROR: cannot add table "s2.t1" to publication "pub1"
> DETAIL: Table "s2.t1" is currently in EXCEPT list
> HINT: Change EXCEPT list using ALTER PUBLICATION ..SET TABLES IN
> SCHEMA .. EXCEPT
>
> Please rephrase above as needed. Look earlier such messages/hints
> already added for ALL TABLES.
>

Updated the error as suggested, with a slight change in DETAIL message.

> From the user's perspective, it seems slightly odd that if he has
> excluded a table from publication, he can not add it back using 'add
> table'. Was this point discussed earlier?
>

This hasn't been discussed yet.

I kept the current behavior, as IMO, it is hard to tell whether the
user is trying to re-include a table or whether the ADD is unintended
and should be blocked. To avoid ambiguity, I think EXCEPT entries
should be modified only through the EXCEPT (...) clause itself, such
as ALTER PUBLICATION ... ADD/SET ... EXCEPT(TABLE ...), or by omitting
EXCEPT in the SET case.

This would also keep the behavior of ADD TABLE and DROP TABLE aligned,
as both would operate only on the include list without touching the
EXCEPT list.
I think this also aligns with FOR ALL TABLES, where ADD TABLE is
disallowed, so the EXCEPT list can only be modified through SET ..
EXCEPT (...).

Thoughts?

> 2)
> Currently:
> postgres=# alter publication pub1 drop table s2.t1;
> ERROR:  relation "t1" is not part of the publication
>
> s2.t1 is EXCEPT list here.
>
> Should we have below error for this case rather than above generic
> error, it will be more intuitive for user. Plus both add and drop
> table commands will have similar error-style for EXCEPT list.
> Thoughts?
>
> ERROR: cannot drop table "s2.t1" from publication "pub1"
> DETAIL: Table "s2.t1" is currently in EXCEPT list
> HINT: Change EXCEPT list using ALTER PUBLICATION ..SET TABLES IN
> SCHEMA .. EXCEPT
>

Makes sense. Fixed.

> 3)
> Please see below test:
>
> --Setting Except list for pub1 which has all tables of s2 included:
> alter publication pub1 set tables in schema s2 EXCEPT ( TABLE t1, t2);
>
> --pg_publication_rel entries:
> pubname | schema_name | table_name | prexcept
> --------+-------------+------------+---------
> pub1    | s2          | t1         | t
> pub1    | s2          | t2         | t
>
>
> --Then added a partition:
> alter publication pub1 add table s2.tab_part_1_p2;
>
> --pg_publication_rel entries:
> pubname | schema_name |  table_name   | prexcept
> --------+-------------+---------------+---------
> pub1    | s2          | t1            | t
> pub1    | s2          | t2            | t
> pub1    | s2          | tab_part_1_p2 | f
>
>
> --Then changed pub1 to exclude tab_root (parent of tab_part_1_p2) as well:
>
> alter publication pub1 set tables in schema s2 EXCEPT ( TABLE t1, t2, tab_root);
>
> --pg_publication_rel entries:
> pubname | schema_name | table_name | prexcept
> --------+-------------+------------+---------
> pub1    | s2          | t1         | t
> pub1    | s2          | t2         | t
> pub1    | s2          | tab_root   | t
>
> Note theoutput above, tab_part_1_p2 is removed internally as part of
> earlier command since its parent tab_root is now excluded.
>
> --Now add parition back, it allowed to add it:
> alter publication pub1 add table s2.tab_part_1_p2;
>
> pg_publication_rel entries:
> pubname | schema_name |  table_name   | prexcept
> --------+-------------+---------------+---------
> pub1    | s2          | t1            | t
> pub1    | s2          | t2            | t
> pub1    | s2          | tab_root      | t
> pub1    | s2          | tab_part_1_p2 | f
>
>
> FOR ALL TABLES publicaiton, if root is excluded, there is no way
> publication can have parition included independently. Same should hold
> true here. Thoughts?

Right, based on the discussion at [1], since we follow "all partitions
are excluded if the root is excluded", a partition child should not be
allowed to be added when its partition root is already excluded from
the publication.
Fixed. Such an operation will now raise an error:

postgres=# alter publication pub2 add table t_part_p1;
ERROR:  cannot add table "public.t_part_p1" to publication "pub2"
DETAIL:  Partition ancestor "public.t_part" of table
"public.t_part_p1" is currently listed in the EXCEPT clause of the
publication.
HINT:  Change EXCEPT list using ALTER PUBLICATION ... SET TABLES IN
SCHEMA ... EXCEPT.
~~~

Attached are the updated patches v18.

[1] https://www.postgresql.org/message-id/CAA4eK1%2BNmQRjSHPLr0X8YBuC6joivFqgsY3_qJ5-RnuuwNGkRQ%40mail.g...
--
Thanks,
Nisha

Attachments: download all (4 files, .tar.gz)

v18-0001-Support-EXCEPT-clause-for-schema-level-publicati.patch (application/x-patch, 69.2K) download From d0be6cb9e0b77728659f7b7f32507523294e5cba Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Tue, 16 Jun 2026 10:58:49 +0530 Subject: [PATCH v18 1/4] Support EXCEPT clause for schema-level publications Extend table exclusion support in publications to allow specific tables to be excluded from schema-level publications using an EXCEPT clause in CREATE PUBLICATION. Supported syntax: CREATE PUBLICATION <pub> FOR TABLES IN SCHEMA s EXCEPT (TABLE t1,...); --- src/backend/catalog/pg_publication.c | 244 ++++++++++++++++---- src/backend/commands/publicationcmds.c | 162 ++++++++++++- src/backend/commands/tablecmds.c | 11 + src/backend/parser/gram.y | 54 ++++- src/backend/replication/pgoutput/pgoutput.c | 39 +++- src/backend/utils/cache/relcache.c | 41 ++-- src/bin/psql/describe.c | 18 ++ src/bin/psql/tab-complete.in.c | 35 ++- src/include/catalog/pg_publication.h | 3 +- src/include/commands/publicationcmds.h | 2 + src/include/nodes/parsenodes.h | 2 + src/test/regress/expected/publication.out | 180 ++++++++++++++- src/test/regress/sql/publication.sql | 107 ++++++++- src/test/subscription/t/037_except.pl | 133 ++++++++++- 14 files changed, 943 insertions(+), 88 deletions(-) diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index 1ec94c851b2..ce0f6d5b8c1 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -53,9 +53,10 @@ typedef struct * error if not. */ static void -check_publication_add_relation(PublicationRelInfo *pri) +check_publication_add_relation(PublicationRelInfo *pri, Oid pubid) { Relation targetrel = pri->relation; + Oid relid = RelationGetRelid(targetrel); const char *relname; const char *errormsg; @@ -110,6 +111,48 @@ check_publication_add_relation(PublicationRelInfo *pri) (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg(errormsg, relname), errdetail("This operation is not supported for unlogged tables."))); + + /* + * A partition cannot be independently included when any of its partition + * ancestors is in this publication's EXCEPT list. Doing so would leave + * the catalog inconsistent (root excluded, partition explicitly included) + * and the ancestor-cascade rule would silently override the include at + * replication time. Individual partitions cannot appear in EXCEPT + * (rejected above), so this check only applies to non-EXCEPT adds. + */ + if (!pri->except && targetrel->rd_rel->relispartition) + { + List *ancestors = get_partition_ancestors(relid); + + foreach_oid(ancestor, ancestors) + { + HeapTuple atup; + bool ancestor_except; + + atup = SearchSysCache2(PUBLICATIONRELMAP, + ObjectIdGetDatum(ancestor), + ObjectIdGetDatum(pubid)); + if (!HeapTupleIsValid(atup)) + continue; + + ancestor_except = ((Form_pg_publication_rel) GETSTRUCT(atup))->prexcept; + ReleaseSysCache(atup); + + if (ancestor_except) + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("cannot add table \"%s\" to publication \"%s\"", + RelationGetQualifiedRelationName(targetrel), + get_publication_name(pubid, false)), + errdetail("Partition ancestor \"%s\" of table \"%s\" is currently listed in the EXCEPT clause of the publication.", + quote_qualified_identifier(get_namespace_name(get_rel_namespace(ancestor)), + get_rel_name(ancestor)), + RelationGetQualifiedRelationName(targetrel)), + errhint("Change EXCEPT list using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT."))); + } + + list_free(ancestors); + } } /* @@ -340,19 +383,20 @@ is_table_publication(Oid pubid) scan = systable_beginscan(pubrelsrel, PublicationRelPrpubidIndexId, true, NULL, 1, &scankey); - tup = systable_getnext(scan); - if (HeapTupleIsValid(tup)) - { - Form_pg_publication_rel pubrel; - - pubrel = (Form_pg_publication_rel) GETSTRUCT(tup); - /* - * For any publication, pg_publication_rel contains either only EXCEPT - * entries or only explicitly included tables. Therefore, examining - * the first tuple is sufficient to determine table inclusion. - */ - result = !pubrel->prexcept; + /* + * A publication can hold both explicit-include (prexcept=false) + * and EXCEPT (prexcept=true) rows for the same pubid. Scan until + * we find an explicit-include row, rather than relying on the first row's + * prexcept value. + */ + while (HeapTupleIsValid(tup = systable_getnext(scan))) + { + if (!((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept) + { + result = true; + break; + } } systable_endscan(scan); @@ -454,14 +498,27 @@ GetPubPartitionOptionRelations(List *result, PublicationPartOpt pub_partopt, * * Note that the list of ancestors should be ordered such that the topmost * ancestor is at the end of the list. + * + * except_pubids is a list of publication OIDs whose schema membership + * should be ignored for the ancestor (because the ancestor is in their + * EXCEPT clause). */ Oid -GetTopMostAncestorInPublication(Oid puboid, List *ancestors, int *ancestor_level) +GetTopMostAncestorInPublication(Oid puboid, List *ancestors, + int *ancestor_level, List *except_pubids) { ListCell *lc; Oid topmost_relid = InvalidOid; int level = 0; + /* + * except_pubids is computed once from the partition root and reused + * across the ancestor walk. Re-fetching exclusion information for each + * ancestor is unnecessary because only the root can have prexcept=true; + * partitions themselves cannot be added to EXCEPT. + */ + bool check_schemas = !list_member_oid(except_pubids, puboid); + /* * Find the "topmost" ancestor that is in this publication. */ @@ -480,7 +537,7 @@ GetTopMostAncestorInPublication(Oid puboid, List *ancestors, int *ancestor_level if (ancestor_level) *ancestor_level = level; } - else + else if (check_schemas) { aschemaPubids = GetSchemaPublications(get_rel_namespace(ancestor)); if (list_member_oid(aschemaPubids, puboid)) @@ -555,21 +612,36 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, * duplicates, it's here just to provide nicer error message in common * case. The real protection is the unique key on the catalog. */ - if (SearchSysCacheExists2(PUBLICATIONRELMAP, ObjectIdGetDatum(relid), - ObjectIdGetDatum(pubid))) + tup = SearchSysCache2(PUBLICATIONRELMAP, ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + + if (HeapTupleIsValid(tup)) { + bool is_except = ((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept; + + ReleaseSysCache(tup); table_close(rel, RowExclusiveLock); if (if_not_exists) return InvalidObjectAddress; - ereport(ERROR, - (errcode(ERRCODE_DUPLICATE_OBJECT), - errmsg("relation \"%s\" is already member of publication \"%s\"", - RelationGetRelationName(targetrel), pub->name))); + if (is_except) + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("cannot add table \"%s\" to publication \"%s\"", + RelationGetQualifiedRelationName(targetrel), + pub->name), + errdetail("Table \"%s\" is currently listed in the EXCEPT clause of the publication.", + RelationGetQualifiedRelationName(targetrel)), + errhint("Change EXCEPT list using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT."))); + else + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("relation \"%s\" is already member of publication \"%s\"", + RelationGetRelationName(targetrel), pub->name))); } - check_publication_add_relation(pri); + check_publication_add_relation(pri, pubid); /* Validate and translate column names into a Bitmapset of attnums. */ attnums = pub_collist_validate(pri->relation, pri->columns); @@ -992,12 +1064,13 @@ GetIncludedPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) * Gets list of table oids that were specified in the EXCEPT clause for a * publication. * - * This should only be used FOR ALL TABLES publications. + * This is used for FOR ALL TABLES and FOR TABLES IN SCHEMA publications, + * both of which support EXCEPT TABLE. */ List * GetExcludedPublicationTables(Oid pubid, PublicationPartOpt pub_partopt) { - Assert(GetPublication(pubid)->alltables); + Assert(GetPublication(pubid)->alltables || is_schema_publication(pubid)); return get_publication_relations(pubid, pub_partopt, true); } @@ -1059,15 +1132,15 @@ GetAllPublicationRelations(Oid pubid, char relkind, bool pubviaroot) TableScanDesc scan; HeapTuple tuple; List *result = NIL; - List *exceptlist = NIL; + List *except_relids = NIL; Assert(!(relkind == RELKIND_SEQUENCE && pubviaroot)); /* EXCEPT filtering applies only to relations, not sequences */ if (relkind == RELKIND_RELATION) - exceptlist = GetExcludedPublicationTables(pubid, pubviaroot ? - PUBLICATION_PART_ROOT : - PUBLICATION_PART_LEAF); + except_relids = GetExcludedPublicationTables(pubid, pubviaroot ? + PUBLICATION_PART_ROOT : + PUBLICATION_PART_LEAF); classRel = table_open(RelationRelationId, AccessShareLock); @@ -1085,7 +1158,7 @@ GetAllPublicationRelations(Oid pubid, char relkind, bool pubviaroot) if (is_publishable_class(relid, relForm) && !(relForm->relispartition && pubviaroot) && - !list_member_oid(exceptlist, relid)) + !list_member_oid(except_relids, relid)) result = lappend_oid(result, relid); } @@ -1107,7 +1180,7 @@ GetAllPublicationRelations(Oid pubid, char relkind, bool pubviaroot) if (is_publishable_class(relid, relForm) && !relForm->relispartition && - !list_member_oid(exceptlist, relid)) + !list_member_oid(except_relids, relid)) result = lappend_oid(result, relid); } @@ -1242,22 +1315,68 @@ GetSchemaPublicationRelations(Oid schemaid, PublicationPartOpt pub_partopt) /* * Gets the list of all relations published by FOR TABLES IN SCHEMA - * publication. + * publication, excluding any tables listed in the EXCEPT clause. */ List * GetAllSchemaPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) { List *result = NIL; List *pubschemalist = GetPublicationSchemas(pubid); + List *except_relids = NIL; ListCell *cell; + /* get the list of tables excluded via EXCEPT TABLE for this publication */ + if (pubschemalist != NIL) + except_relids = GetExcludedPublicationTables(pubid, pub_partopt); + foreach(cell, pubschemalist) { Oid schemaid = lfirst_oid(cell); List *schemaRels = NIL; schemaRels = GetSchemaPublicationRelations(schemaid, pub_partopt); - result = list_concat(result, schemaRels); + + if (except_relids != NIL) + { + /* filter out any tables that appear in the EXCEPT list */ + ListCell *rlc; + + foreach(rlc, schemaRels) + { + Oid relid = lfirst_oid(rlc); + bool excluded = list_member_oid(except_relids, relid); + + /* + * A partition whose ancestor is in the publication's EXCEPT + * list is also excluded, even if the partition itself lives + * in a different (included) schema. Individual partitions + * cannot appear in EXCEPT, so cascading from the root is the + * only way to exclude a partition; this matches the ALL + * TABLES EXCEPT (TABLE root) behavior. + */ + if (!excluded && get_rel_relispartition(relid)) + { + List *ancestors = get_partition_ancestors(relid); + ListCell *alc; + + foreach(alc, ancestors) + { + if (list_member_oid(except_relids, lfirst_oid(alc))) + { + excluded = true; + break; + } + } + list_free(ancestors); + } + + if (!excluded) + result = lappend_oid(result, relid); + } + list_free(schemaRels); + } + else + result = list_concat(result, schemaRels); } return result; @@ -1334,6 +1453,7 @@ is_table_publishable_in_publication(Oid relid, Publication *pub) { bool relispartition; List *ancestors = NIL; + HeapTuple tup; /* * For non-pubviaroot publications, a partitioned table is never the @@ -1390,20 +1510,62 @@ is_table_publishable_in_publication(Oid relid, Publication *pub) * If it's false, the partition is covered by its ancestor's presence in * the publication, it should be included (return true). */ - if (relispartition && - OidIsValid(GetTopMostAncestorInPublication(pub->oid, ancestors, NULL))) - return !pub->pubviaroot; + if (relispartition) + { + Oid ancestor_oid; + + ancestor_oid = GetTopMostAncestorInPublication(pub->oid, ancestors, NULL, NIL); + if (OidIsValid(ancestor_oid)) + { + /* + * The ancestor was found in the publication (via explicit + * membership or schema membership), but it may be excluded. Check + * for a prexcept row before concluding the partition is + * published. + */ + tup = SearchSysCache2(PUBLICATIONRELMAP, + ObjectIdGetDatum(ancestor_oid), + ObjectIdGetDatum(pub->oid)); + if (HeapTupleIsValid(tup)) + { + bool is_except; + + is_except = ((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept; + ReleaseSysCache(tup); + if (is_except) + return false; + } + return !pub->pubviaroot; + } + } /* * Check whether the table is explicitly published via pg_publication_rel * or pg_publication_namespace. + * + * A pg_publication_rel row with prexcept=true means the table is + * explicitly excluded via EXCEPT and must not be reported as published, + * even if its schema is otherwise included. A row with prexcept=false + * means it is explicitly included. If no pg_publication_rel row exists, + * the table is published iff its schema appears in + * pg_publication_namespace. */ - return (SearchSysCacheExists2(PUBLICATIONRELMAP, - ObjectIdGetDatum(relid), - ObjectIdGetDatum(pub->oid)) || - SearchSysCacheExists2(PUBLICATIONNAMESPACEMAP, - ObjectIdGetDatum(get_rel_namespace(relid)), - ObjectIdGetDatum(pub->oid))); + + tup = SearchSysCache2(PUBLICATIONRELMAP, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pub->oid)); + if (HeapTupleIsValid(tup)) + { + bool is_except; + + is_except = ((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept; + ReleaseSysCache(tup); + return !is_except; + } + + return SearchSysCacheExists2(PUBLICATIONNAMESPACEMAP, + ObjectIdGetDatum(get_rel_namespace(relid)), + ObjectIdGetDatum(pub->oid)); } /* diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 440adb356ad..45a8a5c3f71 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -71,6 +71,7 @@ static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); static char defGetGeneratedColsOption(DefElem *def); +static void CheckExceptNotInTableList(List *except_rels, List *explicitrelids); static void @@ -181,7 +182,7 @@ parse_publication_options(ParseState *pstate, */ static void ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, - List **rels, List **exceptrels, List **schemas) + List **rels, List **except_pubtables, List **schemas) { ListCell *cell; PublicationObjSpec *pubobj; @@ -200,7 +201,7 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, { case PUBLICATIONOBJ_EXCEPT_TABLE: pubobj->pubtable->except = true; - *exceptrels = lappend(*exceptrels, pubobj->pubtable); + *except_pubtables = lappend(*except_pubtables, pubobj->pubtable); break; case PUBLICATIONOBJ_TABLE: pubobj->pubtable->except = false; @@ -224,6 +225,38 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, /* Filter out duplicates if user specifies "sch1, sch1" */ *schemas = list_append_unique_oid(*schemas, schemaid); + + /* + * Qualify unqualified EXCEPT table names with the resolved + * current schema and reject any explicitly cross-schema + * entries. This mirrors the parse-time handling done for + * TABLES_IN_SCHEMA in preprocess_pubobj_list(), deferred here + * because CURRENT_SCHEMA is not known until execution time. + */ + if (pubobj->except_tables != NIL) + { + char *cur_schema_name = get_namespace_name(schemaid); + + foreach_ptr(PublicationObjSpec, eobj, pubobj->except_tables) + { + const char *eobj_schemaname = + eobj->pubtable->relation->schemaname; + const char *eobj_relname = + eobj->pubtable->relation->relname; + + if (eobj_schemaname == NULL) + eobj->pubtable->relation->schemaname = cur_schema_name; + else if (strcmp(eobj_schemaname, cur_schema_name) != 0) + ereport(ERROR, + errcode(ERRCODE_INVALID_OBJECT_DEFINITION), + errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", + quote_qualified_identifier(eobj_schemaname, eobj_relname), + cur_schema_name)); + + *except_pubtables = lappend(*except_pubtables, + eobj->pubtable); + } + } break; default: /* shouldn't happen */ @@ -305,7 +338,7 @@ pub_rf_contains_invalid_column(Oid pubid, Relation relation, List *ancestors, if (pubviaroot && relation->rd_rel->relispartition) { publish_as_relid - = GetTopMostAncestorInPublication(pubid, ancestors, NULL); + = GetTopMostAncestorInPublication(pubid, ancestors, NULL, NIL); if (!OidIsValid(publish_as_relid)) publish_as_relid = relid; @@ -389,7 +422,7 @@ pub_contains_invalid_column(Oid pubid, Relation relation, List *ancestors, */ if (pubviaroot && relation->rd_rel->relispartition) { - publish_as_relid = GetTopMostAncestorInPublication(pubid, ancestors, NULL); + publish_as_relid = GetTopMostAncestorInPublication(pubid, ancestors, NULL, NIL); if (!OidIsValid(publish_as_relid)) publish_as_relid = relid; @@ -770,6 +803,23 @@ TransformPubWhereClauses(List *tables, const char *queryString, } } +/* + * Check that no relation in except_rels is also present in explicitrelids, + * the list of OIDs added to the publication by the explicit TABLE list. A + * table cannot be both explicitly published and excluded in the same DDL. + */ +static void +CheckExceptNotInTableList(List *except_rels, List *explicitrelids) +{ + foreach_ptr(PublicationRelInfo, pri, except_rels) + { + if (list_member_oid(explicitrelids, RelationGetRelid(pri->relation))) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" cannot appear in both the table list and the EXCEPT clause", + RelationGetQualifiedRelationName(pri->relation))); + } +} /* * Given a list of tables that are going to be added to a publication, @@ -849,7 +899,7 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) char publish_generated_columns; AclResult aclresult; List *relations = NIL; - List *exceptrelations = NIL; + List *except_pubtables = NIL; List *schemaidlist = NIL; /* must have CREATE privilege on database */ @@ -936,16 +986,16 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) /* Associate objects with the publication. */ ObjectsInPublicationToOids(stmt->pubobjects, pstate, &relations, - &exceptrelations, &schemaidlist); + &except_pubtables, &schemaidlist); if (stmt->for_all_tables) { /* Process EXCEPT table list */ - if (exceptrelations != NIL) + if (except_pubtables != NIL) { List *rels; - rels = OpenTableList(exceptrelations); + rels = OpenTableList(except_pubtables); PublicationAddTables(puboid, rels, true, NULL); CloseTableList(rels); } @@ -959,6 +1009,8 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) } else if (!stmt->for_all_sequences) { + List *explicitrelids = NIL; + /* FOR TABLES IN SCHEMA requires superuser */ if (schemaidlist != NIL && !superuser()) ereport(ERROR, @@ -977,6 +1029,19 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) schemaidlist != NIL, publish_via_partition_root); + /* + * Collect explicit table OIDs now, before we close the relation + * list, so that except-table validation below can check for + * contradictions without relying on a catalog scan that might not + * yet see the just-inserted rows. + */ + if (except_pubtables != NIL) + { + foreach_ptr(PublicationRelInfo, pri, rels) + explicitrelids = lappend_oid(explicitrelids, + RelationGetRelid(pri->relation)); + } + PublicationAddTables(puboid, rels, true, NULL); CloseTableList(rels); } @@ -989,6 +1054,25 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) */ LockSchemaList(schemaidlist); PublicationAddSchemas(puboid, schemaidlist, true, NULL); + + if (except_pubtables != NIL) + { + List *except_rels; + + except_rels = OpenTableList(except_pubtables); + + /* + * Validate that each excluded table is not also in the + * explicit table list (which would be contradictory). Use the + * in-memory explicitrelids collected above rather than + * re-reading the catalog, which may not yet see the + * just-inserted rows. + */ + CheckExceptNotInTableList(except_rels, explicitrelids); + + PublicationAddTables(puboid, except_rels, true, NULL); + CloseTableList(except_rels); + } } } @@ -1683,12 +1767,12 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) else { List *relations = NIL; - List *exceptrelations = NIL; + List *except_pubtables = NIL; List *schemaidlist = NIL; Oid pubid = pubform->oid; ObjectsInPublicationToOids(stmt->pubobjects, pstate, &relations, - &exceptrelations, &schemaidlist); + &except_pubtables, &schemaidlist); CheckAlterPublication(stmt, tup, relations, schemaidlist); @@ -1711,7 +1795,7 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) errmsg("publication \"%s\" does not exist", stmt->pubname)); - relations = list_concat(relations, exceptrelations); + relations = list_concat(relations, except_pubtables); AlterPublicationTables(stmt, tup, relations, pstate->p_sourcetext, schemaidlist != NIL); AlterPublicationSchemas(stmt, tup, schemaidlist); @@ -1829,6 +1913,62 @@ RemovePublicationSchemaById(Oid psoid) table_close(rel, RowExclusiveLock); } +/* + * Remove any EXCEPT clause entries for a relation from schema publications. + * Called when a table changes schema (ALTER TABLE ... SET SCHEMA), so that + * a schema-scoped exclusion does not silently follow the table to its new + * schema. + */ +void +RemoveSchemaPubExceptForRel(Oid relid, Oid oldNspOid, Oid newNspOid) +{ + List *pubids; + + /* + * If the table is not actually moving to a different schema (no-op + * ALTER TABLE ... SET SCHEMA <current_schema>), there is nothing to do. + */ + if (oldNspOid == newNspOid) + return; + + pubids = GetRelationExcludedPublications(relid); + + foreach_oid(pubid, pubids) + { + Oid proid; + + /* + * This problem does not apply to FOR ALL TABLES publications, because + * their EXCEPT clause is publication-scoped, not schema-scoped: the + * exclusion should persist regardless of what schema the table is in. + */ + if (!is_schema_publication(pubid)) + continue; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddress obj; + + ObjectAddressSet(obj, PublicationRelRelationId, proid); + + ereport(DEBUG2, + errmsg_internal("auto-remove exclusion of table \"%s.%s\" from publication \"%s\": table moved to schema \"%s\"", + get_namespace_name(oldNspOid), + get_rel_name(relid), + get_publication_name(pubid, false), + get_namespace_name(newNspOid))); + + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + list_free(pubids); +} + /* * Open relations specified by a PublicationTable list. * The returned tables are locked in ShareUpdateExclusiveLock mode in order to diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 95abaf4890c..a6afb262967 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -63,6 +63,7 @@ #include "commands/event_trigger.h" #include "commands/extension.h" #include "commands/repack.h" +#include "commands/publicationcmds.h" #include "commands/sequence.h" #include "commands/tablecmds.h" #include "commands/tablespace.h" @@ -19569,6 +19570,16 @@ AlterTableNamespaceInternal(Relation rel, Oid oldNspOid, Oid nspOid, AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid, false, objsMoved); + /* + * Remove any EXCEPT clause entries for this relation from schema + * publications. A schema-scoped exclusion is no longer meaningful once + * the table moves to a different schema. + */ + if (rel->rd_rel->relkind == RELKIND_RELATION || + rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE) + RemoveSchemaPubExceptForRel(RelationGetRelid(rel), oldNspOid, + nspOid); + table_close(classRel, RowExclusiveLock); } diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y index ff4e1388c55..6a7a1bc5f8d 100644 --- a/src/backend/parser/gram.y +++ b/src/backend/parser/gram.y @@ -58,6 +58,7 @@ #include "nodes/makefuncs.h" #include "nodes/nodeFuncs.h" #include "parser/parser.h" +#include "utils/builtins.h" #include "utils/datetime.h" #include "utils/xml.h" @@ -11272,7 +11273,7 @@ AlterOwnerStmt: ALTER AGGREGATE aggregate_with_argtypes OWNER TO RoleSpec * pub_obj is one of: * * TABLE table [, ...] - * TABLES IN SCHEMA schema [, ...] + * TABLES IN SCHEMA schema [EXCEPT (TABLE table [, ...] )] [, ...] * *****************************************************************************/ @@ -11332,23 +11333,26 @@ PublicationObjSpec: $$->pubtable->columns = $3; $$->pubtable->whereClause = $4; } - | TABLES IN_P SCHEMA ColId + | TABLES IN_P SCHEMA ColId opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_SCHEMA; $$->name = $4; + $$->except_tables = $5; $$->location = @4; } - | TABLES IN_P SCHEMA CURRENT_SCHEMA + | TABLES IN_P SCHEMA CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_CUR_SCHEMA; + $$->except_tables = $5; $$->location = @4; } - | ColId opt_column_list OptWhereClause + | ColId opt_column_list OptWhereClause opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $4; /* * If either a row filter or column list is specified, create * a PublicationTable object. @@ -11392,10 +11396,11 @@ PublicationObjSpec: $$->pubtable->columns = $2; $$->pubtable->whereClause = $3; } - | CURRENT_SCHEMA + | CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $2; $$->location = @1; } ; @@ -20784,6 +20789,8 @@ preprocess_pub_all_objtype_list(List *all_objects_list, List **pubobjects, /* * Process pubobjspec_list to check for errors in any of the objects and * convert PUBLICATIONOBJ_CONTINUATION into appropriate PublicationObjSpecType. + * Also flattens except_tables from TABLES IN SCHEMA nodes into the list so + * that ObjectsInPublicationToOids() sees them as top-level EXCEPT_TABLE entries. */ static void preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) @@ -20812,6 +20819,13 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLE) { + /* EXCEPT is not valid for table objects */ + if (pubobj->except_tables != NIL) + ereport(ERROR, + errcode(ERRCODE_SYNTAX_ERROR), + errmsg("EXCEPT is not allowed for TABLE publication objects"), + parser_errposition(pubobj->location)); + /* relation name or pubtable must be set for this type of object */ if (!pubobj->name && !pubobj->pubtable) ereport(ERROR, @@ -20860,6 +20874,36 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) errcode(ERRCODE_SYNTAX_ERROR), errmsg("invalid schema name"), parser_errposition(pubobj->location)); + + /* + * For TABLES_IN_SCHEMA, qualify unqualified EXCEPT table names + * with the parent schema and reject cross-schema entries at parse + * time, then flatten into the top-level list. + * + * For TABLES_IN_CUR_SCHEMA the schema name is not yet known, so + * skip both steps here; ObjectsInPublicationToOids() will + * qualify names and validate schema membership at execution time. + */ + if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLES_IN_SCHEMA) + { + foreach_ptr(PublicationObjSpec, eobj, pubobj->except_tables) + { + const char *eobj_schemaname = eobj->pubtable->relation->schemaname; + const char *eobj_relname = eobj->pubtable->relation->relname; + + if (eobj_schemaname == NULL) + eobj->pubtable->relation->schemaname = pubobj->name; + else if (strcmp(eobj_schemaname, pubobj->name) != 0) + ereport(ERROR, + errcode(ERRCODE_INVALID_OBJECT_DEFINITION), + errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", + quote_qualified_identifier(eobj_schemaname, eobj_relname), + pubobj->name), + parser_errposition(eobj->location)); + } + pubobjspec_list = list_concat(pubobjspec_list, pubobj->except_tables); + pubobj->except_tables = NIL; + } } prevobjtype = pubobj->pubobjtype; diff --git a/src/backend/replication/pgoutput/pgoutput.c b/src/backend/replication/pgoutput/pgoutput.c index 4ecfcbff7ab..b0983775a03 100644 --- a/src/backend/replication/pgoutput/pgoutput.c +++ b/src/backend/replication/pgoutput/pgoutput.c @@ -2097,6 +2097,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) * are absorbed while decoding WAL. */ List *schemaPubids = GetSchemaPublications(schemaId); + List *except_pubids; ListCell *lc; Oid publish_as_relid = relid; int publish_ancestor_level = 0; @@ -2104,6 +2105,28 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) char relkind = get_rel_relkind(relid); List *rel_publications = NIL; + /* + * For the schema EXCEPT check, we must look up the top-most ancestor + * rather than the relation itself. check_publication_add_relation() + * prevents individual partitions from appearing in the EXCEPT clause, + * so only a root (non-partition) table can have prexcept = true. + * Using the partition's own OID would always return NIL and miss the + * exclusion. + */ + Oid root_relid; + + if (am_partition) + { + List *ancestors = get_partition_ancestors(relid); + + root_relid = llast_oid(ancestors); + list_free(ancestors); + } + else + root_relid = relid; + + except_pubids = GetRelationExcludedPublications(root_relid); + /* Reload publications if needed before use. */ if (!publications_valid) { @@ -2265,9 +2288,19 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) int level; List *ancestors = get_partition_ancestors(relid); + /* + * Reach here for FOR TABLE, FOR TABLES IN SCHEMA, or + * mixed publications. except_pubids lets + * GetTopMostAncestorInPublication() skip schema-based + * ancestor matches when the partition root is excluded + * via this publication's EXCEPT clause. It has no effect + * for pure FOR TABLE publications, which cannot have + * prexcept rows. + */ ancestor = GetTopMostAncestorInPublication(pub->oid, ancestors, - &level); + &level, + except_pubids); if (ancestor != InvalidOid) { @@ -2281,7 +2314,8 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) } if (list_member_oid(pubids, pub->oid) || - list_member_oid(schemaPubids, pub->oid) || + (list_member_oid(schemaPubids, pub->oid) && + !list_member_oid(except_pubids, pub->oid)) || ancestor_published) publish = true; } @@ -2360,6 +2394,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) list_free(pubids); list_free(schemaPubids); + list_free(except_pubids); list_free(rel_publications); entry->replicate_valid = true; diff --git a/src/backend/utils/cache/relcache.c b/src/backend/utils/cache/relcache.c index fb4e042be8a..92ff89fa2a4 100644 --- a/src/backend/utils/cache/relcache.c +++ b/src/backend/utils/cache/relcache.c @@ -5845,16 +5845,29 @@ RelationBuildPublicationDesc(Relation relation, PublicationDesc *pubdesc) /* Fetch the publication membership info. */ puboids = GetRelationIncludedPublications(relid); schemaid = RelationGetNamespace(relation); - puboids = list_concat_unique_oid(puboids, GetSchemaPublications(schemaid)); if (relation->rd_rel->relispartition) { - Oid last_ancestor_relid; - - /* Add publications that the ancestors are in too. */ ancestors = get_partition_ancestors(relid); - last_ancestor_relid = llast_oid(ancestors); + exceptpuboids = GetRelationExcludedPublications(llast_oid(ancestors)); + } + else + exceptpuboids = GetRelationExcludedPublications(relid); + /* + * Subtract exceptpuboids from the schema-publication contribution so that + * a relation EXCEPT'd from a schema publication does not inherit that + * publication's pubactions. Without this filter, + * CheckCmdReplicaIdentity() would demand REPLICA IDENTITY for + * UPDATE/DELETE even on a explicitly excluded table. + */ + puboids = list_concat_unique_oid(puboids, + list_difference_oid(GetSchemaPublications(schemaid), + exceptpuboids)); + + if (relation->rd_rel->relispartition) + { + /* Add publications that the ancestors are in too. */ foreach(lc, ancestors) { Oid ancestor = lfirst_oid(lc); @@ -5863,23 +5876,9 @@ RelationBuildPublicationDesc(Relation relation, PublicationDesc *pubdesc) GetRelationIncludedPublications(ancestor)); schemaid = get_rel_namespace(ancestor); puboids = list_concat_unique_oid(puboids, - GetSchemaPublications(schemaid)); + list_difference_oid(GetSchemaPublications(schemaid), + exceptpuboids)); } - - /* - * Only the top-most ancestor can appear in the EXCEPT clause. - * Therefore, for a partition, exclusion must be evaluated at the - * top-most ancestor. - */ - exceptpuboids = GetRelationExcludedPublications(last_ancestor_relid); - } - else - { - /* - * For a regular table or a root partitioned table, check exclusion on - * table itself. - */ - exceptpuboids = GetRelationExcludedPublications(relid); } alltablespuboids = GetAllTablesPublications(); diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c index fef86b4cca3..72e8f58fc3e 100644 --- a/src/bin/psql/describe.c +++ b/src/bin/psql/describe.c @@ -6815,6 +6815,24 @@ describePublications(const char *pattern) if (!addFooterToPublicationDesc(&buf, _("Tables from schemas:"), true, &cont)) goto error_return; + + if (pset.sversion >= 190000) + { + /* + * Get tables in the EXCEPT clause for this schema + * publication. + */ + printfPQExpBuffer(&buf, + "SELECT concat(c.relnamespace::regnamespace, '.', c.relname)\n" + "FROM pg_catalog.pg_class c\n" + " JOIN pg_catalog.pg_publication_rel pr ON c.oid = pr.prrelid\n" + "WHERE pr.prpubid = '%s'\n" + " AND pr.prexcept\n" + "ORDER BY 1", pubid); + if (!addFooterToPublicationDesc(&buf, _("Except tables:"), + true, &cont)) + goto error_return; + } } } else diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index e4bc2c93145..5fd4f86ce70 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -1065,6 +1065,24 @@ static const SchemaQuery Query_for_trigger_of_table = { "SELECT nspname FROM pg_catalog.pg_namespace "\ " WHERE nspname LIKE '%s'" +#define Query_for_list_of_tables_in_schema \ +"SELECT n.nspname || '.' || c.relname "\ +" FROM pg_catalog.pg_class c "\ +" JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "\ +" WHERE c.relkind IN (" CppAsString2(RELKIND_RELATION) ", " \ + CppAsString2(RELKIND_PARTITIONED_TABLE) ") "\ +" AND (n.nspname || '.' || c.relname) LIKE '%s' "\ +" AND n.nspname = '%s'" + +#define Query_for_list_of_tables_in_current_schema \ +"SELECT c.relname "\ +" FROM pg_catalog.pg_class c "\ +" JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "\ +" WHERE c.relkind IN (" CppAsString2(RELKIND_RELATION) ", " \ + CppAsString2(RELKIND_PARTITIONED_TABLE) ") "\ +" AND c.relname LIKE '%s' "\ +" AND n.nspname = pg_catalog.current_schema()" + /* Use COMPLETE_WITH_QUERY_VERBATIM with these queries for GUC names: */ #define Query_for_list_of_alter_system_set_vars \ "SELECT pg_catalog.lower(name) FROM pg_catalog.pg_settings "\ @@ -3774,8 +3792,21 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); - else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && (!ends_with(prev_wd, ','))) - COMPLETE_WITH("WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE", "WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* Complete "CREATE PUBLICATION <name> [...] WITH" */ else if (Matches("CREATE", "PUBLICATION", MatchAnyN, "WITH", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/include/catalog/pg_publication.h b/src/include/catalog/pg_publication.h index 89b4bb14f62..53e3d7c6f3d 100644 --- a/src/include/catalog/pg_publication.h +++ b/src/include/catalog/pg_publication.h @@ -191,7 +191,8 @@ extern List *GetPubPartitionOptionRelations(List *result, PublicationPartOpt pub_partopt, Oid relid); extern Oid GetTopMostAncestorInPublication(Oid puboid, List *ancestors, - int *ancestor_level); + int *ancestor_level, + List *except_pubids); extern bool is_publishable_relation(Relation rel); extern bool is_schema_publication(Oid pubid); diff --git a/src/include/commands/publicationcmds.h b/src/include/commands/publicationcmds.h index 4cf45c17cc5..fb1703aa675 100644 --- a/src/include/commands/publicationcmds.h +++ b/src/include/commands/publicationcmds.h @@ -27,6 +27,8 @@ extern void AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt); extern void RemovePublicationById(Oid pubid); extern void RemovePublicationRelById(Oid proid); extern void RemovePublicationSchemaById(Oid psoid); +extern void RemoveSchemaPubExceptForRel(Oid relid, Oid oldNspOid, + Oid newNspOid); extern ObjectAddress AlterPublicationOwner(const char *name, Oid newOwnerId); extern void AlterPublicationOwner_oid(Oid pubid, Oid newOwnerId); diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h index e03556399ab..1f3697ccd23 100644 --- a/src/include/nodes/parsenodes.h +++ b/src/include/nodes/parsenodes.h @@ -4489,6 +4489,8 @@ typedef struct PublicationObjSpec PublicationObjSpecType pubobjtype; /* type of this publication object */ char *name; PublicationTable *pubtable; + List *except_tables; /* tables specified in the EXCEPT clause (for + * TABLES IN SCHEMA) */ ParseLoc location; /* token location, or -1 if unknown */ } PublicationObjSpec; diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 29e54b214a0..b4104e8220a 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -270,6 +270,12 @@ CREATE PUBLICATION testpub_foralltables_excepttable2 FOR ALL TABLES EXCEPT (test ERROR: syntax error at or near "testpub_tbl1" LINE 1: ..._foralltables_excepttable2 FOR ALL TABLES EXCEPT (testpub_tb... ^ +-- fail - EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testpub_tbl3); +ERROR: EXCEPT is not allowed for TABLE publication objects +LINE 2: FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testp... + ^ --------------------------------------------- -- SET ALL TABLES/SEQUENCES --------------------------------------------- @@ -470,7 +476,139 @@ HINT: Change the publication's EXCEPT clause using ALTER PUBLICATION ... SET AL RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Create same-named tables in public to verify unqualified EXCEPT entries +-- are qualified with the named schema, not public +CREATE TABLE testpub_nopk (foo int, bar int); +CREATE TABLE testpub_tbl_s1 (a int primary key, b text); +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + Publication testpub_schema_except1 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- Exclude multiple tables using unqualified names; same-named tables exist in +-- public to confirm unqualified names resolve to pub_test, not public +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + Publication testpub_schema_except2 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_nopk" + "pub_test.testpub_tbl_s1" + +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testp... + ^ +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); +ERROR: table "pub_test.testpub_tbl_s1" in EXCEPT clause does not belong to schema "public" +LINE 2: ...R TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.t... + ^ +-- Multiple schemas each with their own EXCEPT clause +CREATE PUBLICATION testpub_schema_except_multi + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_schema_except_multi + Publication testpub_schema_except_multi + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- ALTER TABLE ... SET SCHEMA on a table excluded by a schema publication: +-- the schema-scoped exclusion is no longer meaningful once the table moves +-- out of its schema, so the exclusion is auto-removed. +CREATE PUBLICATION testpub_schema_except_setsch + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_schema_except_setsch + Publication testpub_schema_except_setsch + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s2" + +ALTER TABLE pub_test.testpub_tbl_s2 SET SCHEMA public; +\dRp+ testpub_schema_except_setsch + Publication testpub_schema_except_setsch + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + +DROP PUBLICATION testpub_schema_except_setsch; +-- Restore for further tests +ALTER TABLE public.testpub_tbl_s2 SET SCHEMA pub_test; +-- fail: table appears in both the explicit table list and the EXCEPT clause +CREATE PUBLICATION testpub_except_conflict + FOR TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot appear in both the table list and the EXCEPT clause +-- fail: nonexistent table in EXCEPT clause +CREATE PUBLICATION testpub_except_norel + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- fail: partition cannot appear in EXCEPT clause; only root tables are allowed +CREATE TABLE pub_test.testpub_parted_s (a int) PARTITION BY LIST (a); +CREATE TABLE pub_test.testpub_part_s PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (1); +CREATE PUBLICATION testpub_except_partition + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); +ERROR: cannot specify relation "pub_test.testpub_part_s" in the publication EXCEPT clause +DETAIL: This operation is not supported for individual partitions. +-- fail: TABLE keyword is required for the first entry in the EXCEPT clause +CREATE PUBLICATION testpub_except_nokw + FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +ERROR: syntax error at or near "testpub_nopk" +LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + ^ +-- error: ADD TABLE for a partition is rejected when a partition ancestor +-- is currently in the publication's EXCEPT list. +CREATE PUBLICATION testpub_except_ancestor + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ALTER PUBLICATION testpub_except_ancestor ADD TABLE pub_test.testpub_part_s; +ERROR: cannot add table "pub_test.testpub_part_s" to publication "testpub_except_ancestor" +DETAIL: Partition ancestor "pub_test.testpub_parted_s" of table "pub_test.testpub_part_s" is currently listed in the EXCEPT clause of the publication. +HINT: Change EXCEPT list using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT. +DROP PUBLICATION testpub_except_ancestor; +-- Cleanup +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP TABLE pub_test.testpub_parted_s CASCADE; +DROP TABLE testpub_nopk, testpub_tbl_s1; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +--------------------------------------------- +-- Tests for publications with SEQUENCES +--------------------------------------------- CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; -- FOR ALL SEQUENCES @@ -1953,6 +2091,27 @@ ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b); ERROR: column specification not allowed for schema LINE 1: ...TION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b)... ^ +-- EXCEPT clause with CURRENT_SCHEMA: cross-schema entry must be rejected +SET search_path = pub_test1; +-- qualified name from wrong schema -> error +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.tbl1); +ERROR: table "pub_test2.tbl1" in EXCEPT clause does not belong to schema "pub_test1" +-- unqualified name implicitly qualified with current schema (pub_test1.tbl) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl); +RESET client_min_messages; +\dRp+ testpub_cursch_except + Publication testpub_cursch_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test1" +Except tables: + "pub_test1.tbl" + +DROP PUBLICATION testpub_cursch_except; +RESET search_path; -- cleanup pub_test1 schema for invalidation tests ALTER PUBLICATION testpub2_forschema DROP TABLES IN SCHEMA pub_test1; DROP PUBLICATION testpub3_forschema, testpub4_forschema, testpub5_forschema, testpub6_forschema, testpub_fortable; @@ -2304,6 +2463,7 @@ DROP ROLE regress_publication_user_dummy; -- Test pg_get_publication_tables(text[], oid) function CREATE SCHEMA gpt_test_sch; CREATE TABLE gpt_test_sch.tbl_sch (id int); +CREATE TABLE gpt_test_sch.tbl_sch2 (id int); CREATE TABLE tbl_normal (id int); CREATE TABLE tbl_parent (id1 int, id2 int, id3 int) PARTITION BY RANGE (id1); CREATE TABLE tbl_part1 PARTITION OF tbl_parent FOR VALUES FROM (1) TO (10); @@ -2314,6 +2474,7 @@ CREATE PUBLICATION pub_all_no_viaroot FOR ALL TABLES WITH (publish_via_partition CREATE PUBLICATION pub_all_except FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = true); CREATE PUBLICATION pub_all_except_no_viaroot FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_schema FOR TABLES IN SCHEMA gpt_test_sch; +CREATE PUBLICATION pub_schema_except FOR TABLES IN SCHEMA gpt_test_sch EXCEPT (TABLE gpt_test_sch.tbl_sch); CREATE PUBLICATION pub_normal FOR TABLE tbl_normal WHERE (id < 10); CREATE PUBLICATION pub_part_leaf FOR TABLE tbl_part1 WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_part_parent FOR TABLE tbl_parent (id1, id2) WHERE (id1 = 10) WITH (publish_via_partition_root = true); @@ -2465,6 +2626,18 @@ SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_part1'); -- no r ---------+---------+-------+------ (0 rows) +-- test for EXCEPT clause with schema publication +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch'); -- no result (excluded) + pubname | relname | attrs | qual +---------+---------+-------+------ +(0 rows) + +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch2'); -- one row (included via schema) + pubname | relname | attrs | qual +-------------------+----------+-------+------ + pub_schema_except | tbl_sch2 | 1 | +(1 row) + -- two rows with different row filter SELECT * FROM test_gpt(ARRAY['pub_all', 'pub_normal'], 'tbl_normal'); pubname | relname | attrs | qual @@ -2517,6 +2690,7 @@ DROP PUBLICATION pub_all_no_viaroot; DROP PUBLICATION pub_all_except; DROP PUBLICATION pub_all_except_no_viaroot; DROP PUBLICATION pub_schema; +DROP PUBLICATION pub_schema_except; DROP PUBLICATION pub_normal; DROP PUBLICATION pub_part_leaf; DROP PUBLICATION pub_part_parent; @@ -2525,7 +2699,9 @@ DROP PUBLICATION pub_part_parent_child; DROP VIEW gpt_test_view; DROP TABLE tbl_normal, tbl_parent, tbl_part1; DROP SCHEMA gpt_test_sch CASCADE; -NOTICE: drop cascades to table gpt_test_sch.tbl_sch +NOTICE: drop cascades to 2 other objects +DETAIL: drop cascades to table gpt_test_sch.tbl_sch +drop cascades to table gpt_test_sch.tbl_sch2 -- stage objects for pg_dump tests CREATE SCHEMA pubme CREATE TABLE t0 (c int, d int) CREATE TABLE t1 (c int); CREATE SCHEMA pubme2 CREATE TABLE t0 (c int, d int); diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 041e14a4de6..013d7249b27 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -123,6 +123,9 @@ CREATE PUBLICATION testpub_foralltables_excepttable1 FOR ALL TABLES EXCEPT (TABL \d testpub_tbl1 -- fail - first table in the EXCEPT list should use TABLE keyword CREATE PUBLICATION testpub_foralltables_excepttable2 FOR ALL TABLES EXCEPT (testpub_tbl1, testpub_tbl2); +-- fail - EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testpub_tbl3); --------------------------------------------- -- SET ALL TABLES/SEQUENCES @@ -220,7 +223,90 @@ RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Create same-named tables in public to verify unqualified EXCEPT entries +-- are qualified with the named schema, not public +CREATE TABLE testpub_nopk (foo int, bar int); +CREATE TABLE testpub_tbl_s1 (a int primary key, b text); + +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + +-- Exclude multiple tables using unqualified names; same-named tables exist in +-- public to confirm unqualified names resolve to pub_test, not public +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); + +-- Multiple schemas each with their own EXCEPT clause +CREATE PUBLICATION testpub_schema_except_multi + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_schema_except_multi + +-- ALTER TABLE ... SET SCHEMA on a table excluded by a schema publication: +-- the schema-scoped exclusion is no longer meaningful once the table moves +-- out of its schema, so the exclusion is auto-removed. +CREATE PUBLICATION testpub_schema_except_setsch + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_schema_except_setsch +ALTER TABLE pub_test.testpub_tbl_s2 SET SCHEMA public; +\dRp+ testpub_schema_except_setsch +DROP PUBLICATION testpub_schema_except_setsch; +-- Restore for further tests +ALTER TABLE public.testpub_tbl_s2 SET SCHEMA pub_test; + +-- fail: table appears in both the explicit table list and the EXCEPT clause +CREATE PUBLICATION testpub_except_conflict + FOR TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: nonexistent table in EXCEPT clause +CREATE PUBLICATION testpub_except_norel + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- fail: partition cannot appear in EXCEPT clause; only root tables are allowed +CREATE TABLE pub_test.testpub_parted_s (a int) PARTITION BY LIST (a); +CREATE TABLE pub_test.testpub_part_s PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (1); +CREATE PUBLICATION testpub_except_partition + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); + +-- fail: TABLE keyword is required for the first entry in the EXCEPT clause +CREATE PUBLICATION testpub_except_nokw + FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + +-- error: ADD TABLE for a partition is rejected when a partition ancestor +-- is currently in the publication's EXCEPT list. +CREATE PUBLICATION testpub_except_ancestor + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ALTER PUBLICATION testpub_except_ancestor ADD TABLE pub_test.testpub_part_s; +DROP PUBLICATION testpub_except_ancestor; + +-- Cleanup +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP TABLE pub_test.testpub_parted_s CASCADE; +DROP TABLE testpub_nopk, testpub_tbl_s1; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; + +--------------------------------------------- +-- Tests for publications with SEQUENCES +--------------------------------------------- CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; @@ -1189,6 +1275,18 @@ ALTER PUBLICATION testpub1_forschema SET TABLES IN SCHEMA pub_test1, pub_test1; ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo (a, b); ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b); +-- EXCEPT clause with CURRENT_SCHEMA: cross-schema entry must be rejected +SET search_path = pub_test1; +-- qualified name from wrong schema -> error +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.tbl1); +-- unqualified name implicitly qualified with current schema (pub_test1.tbl) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl); +RESET client_min_messages; +\dRp+ testpub_cursch_except +DROP PUBLICATION testpub_cursch_except; +RESET search_path; + -- cleanup pub_test1 schema for invalidation tests ALTER PUBLICATION testpub2_forschema DROP TABLES IN SCHEMA pub_test1; DROP PUBLICATION testpub3_forschema, testpub4_forschema, testpub5_forschema, testpub6_forschema, testpub_fortable; @@ -1443,6 +1541,7 @@ DROP ROLE regress_publication_user_dummy; -- Test pg_get_publication_tables(text[], oid) function CREATE SCHEMA gpt_test_sch; CREATE TABLE gpt_test_sch.tbl_sch (id int); +CREATE TABLE gpt_test_sch.tbl_sch2 (id int); CREATE TABLE tbl_normal (id int); CREATE TABLE tbl_parent (id1 int, id2 int, id3 int) PARTITION BY RANGE (id1); CREATE TABLE tbl_part1 PARTITION OF tbl_parent FOR VALUES FROM (1) TO (10); @@ -1454,6 +1553,7 @@ CREATE PUBLICATION pub_all_no_viaroot FOR ALL TABLES WITH (publish_via_partition CREATE PUBLICATION pub_all_except FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = true); CREATE PUBLICATION pub_all_except_no_viaroot FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_schema FOR TABLES IN SCHEMA gpt_test_sch; +CREATE PUBLICATION pub_schema_except FOR TABLES IN SCHEMA gpt_test_sch EXCEPT (TABLE gpt_test_sch.tbl_sch); CREATE PUBLICATION pub_normal FOR TABLE tbl_normal WHERE (id < 10); CREATE PUBLICATION pub_part_leaf FOR TABLE tbl_part1 WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_part_parent FOR TABLE tbl_parent (id1, id2) WHERE (id1 = 10) WITH (publish_via_partition_root = true); @@ -1510,6 +1610,10 @@ SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'gpt_test_sch.tbl_sch SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_parent'); -- no result (excluded) SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_part1'); -- no result +-- test for EXCEPT clause with schema publication +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch'); -- no result (excluded) +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch2'); -- one row (included via schema) + -- two rows with different row filter SELECT * FROM test_gpt(ARRAY['pub_all', 'pub_normal'], 'tbl_normal'); @@ -1538,6 +1642,7 @@ DROP PUBLICATION pub_all_no_viaroot; DROP PUBLICATION pub_all_except; DROP PUBLICATION pub_all_except_no_viaroot; DROP PUBLICATION pub_schema; +DROP PUBLICATION pub_schema_except; DROP PUBLICATION pub_normal; DROP PUBLICATION pub_part_leaf; DROP PUBLICATION pub_part_parent; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 8c58d282eee..18c7b2c1fca 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -24,14 +24,17 @@ my $result; sub test_except_root_partition { - my ($pubviaroot) = @_; + my ($pubviaroot, $pubsql) = @_; + $pubsql //= + "CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1)"; + $pubsql .= " WITH (publish_via_partition_root = $pubviaroot)"; # If the root partitioned table is in the EXCEPT clause, all its # partitions are excluded from publication, regardless of the # publish_via_partition_root setting. $node_publisher->safe_psql( 'postgres', qq( - CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1) WITH (publish_via_partition_root = $pubviaroot); + $pubsql; INSERT INTO root1 VALUES (1), (101); )); $node_subscriber->safe_psql('postgres', @@ -223,6 +226,131 @@ $node_subscriber->safe_psql( test_except_root_partition('false'); test_except_root_partition('true'); +# Same validation using TABLES IN SCHEMA instead of FOR ALL TABLES. +my $schema_pub = + "CREATE PUBLICATION tap_pub_part FOR TABLES IN SCHEMA public EXCEPT (TABLE public.root1)"; +test_except_root_partition('false', $schema_pub); +test_except_root_partition('true', $schema_pub); + +# ============================================ +# EXCEPT test cases for TABLES IN SCHEMA +# ============================================ + +# Create a dedicated schema with two tables: one to be published and one to be +# excluded. Also create inherited tables to verify ONLY semantics. +$node_publisher->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_published AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.tab_excluded AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.parent (a int); + CREATE TABLE sch1.child (b int) INHERITS (sch1.parent); +)); + +$node_subscriber->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_published (a int); + CREATE TABLE sch1.tab_excluded (a int); + CREATE TABLE sch1.parent (a int); + CREATE TABLE sch1.child (b int) INHERITS (sch1.parent); +)); + +# Basic test: initial sync respects EXCEPT. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_excluded)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: initial sync copies included table'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: initial sync skips excluded table'); + +# DML: only the included table should be replicated. +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (6); + INSERT INTO sch1.tab_excluded VALUES (6); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(6), + 'TABLES IN SCHEMA EXCEPT: DML on included table is replicated'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: DML on excluded table is not replicated'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Inherited tables: excluding the parent (without ONLY) also excludes the child. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.parent)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.child VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.child"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: excluding parent (without ONLY) also excludes child' +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Test that EXCEPT (TABLE ONLY parent) excludes only the parent itself, not its +# child. Truncate child first so rows from the previous test are not copied by +# the initial table sync of the next subscription. +$node_publisher->safe_psql('postgres', 'TRUNCATE sch1.child'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE sch1.child'); +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE ONLY sch1.parent)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.child VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.child"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: ONLY parent in EXCEPT does not exclude child'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Cleanup schema tables before the multi-publication section. +$node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); +$node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); + # ============================================ # Test when a subscription is subscribing to multiple publications # ============================================ @@ -254,6 +382,7 @@ $node_publisher->safe_psql( DROP PUBLICATION tap_pub2; TRUNCATE tab1; )); +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_subscriber->safe_psql('postgres', qq(TRUNCATE tab1)); # OK when a table is excluded by pub1 EXCEPT clause, but it is included by pub2 -- 2.50.1 (Apple Git-155)
v18-0002-Add-EXCEPT-support-to-ALTER-PUBLICATION-ADD-TABL.patch (application/x-patch, 18.6K) download From 0ca5916fc07bda872dc95c83aeb21d17cea0120d Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Fri, 3 Jul 2026 19:42:25 +0530 Subject: [PATCH v18 2/4] Add EXCEPT support to ALTER PUBLICATION ADD TABLES IN SCHEMA Extend the EXCEPT clause support to allow tables to be excluded when adding a schema to a publication via ALTER PUBLICATION ... ADD. Syntax: ALTER PUBLICATION pub ADD TABLES IN SCHEMA s EXCEPT (TABLE s.t1); Since pg_dump uses ALTER PUBLICATION ... ADD, support for it is included in this patch. --- src/backend/catalog/pg_publication.c | 19 +++-- src/backend/commands/publicationcmds.c | 98 ++++++++++++++++++++++- src/bin/pg_dump/pg_dump.c | 30 ++++++- src/bin/pg_dump/t/002_pg_dump.pl | 24 ++++++ src/bin/psql/tab-complete.in.c | 17 ++++ src/test/regress/expected/publication.out | 32 +++++++- src/test/regress/sql/publication.sql | 20 ++++- src/test/subscription/t/037_except.pl | 32 ++++++++ 8 files changed, 258 insertions(+), 14 deletions(-) diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index ce0f6d5b8c1..ae51d783798 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -713,15 +713,18 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, * here, as CreatePublication() function invalidates all relations as part * of defining a FOR ALL TABLES publication. * - * For ALTER PUBLICATION, invalidation is needed only when adding an - * EXCEPT table to a publication already marked as ALL TABLES. For - * publications that were originally empty or defined as ALL SEQUENCES and - * are being converted to ALL TABLES, invalidation is skipped here, as - * AlterPublicationAllFlags() function invalidates all relations while - * marking the publication as ALL TABLES publication. + * For ALTER PUBLICATION, invalidation is needed when adding an EXCEPT + * table to either a FOR ALL TABLES publication (pub->alltables is true) + * or a FOR TABLES IN SCHEMA publication (is_schema_publication is true). + * The exception: when a publication is being converted to FOR ALL TABLES + * (pub->alltables is still false at this point), + * AlterPublicationAllFlags() will perform a full invalidation, so we skip + * it here. */ - inval_except_table = (alter_stmt != NULL) && pub->alltables && - (alter_stmt->for_all_tables && pri->except); + inval_except_table = (alter_stmt != NULL) && pri->except && + (pub->alltables + ? alter_stmt->for_all_tables + : is_schema_publication(pubid)); if (!pri->except || inval_except_table) { diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 45a8a5c3f71..542579dae86 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -70,6 +70,13 @@ static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok); static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); +static void AlterPublicationSchemas(AlterPublicationStmt *stmt, + HeapTuple tup, List *schemaidlist, + List *except_pubtables); +static void AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, + List *except_pubtables, + List *schemaidlist); static char defGetGeneratedColsOption(DefElem *def); static void CheckExceptNotInTableList(List *except_rels, List *explicitrelids); @@ -1509,7 +1516,8 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, */ static void AlterPublicationSchemas(AlterPublicationStmt *stmt, - HeapTuple tup, List *schemaidlist) + HeapTuple tup, List *schemaidlist, + List *except_pubtables) { Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); @@ -1586,6 +1594,88 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, */ PublicationAddSchemas(pubform->oid, schemaidlist, true, stmt); } + + /* + * Increment the command counter so that is_schema_publication() in + * GetExcludedPublicationTables() can see the just-inserted schema + * rows when AlterPublicationSchemaExceptTables runs next. + */ + if (stmt->action == AP_AddObjects || stmt->action == AP_SetObjects) + CommandCounterIncrement(); + + AlterPublicationSchemaExceptTables(stmt, tup, except_pubtables, schemaidlist); +} + +/* + * Alter the EXCEPT list of a schema-level publication. + * + * Adds, removes, or replaces except-table entries in pg_publication_rel + * (rows with prexcept = true). These entries suppress publication of the + * named tables that would otherwise be covered by a FOR TABLES IN SCHEMA + * clause. + */ +static void +AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, List *except_pubtables, + List *schemaidlist) +{ + Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); + Oid pubid = pubform->oid; + + /* + * Nothing to do if no EXCEPT entries. + */ + if (!except_pubtables) + return; + + /* + * This function handles EXCEPT entries for schema-level publications + * only. For FOR ALL TABLES publications, EXCEPT entries are already + * processed by AlterPublicationTables(). + */ + if (schemaidlist == NIL && !is_schema_publication(pubid)) + return; + + /* + * Dropping a schema from a publication removes all its EXCEPT entries via + * cascade. The concept of "drop all schema tables from the publication + * EXCEPT these ones" is not supported. + */ + if (stmt->action == AP_DropObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); + + /* + * XXX EXCEPT with SET is not currently implemented. Workaround: DROP and + * re-ADD the schema with the desired EXCEPT list. + */ + if (stmt->action == AP_SetObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"), + errhint("Drop and re-add the schema with the desired EXCEPT list."))); + + if (stmt->action == AP_AddObjects) + { + List *rels; + List *explicitrelids; + + rels = OpenTableList(except_pubtables); + + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + /* + * Validate that each excluded table is not also in the explicit table + * list (which would be contradictory). + */ + CheckExceptNotInTableList(rels, explicitrelids); + + PublicationAddTables(pubid, rels, false, stmt); + + CloseTableList(rels); + } } /* @@ -1795,10 +1885,12 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) errmsg("publication \"%s\" does not exist", stmt->pubname)); - relations = list_concat(relations, except_pubtables); + if (stmt->for_all_tables) + relations = list_concat(relations, except_pubtables); + AlterPublicationTables(stmt, tup, relations, pstate->p_sourcetext, schemaidlist != NIL); - AlterPublicationSchemas(stmt, tup, schemaidlist); + AlterPublicationSchemas(stmt, tup, schemaidlist, except_pubtables); AlterPublicationAllFlags(stmt, rel, tup); } diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c index f67daf85911..007a1eadcaa 100644 --- a/src/bin/pg_dump/pg_dump.c +++ b/src/bin/pg_dump/pg_dump.c @@ -4973,6 +4973,7 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) PublicationInfo *pubinfo = pubsinfo->publication; PQExpBuffer query; char *tag; + bool has_except = false; /* Do nothing if not dumping schema */ if (!dopt->dumpSchema) @@ -4983,7 +4984,34 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) query = createPQExpBuffer(); appendPQExpBuffer(query, "ALTER PUBLICATION %s ", fmtId(pubinfo->dobj.name)); - appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s;\n", fmtId(schemainfo->dobj.name)); + appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s", fmtId(schemainfo->dobj.name)); + + /* + * Append EXCEPT clause for any tables that belong to this schema + * and are excluded from the publication. + */ + for (SimplePtrListCell *cell = pubinfo->except_tables.head; cell; cell = cell->next) + { + TableInfo *tbinfo = (TableInfo *) cell->ptr; + + if (strcmp(tbinfo->dobj.namespace->dobj.name, schemainfo->dobj.name) == 0) + { + if (!has_except) + { + appendPQExpBufferStr(query, " EXCEPT ("); + has_except = true; + } + else + appendPQExpBufferStr(query, ", "); + + appendPQExpBuffer(query, "TABLE ONLY %s", fmtId(tbinfo->dobj.name)); + } + } + + if (has_except) + appendPQExpBufferStr(query, ")"); + + appendPQExpBufferStr(query, ";\n"); /* * There is no point in creating drop query as the drop is done by schema diff --git a/src/bin/pg_dump/t/002_pg_dump.pl b/src/bin/pg_dump/t/002_pg_dump.pl index 9258948b583..d18b3b0d7b9 100644 --- a/src/bin/pg_dump/t/002_pg_dump.pl +++ b/src/bin/pg_dump/t/002_pg_dump.pl @@ -3283,6 +3283,30 @@ my %tests = ( like => { %full_runs, section_post_data => 1, }, }, + 'CREATE PUBLICATION pub11' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub11 FOR TABLES IN SCHEMA dump_test EXCEPT (TABLE test_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub11 WITH (publish = 'insert, update, delete, truncate');\E + .*? + \QALTER PUBLICATION pub11 ADD TABLES IN SCHEMA dump_test EXCEPT (TABLE ONLY test_table);\E + /xms, + like => { %full_runs, section_post_data => 1, }, + }, + + 'CREATE PUBLICATION pub12' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub12 FOR TABLES IN SCHEMA dump_test EXCEPT (TABLE test_table, dump_test.test_second_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub12 WITH (publish = 'insert, update, delete, truncate');\E + .*? + \QALTER PUBLICATION pub12 ADD TABLES IN SCHEMA dump_test EXCEPT (TABLE ONLY test_table, TABLE ONLY test_second_table);\E + /xms, + like => { %full_runs, section_post_data => 1, }, + }, + 'CREATE SUBSCRIPTION sub1' => { create_order => 50, create_sql => 'CREATE SUBSCRIPTION sub1 diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index 5fd4f86ce70..1b9cc926d81 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2359,6 +2359,23 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); + /* After a single schema name in ADD context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index b4104e8220a..b17ea933b76 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -600,12 +600,42 @@ ERROR: cannot add table "pub_test.testpub_part_s" to publication "testpub_excep DETAIL: Partition ancestor "pub_test.testpub_parted_s" of table "pub_test.testpub_part_s" is currently listed in the EXCEPT clause of the publication. HINT: Change EXCEPT list using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT. DROP PUBLICATION testpub_except_ancestor; +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; +-- fail: non-existing table in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- fail: EXCEPT table belongs to a different schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 1: ...xcept ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.tes... + ^ +-- fail: TABLE keyword is required for the first entry in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +ERROR: syntax error at or near "testpub_nopk" +LINE 1: ...lter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_no... + ^ +-- ADD: qualified and unqualified names; unqualified is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + "pub_test.testpub_tbl_s2" + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP TABLE pub_test.testpub_parted_s CASCADE; DROP TABLE testpub_nopk, testpub_tbl_s1; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi, testpub_alter_except; --------------------------------------------- -- Tests for publications with SEQUENCES --------------------------------------------- diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 013d7249b27..048609bbc96 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -297,12 +297,30 @@ CREATE PUBLICATION testpub_except_ancestor ALTER PUBLICATION testpub_except_ancestor ADD TABLE pub_test.testpub_part_s; DROP PUBLICATION testpub_except_ancestor; +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; + +-- fail: non-existing table in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- fail: EXCEPT table belongs to a different schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- fail: TABLE keyword is required for the first entry in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + +-- ADD: qualified and unqualified names; unqualified is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); +\dRp+ testpub_alter_except + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP TABLE pub_test.testpub_parted_s CASCADE; DROP TABLE testpub_nopk, testpub_tbl_s1; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi, testpub_alter_except; --------------------------------------------- -- Tests for publications with SEQUENCES diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 18c7b2c1fca..0ba6d6f8bb2 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -347,6 +347,38 @@ is($result, qq(5), $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); +# ============================================ +# ALTER PUBLICATION EXCEPT for TABLES IN SCHEMA +# ============================================ + +# Truncate subscriber tables to remove data accumulated from previous tests. +$node_subscriber->safe_psql('postgres', + 'TRUNCATE sch1.tab_published, sch1.tab_excluded, sch1.parent, sch1.child'); + +# ADD: add a schema with an excepted table; verify the except entry takes effect. +$node_publisher->safe_psql('postgres', "CREATE PUBLICATION sch_pub"); +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub ADD TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_excluded)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(6), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: included table synced'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + # Cleanup schema tables before the multi-publication section. $node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); $node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); -- 2.50.1 (Apple Git-155)
v18-0003-Add-EXCEPT-support-to-ALTER-PUBLICATION-SET-TABL.patch (application/x-patch, 26.9K) download From 73eef80617be353e601c92e54102434af0cbc924 Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Thu, 18 Jun 2026 11:32:32 +0530 Subject: [PATCH v18 3/4] Add EXCEPT support to ALTER PUBLICATION SET TABLES IN SCHEMA Extend AlterPublicationExceptTables() with the AP_SetObjects case, which redefines the publication and replaces the entire EXCEPT list. Syntax: ALTER PUBLICATION pub SET TABLES IN SCHEMA s EXCEPT (TABLE t1); This patch also cleans up EXCEPT entries when a schema is dropped from the publication. --- src/backend/commands/publicationcmds.c | 181 +++++++++++++++++++--- src/bin/psql/tab-complete.in.c | 17 ++ src/test/regress/expected/publication.out | 105 +++++++++++++ src/test/regress/sql/publication.sql | 44 ++++++ src/test/subscription/t/037_except.pl | 85 ++++++++++ 5 files changed, 407 insertions(+), 25 deletions(-) diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 542579dae86..423dbc152e6 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -66,7 +66,8 @@ static void CloseTableList(List *rels); static void LockSchemaList(List *schemalist); static void PublicationAddTables(Oid pubid, List *rels, bool if_not_exists, AlterPublicationStmt *stmt); -static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok); +static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok, + bool delete_excluded); static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); @@ -1360,7 +1361,7 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, PublicationAddTables(pubid, rels, false, stmt); } else if (stmt->action == AP_DropObjects) - PublicationDropTables(pubid, rels, false); + PublicationDropTables(pubid, rels, false, false); else /* AP_SetObjects */ { List *oldrelids = NIL; @@ -1495,7 +1496,7 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, } /* And drop them. */ - PublicationDropTables(pubid, delrels, true); + PublicationDropTables(pubid, delrels, true, true); /* * Don't bother calculating the difference for adding, we'll catch and @@ -1597,8 +1598,8 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, /* * Increment the command counter so that is_schema_publication() in - * GetExcludedPublicationTables() can see the just-inserted schema - * rows when AlterPublicationSchemaExceptTables runs next. + * GetExcludedPublicationTables() can see the just-inserted schema rows + * when AlterPublicationSchemaExceptTables runs next. */ if (stmt->action == AP_AddObjects || stmt->action == AP_SetObjects) CommandCounterIncrement(); @@ -1616,16 +1617,18 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, */ static void AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, - HeapTuple tup, List *except_pubtables, - List *schemaidlist) + HeapTuple tup, List *except_pubtables, + List *schemaidlist) { Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); Oid pubid = pubform->oid; /* - * Nothing to do if no EXCEPT entries. + * Nothing to do if there are no EXCEPT entries, unless handling the SET + * command, because if the user has removed all exceptions we need to drop + * any existing ones. */ - if (!except_pubtables) + if (!except_pubtables && stmt->action != AP_SetObjects) return; /* @@ -1646,16 +1649,6 @@ AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); - /* - * XXX EXCEPT with SET is not currently implemented. Workaround: DROP and - * re-ADD the schema with the desired EXCEPT list. - */ - if (stmt->action == AP_SetObjects) - ereport(ERROR, - (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"), - errhint("Drop and re-add the schema with the desired EXCEPT list."))); - if (stmt->action == AP_AddObjects) { List *rels; @@ -1674,6 +1667,75 @@ AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, PublicationAddTables(pubid, rels, false, stmt); + CloseTableList(rels); + } + else /* AP_SetObjects */ + { + List *oldexceptrelids = NIL; + List *newexceptrelids = NIL; + List *delrelids = NIL; + List *rels; + List *explicitrelids; + + rels = OpenTableList(except_pubtables); + + /* Collect OIDs of the desired new EXCEPT list. */ + foreach_ptr(PublicationRelInfo, pri, rels) + newexceptrelids = lappend_oid(newexceptrelids, + RelationGetRelid(pri->relation)); + + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + /* + * Validate that each excluded table is not also in the explicit table + * list (which would be contradictory). + */ + CheckExceptNotInTableList(rels, explicitrelids); + + /* + * Get the current set of EXCEPT entries. Only FOR ALL TABLES and + * schema-level publications can have EXCEPT entries; for any other + * publication type oldexceptrelids stays NIL. + * + * Note: we check is_schema_publication() against the current catalog + * state (before AlterPublicationSchemas has run), so if the caller is + * doing SET TABLE t1 to convert a schema publication into a plain + * table publication, is_schema_publication() still returns true here. + * That is intentional: it lets us discover and clean up any stale + * EXCEPT entries that belong to the old schema definition. + */ + if (GetPublication(pubid)->alltables || is_schema_publication(pubid)) + oldexceptrelids = GetExcludedPublicationTables(pubid, + PUBLICATION_PART_ROOT); + + /* Build a list of old EXCEPT entries not present in the new list. */ + foreach_oid(oldrelid, oldexceptrelids) + { + if (!list_member_oid(newexceptrelids, oldrelid)) + delrelids = lappend_oid(delrelids, oldrelid); + } + + /* Drop old EXCEPT entries not present in the new list. */ + foreach_oid(relid, delrelids) + { + Oid proid; + ObjectAddress obj; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + /* Add new EXCEPT entries, skipping any already present. */ + PublicationAddTables(pubid, rels, true, stmt); + CloseTableList(rels); } } @@ -2297,33 +2359,69 @@ PublicationAddTables(Oid pubid, List *rels, bool if_not_exists, /* * Remove listed tables from the publication. + * + * delete_excluded controls how EXCEPT (prexcept=true) rows are handled: + * true - delete them silently. Used by the SET path to clear stale + * EXCEPT rows that are being replaced by a new EXCEPT list. + * false - treat them as "not a member". Used by ALTER ... DROP TABLE: an + * EXCEPT entry is not something DROP TABLE is expected to remove. */ static void -PublicationDropTables(Oid pubid, List *rels, bool missing_ok) +PublicationDropTables(Oid pubid, List *rels, bool missing_ok, + bool delete_excluded) { ObjectAddress obj; ListCell *lc; - Oid prid; foreach(lc, rels) { PublicationRelInfo *pubrel = (PublicationRelInfo *) lfirst(lc); Relation rel = pubrel->relation; Oid relid = RelationGetRelid(rel); + HeapTuple tup; + Form_pg_publication_rel pubrelform; + Oid prid = InvalidOid; + bool is_except = false; if (pubrel->columns) ereport(ERROR, errcode(ERRCODE_SYNTAX_ERROR), errmsg("column list must not be specified in ALTER PUBLICATION ... DROP")); - prid = GetSysCacheOid2(PUBLICATIONRELMAP, Anum_pg_publication_rel_oid, - ObjectIdGetDatum(relid), - ObjectIdGetDatum(pubid)); - if (!OidIsValid(prid)) + tup = SearchSysCache2(PUBLICATIONRELMAP, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (HeapTupleIsValid(tup)) + { + pubrelform = (Form_pg_publication_rel) GETSTRUCT(tup); + is_except = pubrelform->prexcept; + prid = pubrelform->oid; + ReleaseSysCache(tup); + } + + /* + * DROP TABLE operates only on regular member rows. A missing row + * and an EXCEPT row both mean the table isn't currently published, + * but we distinguish them so the EXCEPT case can carry a hint + * pointing the user at the EXCEPT list. The SET-cleanup caller + * (delete_excluded = true) intends to remove EXCEPT rows and so + * bypasses the EXCEPT half of this check. + */ + if (!OidIsValid(prid) || (is_except && !delete_excluded)) { if (missing_ok) continue; + if (is_except) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("cannot drop table \"%s\" from publication \"%s\"", + RelationGetQualifiedRelationName(rel), + get_publication_name(pubid, false)), + errdetail("Table \"%s\" is currently listed in the EXCEPT clause of the publication.", + RelationGetQualifiedRelationName(rel)), + errhint("Change EXCEPT list using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT."))); + ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("relation \"%s\" is not part of the publication", @@ -2379,6 +2477,7 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) foreach(lc, schemas) { Oid schemaid = lfirst_oid(lc); + List *except_relids; psid = GetSysCacheOid2(PUBLICATIONNAMESPACEMAP, Anum_pg_publication_namespace_oid, @@ -2395,8 +2494,40 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) get_namespace_name(schemaid)))); } + /* + * Collect EXCEPT entries for tables belonging to this schema before + * removing the schema entry. + */ + except_relids = GetExcludedPublicationTables(pubid, PUBLICATION_PART_ROOT); + ObjectAddressSet(obj, PublicationNamespaceRelationId, psid); performDeletion(&obj, DROP_CASCADE, 0); + + /* + * Drop any prexcept rows for tables belonging to this schema. These + * rows have no pg_depend entry pointing at the + * pg_publication_namespace row, so they are not cascaded by the + * performDeletion() call above and must be cleaned up explicitly. + */ + foreach_oid(relid, except_relids) + { + Oid proid; + + if (get_rel_namespace(relid) != schemaid) + continue; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + list_free(except_relids); } } diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index 1b9cc926d81..7e769638acd 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2376,6 +2376,23 @@ match_previous_words(int pattern_id, } else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) COMPLETE_WITH(")"); + /* After a single schema name in SET context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index b17ea933b76..984159657f6 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -630,6 +630,111 @@ Except tables: "pub_test.testpub_tbl_s1" "pub_test.testpub_tbl_s2" +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s2" + +-- fail: table in EXCEPT clause also appears in the explicit table list +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot appear in both the table list and the EXCEPT clause +-- error: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 1: ...xcept SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.tes... + ^ +-- SET: unqualified name in EXCEPT is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- SET without EXCEPT clears the existing except list +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + +-- SET to a different schema removes old schema's EXCEPT entries +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA public; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "public" + +-- fail: nonexistent table in EXCEPT clause (SET path) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- SET: multiple schemas each with their own EXCEPT clause +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- error: ALTER PUBLICATION ... DROP TABLE on an excluded table is rejected +-- with an EXCEPT-specific error; an EXCEPT entry is not a member. +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_tbl_s1; +ERROR: cannot drop table "pub_test.testpub_tbl_s1" from publication "testpub_alter_except" +DETAIL: Table "pub_test.testpub_tbl_s1" is currently listed in the EXCEPT clause of the publication. +HINT: Change EXCEPT list using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT. +-- the EXCEPT entry is still present after the rejected DROP TABLE +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- error: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +ERROR: EXCEPT clause is not supported with DROP in ALTER PUBLICATION +-- DROP TABLES IN SCHEMA removes associated EXCEPT entries +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "public" +Except tables: + "public.testpub_tbl1" + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 048609bbc96..5c174a58df7 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -315,6 +315,50 @@ ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (tes ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); \dRp+ testpub_alter_except +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + +-- fail: table in EXCEPT clause also appears in the explicit table list +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- error: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- SET: unqualified name in EXCEPT is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +\dRp+ testpub_alter_except + +-- SET without EXCEPT clears the existing except list +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + +-- SET to a different schema removes old schema's EXCEPT entries +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA public; +\dRp+ testpub_alter_except + +-- fail: nonexistent table in EXCEPT clause (SET path) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- SET: multiple schemas each with their own EXCEPT clause +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_alter_except + +-- error: ALTER PUBLICATION ... DROP TABLE on an excluded table is rejected +-- with an EXCEPT-specific error; an EXCEPT entry is not a member. +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_tbl_s1; +-- the EXCEPT entry is still present after the rejected DROP TABLE +\dRp+ testpub_alter_except + +-- error: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); + +-- DROP TABLES IN SCHEMA removes associated EXCEPT entries +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 0ba6d6f8bb2..01eafb5b7c8 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -376,6 +376,61 @@ $result = is($result, qq(0), 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); +# SET: replace the except list; tab_excluded is now included and tab_published is excluded. +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_published)" +); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (7); + INSERT INTO sch1.tab_excluded VALUES (7); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded WHERE a = 7"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: newly included table is replicated' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published WHERE a = 7"); +is($result, qq(0), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: now-excluded table is not replicated' +); + +# SET without EXCEPT: clears the except list; both tables are now published. +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1"); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (8); + INSERT INTO sch1.tab_excluded VALUES (8); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published WHERE a = 8"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_published replicated after except list cleared' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded WHERE a = 8"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_excluded replicated after except list cleared' +); + $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); @@ -443,6 +498,36 @@ $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); +# OK when a table is excluded by a TABLES IN SCHEMA EXCEPT publication, +# but is included by another publication. +$node_publisher->safe_psql('postgres', 'TRUNCATE tab1'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE tab1'); + +$node_publisher->safe_psql( + 'postgres', qq( + CREATE PUBLICATION tap_pub1 FOR TABLES IN SCHEMA public EXCEPT (TABLE public.tab1); + CREATE PUBLICATION tap_pub2 FOR TABLE tab1; + INSERT INTO tab1 VALUES(1); +)); +$node_subscriber->psql('postgres', + "CREATE SUBSCRIPTION tap_sub CONNECTION '$publisher_connstr' PUBLICATION tap_pub1, tap_pub2" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'tap_sub'); + +$node_publisher->safe_psql('postgres', qq(INSERT INTO tab1 VALUES(2))); +$node_publisher->wait_for_catchup('tap_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT * FROM tab1 ORDER BY a"); +is( $result, qq(1 +2), + "TABLES IN SCHEMA EXCEPT: table excluded in schema pub but included by another pub is replicated" +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); + $node_publisher->stop('fast'); done_testing(); -- 2.50.1 (Apple Git-155)
v18-0004-Documentation-Patch.patch (application/x-patch, 11.5K) download From 6fd3ddc0d36b722cb83313620531f3909eae140a Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Thu, 18 Jun 2026 09:03:08 +0530 Subject: [PATCH v18 4/4] Documentation Patch --- doc/src/sgml/logical-replication.sgml | 3 +- doc/src/sgml/ref/alter_publication.sgml | 58 +++++++++++++++++++++++- doc/src/sgml/ref/create_publication.sgml | 40 ++++++++++++---- 3 files changed, 90 insertions(+), 11 deletions(-) diff --git a/doc/src/sgml/logical-replication.sgml b/doc/src/sgml/logical-replication.sgml index f21239af6b8..c9918788c7f 100644 --- a/doc/src/sgml/logical-replication.sgml +++ b/doc/src/sgml/logical-replication.sgml @@ -117,7 +117,8 @@ or <literal>FOR ALL SEQUENCES</literal>. Unlike tables, sequences can be synchronized at any time. For more information, see <xref linkend="logical-replication-sequences"/>. When a publication is - created with <literal>FOR ALL TABLES</literal>, a table or set of tables can + created with <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal>, a table or set of tables can be explicitly excluded from publication using the <link linkend="sql-createpublication-params-for-except-table"><literal>EXCEPT</literal></link> clause. diff --git a/doc/src/sgml/ref/alter_publication.sgml b/doc/src/sgml/ref/alter_publication.sgml index 52114a16a39..037ddfa9404 100644 --- a/doc/src/sgml/ref/alter_publication.sgml +++ b/doc/src/sgml/ref/alter_publication.sgml @@ -31,7 +31,7 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA <replaceable class="parameter">tables_in_schema</replaceable> [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -47,6 +47,10 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <replaceable class="parameter">table_object</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] [ WHERE ( <replaceable class="parameter">expression</replaceable> ) ] +<phrase>and <replaceable class="parameter">tables_in_schema</replaceable> is:</phrase> + + { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] + <phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> TABLE <replaceable class="parameter">table_object</replaceable> [, ... ] @@ -69,6 +73,9 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r The first two variants modify which tables/schemas are part of the publication. The <literal>ADD</literal> and <literal>DROP</literal> clauses will add and remove one or more tables/schemas from the publication. + The <literal>EXCEPT</literal> clause can be used with + <literal>ADD TABLES IN SCHEMA</literal> to exclude specific tables from a + schema-level publication. </para> <para> @@ -93,7 +100,11 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r used with a publication defined with <literal>FOR TABLE</literal> or <literal>FOR TABLES IN SCHEMA</literal>, replaces the list of tables/schemas in the publication with the specified list; the existing tables or schemas - that were present in the publication will be removed. + that were present in the publication will be removed. When + <literal>SET TABLES IN SCHEMA</literal> is used with an + <literal>EXCEPT</literal> clause, the excluded tables for each schema are + replaced with the specified list; if <literal>EXCEPT</literal> is omitted + for a schema, any existing exclusions for that schema are cleared. </para> <para> @@ -198,6 +209,27 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r </listitem> </varlistentry> + <varlistentry> + <term><literal>EXCEPT</literal></term> + <listitem> + <para> + When used with <literal>ADD TABLES IN SCHEMA</literal> + or <literal>SET TABLES IN SCHEMA</literal>, specifies + tables to be excluded from the publication. Each named + table must belong to the schema specified in the same + <literal>TABLES IN SCHEMA</literal> clause. Table names may be + schema-qualified or unqualified; unqualified names are implicitly + qualified with the schema named in the same clause. See + <xref linkend="sql-createpublication"/> for further details on the + semantics of <literal>EXCEPT</literal>. + </para> + <para> + Dropping a table always removes it from the <literal>EXCEPT</literal> + clause. + </para> + </listitem> + </varlistentry> + <varlistentry> <term><literal>SET ( <replaceable class="parameter">publication_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] )</literal></term> <listitem> @@ -288,6 +320,28 @@ ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA marketing, sales; </programlisting> </para> + <para> + Add schema <structname>sales</structname> to the publication + <structname>sales_publication</structname>, excluding the + <structname>sales.internal</structname> and + <structname>sales.drafts</structname> tables: +<programlisting> +ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA sales EXCEPT (TABLE internal, drafts); +</programlisting> + </para> + + <para> + Replace the schema list of <structname>sales_publication</structname> with + <structname>sales</structname>, excluding only + <structname>sales.drafts</structname>. Other than + <structname>sales.drafts</structname>, any previously excluded tables for schema + <structname>sales</structname> are no longer excluded. Any schemas previously in + <structname>sales_publication</structname> are removed: +<programlisting> +ALTER PUBLICATION sales_publication SET TABLES IN SCHEMA sales EXCEPT (TABLE drafts); +</programlisting> + </para> + <para> Add tables <structname>users</structname>, <structname>departments</structname> and schema diff --git a/doc/src/sgml/ref/create_publication.sgml b/doc/src/sgml/ref/create_publication.sgml index 85cfcaddafa..582706e5a8e 100644 --- a/doc/src/sgml/ref/create_publication.sgml +++ b/doc/src/sgml/ref/create_publication.sgml @@ -28,7 +28,7 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA <replaceable class="parameter">tables_in_schema</replaceable> [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -39,6 +39,10 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <replaceable class="parameter">table_object</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] [ WHERE ( <replaceable class="parameter">expression</replaceable> ) ] +<phrase>and <replaceable class="parameter">tables_in_schema</replaceable> is:</phrase> + + { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] + <phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> TABLE <replaceable class="parameter">table_object</replaceable> [, ... ] @@ -142,6 +146,8 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <para> Marks the publication as one that replicates changes for all tables in the specified list of schemas, including tables created in the future. + Tables listed in the <literal>EXCEPT</literal> clause for a given schema + are excluded from the publication. </para> <para> @@ -173,7 +179,7 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <para> Marks the publication as one that replicates changes for all tables in the database, including tables created in the future. Tables listed in - <literal>EXCEPT</literal> clause are excluded from the publication. + the <literal>EXCEPT</literal> clause are excluded from the publication. </para> </listitem> </varlistentry> @@ -198,13 +204,21 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <listitem> <para> This clause specifies a list of tables to be excluded from the - publication. + publication. It can be used with <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal>. For <literal>FOR TABLES IN + SCHEMA</literal>, the exclusion applies only to tables in the schema + associated with the <literal>EXCEPT</literal>. </para> <para> - Once a table is excluded, the exclusion applies to that table - regardless of its name or schema. Renaming the table or moving it to - another schema using <command>ALTER TABLE ... SET SCHEMA</command> does - not remove the exclusion. + Once a table is excluded under <literal>FOR ALL TABLES</literal>, the + exclusion applies to that table regardless of its name or schema. + Renaming the table or moving it to another schema using + <command>ALTER TABLE ... SET SCHEMA</command> does not remove the + exclusion. However, for <literal>FOR TABLES IN SCHEMA</literal>, because + the <literal>EXCEPT</literal> is schema-scoped, moving a schema-excluded + table to another schema does remove the exclusion; if the table is later + moved back, the exclusion is not restored and must be re-established + with <command>ALTER PUBLICATION</command>. </para> <para> For inherited tables, if <literal>ONLY</literal> is specified before the @@ -217,7 +231,8 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <para> For partitioned tables, only the root partitioned table may be specified in <literal>EXCEPT</literal>. Doing so excludes the root table and - all of its partitions from replication. The optional + all of its partitions from replication, even any partition that lives + in a schema which is itself included in the publication. The optional <literal>ONLY</literal> and <literal>*</literal> has no effect for partitioned tables. </para> @@ -521,6 +536,15 @@ CREATE PUBLICATION production_publication FOR TABLE users, departments, TABLES I CREATE PUBLICATION sales_publication FOR TABLES IN SCHEMA marketing, sales; </programlisting></para> + <para> + Create a publication that publishes all changes for all the tables present in + the schema <structname>sales</structname>, except + <structname>internal</structname> and <structname>drafts</structname>: +<programlisting> +CREATE PUBLICATION sales_filtered FOR TABLES IN SCHEMA sales EXCEPT (TABLE internal, drafts); +</programlisting> + </para> + <para> Create a publication that publishes all changes for table <structname>users</structname>, but replicates only columns <structname>user_id</structname> and -- 2.50.1 (Apple Git-155)
^ permalink raw reply [nested|flat] 196+ messages in thread

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-03 16:45  Nisha Moond <nisha.moond412@gmail.com>
  parent: Amit Kapila <amit.kapila16@gmail.com>
  0 siblings, 0 replies; 196+ messages in thread

From: Nisha Moond @ 2026-07-03 16:45 UTC (permalink / raw)
  To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Peter Smith <smithpb2250@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Thu, Jul 2, 2026 at 2:34 PM Amit Kapila <amit.kapila16@gmail.com> wrote:
>
> On Wed, Jul 1, 2026 at 3:54 PM shveta malik <shveta.malik@gmail.com> wrote:
> >
> > On Wed, Jul 1, 2026 at 3:42 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
> > >
> > > During tests, I found one behavior that needs discussion:
> > >
> > > Consider a partition hierarchy where the root table is in schema s2, a
> > > child partition is in schema s1, and the publication includes both
> > > schemas but excludes only the root table.
> >
> > This is the exact scenario I had in mind when reviewing
> > 'get_rel_sync_entry-->GetTopMostAncestorInPublication' flow, thus I
> > suggested adding comments about intentionally fetching the 'Exclude
> > list' only for the Root. I was about to test it in my next review
> > cycle.
> >
> > The first thought is that if root is excluded, the partition should
> > also be excluded to maintain consistency with the 'ALL TABLES Except
> > ROOT' behaviour. But then it needs to be documented too.
> >
>
> +1. It is good to be consistent here with similar ALL TABLES case.
> BTW, as we can't exclude the child table explicitly, this anyway seems
> like the only option because otherwise, users won't have any way to
> exclude the child table.
>

I've updated the related comments in v18 and also updated the CREATE
PUBLICATION docs to clarify this behavior.

--
Thanks,
Nisha





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-06 03:11  shveta malik <shveta.malik@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  3 siblings, 0 replies; 196+ messages in thread

From: shveta malik @ 2026-07-06 03:11 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; shveta malik <shveta.malik@gmail.com>

On Fri, Jul 3, 2026 at 10:15 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
>
> On Thu, Jul 2, 2026 at 2:19 PM shveta malik <shveta.malik@gmail.com> wrote:
> >
> > A few comments:
> >
> > 1)
> > postgres=# alter publication pub1 add table s2.t1;
> > ERROR:  table "s2.t1" cannot be added because it is excluded from
> > publication "pub1"
> >
> > It will be good to add hint in above error.
> >
> > Suggestion:
> > ERROR: cannot add table "s2.t1" to publication "pub1"
> > DETAIL: Table "s2.t1" is currently in EXCEPT list
> > HINT: Change EXCEPT list using ALTER PUBLICATION ..SET TABLES IN
> > SCHEMA .. EXCEPT
> >
> > Please rephrase above as needed. Look earlier such messages/hints
> > already added for ALL TABLES.
> >
>
> Updated the error as suggested, with a slight change in DETAIL message.
>
> > From the user's perspective, it seems slightly odd that if he has
> > excluded a table from publication, he can not add it back using 'add
> > table'. Was this point discussed earlier?
> >
>
> This hasn't been discussed yet.
>
> I kept the current behavior, as IMO, it is hard to tell whether the
> user is trying to re-include a table or whether the ADD is unintended
> and should be blocked. To avoid ambiguity, I think EXCEPT entries
> should be modified only through the EXCEPT (...) clause itself, such
> as ALTER PUBLICATION ... ADD/SET ... EXCEPT(TABLE ...), or by omitting
> EXCEPT in the SET case.
>
> This would also keep the behavior of ADD TABLE and DROP TABLE aligned,
> as both would operate only on the include list without touching the
> EXCEPT list.
> I think this also aligns with FOR ALL TABLES, where ADD TABLE is
> disallowed, so the EXCEPT list can only be modified through SET ..
> EXCEPT (...).
>
> Thoughts?

Okay. Makes sense.

>
> > 2)
> > Currently:
> > postgres=# alter publication pub1 drop table s2.t1;
> > ERROR:  relation "t1" is not part of the publication
> >
> > s2.t1 is EXCEPT list here.
> >
> > Should we have below error for this case rather than above generic
> > error, it will be more intuitive for user. Plus both add and drop
> > table commands will have similar error-style for EXCEPT list.
> > Thoughts?
> >
> > ERROR: cannot drop table "s2.t1" from publication "pub1"
> > DETAIL: Table "s2.t1" is currently in EXCEPT list
> > HINT: Change EXCEPT list using ALTER PUBLICATION ..SET TABLES IN
> > SCHEMA .. EXCEPT
> >
>
> Makes sense. Fixed.
>
> > 3)
> > Please see below test:
> >
> > --Setting Except list for pub1 which has all tables of s2 included:
> > alter publication pub1 set tables in schema s2 EXCEPT ( TABLE t1, t2);
> >
> > --pg_publication_rel entries:
> > pubname | schema_name | table_name | prexcept
> > --------+-------------+------------+---------
> > pub1    | s2          | t1         | t
> > pub1    | s2          | t2         | t
> >
> >
> > --Then added a partition:
> > alter publication pub1 add table s2.tab_part_1_p2;
> >
> > --pg_publication_rel entries:
> > pubname | schema_name |  table_name   | prexcept
> > --------+-------------+---------------+---------
> > pub1    | s2          | t1            | t
> > pub1    | s2          | t2            | t
> > pub1    | s2          | tab_part_1_p2 | f
> >
> >
> > --Then changed pub1 to exclude tab_root (parent of tab_part_1_p2) as well:
> >
> > alter publication pub1 set tables in schema s2 EXCEPT ( TABLE t1, t2, tab_root);
> >
> > --pg_publication_rel entries:
> > pubname | schema_name | table_name | prexcept
> > --------+-------------+------------+---------
> > pub1    | s2          | t1         | t
> > pub1    | s2          | t2         | t
> > pub1    | s2          | tab_root   | t
> >
> > Note theoutput above, tab_part_1_p2 is removed internally as part of
> > earlier command since its parent tab_root is now excluded.
> >
> > --Now add parition back, it allowed to add it:
> > alter publication pub1 add table s2.tab_part_1_p2;
> >
> > pg_publication_rel entries:
> > pubname | schema_name |  table_name   | prexcept
> > --------+-------------+---------------+---------
> > pub1    | s2          | t1            | t
> > pub1    | s2          | t2            | t
> > pub1    | s2          | tab_root      | t
> > pub1    | s2          | tab_part_1_p2 | f
> >
> >
> > FOR ALL TABLES publicaiton, if root is excluded, there is no way
> > publication can have parition included independently. Same should hold
> > true here. Thoughts?
>
> Right, based on the discussion at [1], since we follow "all partitions
> are excluded if the root is excluded", a partition child should not be
> allowed to be added when its partition root is already excluded from
> the publication.
> Fixed. Such an operation will now raise an error:
>
> postgres=# alter publication pub2 add table t_part_p1;
> ERROR:  cannot add table "public.t_part_p1" to publication "pub2"
> DETAIL:  Partition ancestor "public.t_part" of table
> "public.t_part_p1" is currently listed in the EXCEPT clause of the
> publication.
> HINT:  Change EXCEPT list using ALTER PUBLICATION ... SET TABLES IN
> SCHEMA ... EXCEPT.
> ~~~

Okay, looks good.

thanks
Shveta





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-06 07:55  Peter Smith <smithpb2250@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  3 siblings, 1 reply; 196+ messages in thread

From: Peter Smith @ 2026-07-06 07:55 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

Hi Nisha.

Some review comments for v18.

//////////
Patch v18-0001
//////////

src/backend/catalog/pg_publication.c

1.
+ /*
+ * A partition cannot be independently included when any of its partition
+ * ancestors is in this publication's EXCEPT list.  Doing so would leave
+ * the catalog inconsistent (root excluded, partition explicitly included)
+ * and the ancestor-cascade rule would silently override the include at
+ * replication time.  Individual partitions cannot appear in EXCEPT
+ * (rejected above), so this check only applies to non-EXCEPT adds.
+ */
+ if (!pri->except && targetrel->rd_rel->relispartition)

It might be tidier to deal with partitions in one place.

SUGGESTION
if (targetrel->rd_rel->relispartition)
{
  if (pri->except)
  {
    /* If in EXCEPT clause, must be root partitioned table */
    ...
  } else {
    /* If not in EXCEPT clause, check ancestors are not excluded */
    ...
  }
}

~~~

2.
+ errmsg("cannot add table \"%s\" to publication \"%s\"",
+ RelationGetQualifiedRelationName(targetrel),
+ get_publication_name(pubid, false)),
+ errdetail("Partition ancestor \"%s\" of table \"%s\" is currently
listed in the EXCEPT clause of the publication.",

"Partition ancestor .. of table" sounded odd.

How about:
errmsg:  cannot add partition \"%s\" to ...
errdetail: Ancestor \"%s\" of partition \"%s\" is currently ...

~~~

publication_add_relation:

3.
+ ereport(ERROR,
+ (errcode(ERRCODE_DUPLICATE_OBJECT),
+ errmsg("cannot add table \"%s\" to publication \"%s\"",
+ RelationGetQualifiedRelationName(targetrel),
+ pub->name),
+ errdetail("Table \"%s\" is currently listed in the EXCEPT clause of
the publication.",

The table was already named in the errmsg. It seemed redundant to name
it again in the errdetail.

SUGGESTION
errdetail("The table is currently listed in the EXCEPT clause of the
publication.")

======
src/backend/commands/publicationcmds.c

4.
+ ereport(ERROR,
+ errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("table \"%s\" cannot appear in both the table list and the
EXCEPT clause",
+    RelationGetQualifiedRelationName(pri->relation)));

Do we need to name the clauses in this errmsg? Users can see what they typed.

SUGGESTION
errmsg("table \"%s\" cannot be both published and excluded")

//////////
Patch v18-0003
//////////

src/backend/commands/publicationcmds.c

PublicationDropTables:

1.
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("cannot drop table \"%s\" from publication \"%s\"",
+ RelationGetQualifiedRelationName(rel),
+ get_publication_name(pubid, false)),
+ errdetail("Table \"%s\" is currently listed in the EXCEPT clause of
the publication.",
+    RelationGetQualifiedRelationName(rel)),
+ errhint("Change EXCEPT list using ALTER PUBLICATION ... SET TABLES
IN SCHEMA ... EXCEPT.")));

1a.
(Same as above review comment for patch 0001).

The table was already named in the errmsg. It seemed redundant to name
it again in the errdetail.

SUGGESTION
errdetail("The table is currently listed in the EXCEPT clause of the
publication.")

~

1b.
Why hint to change the except list -- who says the EXCEPT list is wrong?

It seemed more like a user error to me if they are trying to drop
something from a publication when it is already excluded. Why does
this need any hint at all?

======
src/test/regress/sql/publication.sql

2.
I did not recognise the distinction in the test comments between
"fail:" and "error:".

~~~

3.
+-- error: ALTER PUBLICATION ... DROP TABLE on an excluded table is rejected
+-- with an EXCEPT-specific error; an EXCEPT entry is not a member.

I don't think you need to say "an EXCEPT entry is not a member." --
what does that mean, other than to redundantly say an excluded table
is a table that is excluded?

//////////
Patch v18-0004
//////////

doc/src/sgml/ref/create_publication.sgml

1.
      <para>
       For partitioned tables, only the root partitioned table may be specified
       in <literal>EXCEPT</literal>. Doing so excludes the root table and
-      all of its partitions from replication. The optional
+      all of its partitions from replication, even any partition that lives
+      in a schema which is itself included in the publication.

BEFORE
For partitioned tables, only the root partitioned table may be
specified in EXCEPT. Doing so excludes the root table and all of its
partitions from replication, even any partition that lives in a schema
which is itself included in the publication.

SUGGESTION #1
For partitioned tables, only the root partitioned table may be
specified in EXCEPT. Excluding the root table automatically excludes
all of its partitions from replication, including those in schemas
that are otherwise included in the publication.

SUGGESTION #2 (TI doubt you even needed to mention about other schemas)
For partitioned tables, only the root partitioned table may be
specified in EXCEPT. Excluding the root table automatically excludes
all of its partitions from replication, including those that would
otherwise be included in the publication.

======
Kind Regards,
Peter Smith.
Fujitsu Australia





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-06 23:01  Peter Smith <smithpb2250@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  3 siblings, 1 reply; 196+ messages in thread

From: Peter Smith @ 2026-07-06 23:01 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

Hi Nisha.

Bug: The current patch is allowing conflicting exclusion lists...

======

Background:

It's always been possible for CREATE PUBLICATION to specify the same
schema or same table multiple times.

test_pub=# CREATE SCHEMA MYSCHEMA;
CREATE SCHEMA
test_pub=# CREATE TABLE T1(A INT);
CREATE TABLE
test_pub=# CREATE TABLE MYSCHEMA.T2(A INT);
CREATE TABLE
test_pub=# CREATE TABLE MYSCHEMA.T3(A INT);
CREATE TABLE

// same table multiple times is OK
test_pub=# CREATE PUBLICATION PUB3 FOR TABLE T1,T1,T1,T1;
CREATE PUBLICATION

// same schema multiple times is OK
test_pub=# CREATE PUBLICATION PUB1 FOR TABLES IN SCHEMA MYSCHEMA,
MYSCHEMA, MYSCHEMA;
CREATE PUBLICATION

~~~

But, this behaviour is only allowed if there are no specification
conflicts. e.g. You can't have multiple tables with column lists:

test_pub=# CREATE PUBLICATION PUB4 FOR TABLE T1,T1(A),T1,T1;
ERROR:  conflicting or redundant column lists for table "t1"

======

Bug:

IMO similar restrictions and a similar error message needs to happen
for clashing schema exclusions. Specifying the same schema multiple
times is fine, but it must be disallowed if there are conflicting
exclusion lists.

For example, the command below currently works, but it should not:

test_pub=# CREATE PUBLICATION PUB2 FOR TABLES IN SCHEMA MYSCHEMA
EXCEPT (TABLE T2), MYSCHEMA EXCEPT (TABLE T3), MYSCHEMA;
CREATE PUBLICATION

test_pub=# \dRp+ PUB2
                                                       Publication pub2
  Owner   | All tables | All sequences | Inserts | Updates | Deletes |
Truncates | Generated columns | Via root | Descri
ption
----------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+-------
------
 postgres | f          | f             | t       | t       | t       |
t         | none              | f        |
Tables from schemas:
    "myschema"
Except tables:
    "myschema.t2"
    "myschema.t3"

======
Kind Regards,
Peter Smith.
Fujitsu Australia





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-07 03:09  shveta malik <shveta.malik@gmail.com>
  parent: Peter Smith <smithpb2250@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: shveta malik @ 2026-07-07 03:09 UTC (permalink / raw)
  To: Peter Smith <smithpb2250@gmail.com>; +Cc: Nisha Moond <nisha.moond412@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; shveta malik <shveta.malik@gmail.com>

On Tue, Jul 7, 2026 at 4:31 AM Peter Smith <smithpb2250@gmail.com> wrote:
>
> Hi Nisha.
>
> Bug: The current patch is allowing conflicting exclusion lists...
>
> ======
>
> Background:
>
> It's always been possible for CREATE PUBLICATION to specify the same
> schema or same table multiple times.
>
> test_pub=# CREATE SCHEMA MYSCHEMA;
> CREATE SCHEMA
> test_pub=# CREATE TABLE T1(A INT);
> CREATE TABLE
> test_pub=# CREATE TABLE MYSCHEMA.T2(A INT);
> CREATE TABLE
> test_pub=# CREATE TABLE MYSCHEMA.T3(A INT);
> CREATE TABLE
>
> // same table multiple times is OK
> test_pub=# CREATE PUBLICATION PUB3 FOR TABLE T1,T1,T1,T1;
> CREATE PUBLICATION
>
> // same schema multiple times is OK
> test_pub=# CREATE PUBLICATION PUB1 FOR TABLES IN SCHEMA MYSCHEMA,
> MYSCHEMA, MYSCHEMA;
> CREATE PUBLICATION
>
> ~~~
>
> But, this behaviour is only allowed if there are no specification
> conflicts. e.g. You can't have multiple tables with column lists:
>
> test_pub=# CREATE PUBLICATION PUB4 FOR TABLE T1,T1(A),T1,T1;
> ERROR:  conflicting or redundant column lists for table "t1"
>
> ======
>
> Bug:
>
> IMO similar restrictions and a similar error message needs to happen
> for clashing schema exclusions. Specifying the same schema multiple
> times is fine, but it must be disallowed if there are conflicting
> exclusion lists.
>

+1. Good Catch.

> For example, the command below currently works, but it should not:
>
> test_pub=# CREATE PUBLICATION PUB2 FOR TABLES IN SCHEMA MYSCHEMA
> EXCEPT (TABLE T2), MYSCHEMA EXCEPT (TABLE T3), MYSCHEMA;
> CREATE PUBLICATION
>
> test_pub=# \dRp+ PUB2
>                                                        Publication pub2
>   Owner   | All tables | All sequences | Inserts | Updates | Deletes |
> Truncates | Generated columns | Via root | Descri
> ption
> ----------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+-------
> ------
>  postgres | f          | f             | t       | t       | t       |
> t         | none              | f        |
> Tables from schemas:
>     "myschema"
> Except tables:
>     "myschema.t2"
>     "myschema.t3"
>
> ======
> Kind Regards,
> Peter Smith.
> Fujitsu Australia
>
>





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-07 09:01  shveta malik <shveta.malik@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  3 siblings, 1 reply; 196+ messages in thread

From: shveta malik @ 2026-07-07 09:01 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; shveta malik <shveta.malik@gmail.com>

On Fri, Jul 3, 2026 at 10:15 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
>
>
> postgres=# alter publication pub2 add table t_part_p1;
> ERROR:  cannot add table "public.t_part_p1" to publication "pub2"
> DETAIL:  Partition ancestor "public.t_part" of table
> "public.t_part_p1" is currently listed in the EXCEPT clause of the
> publication.
> HINT:  Change EXCEPT list using ALTER PUBLICATION ... SET TABLES IN
> SCHEMA ... EXCEPT.
> ~~~

Thanks. Do you think we should restrict this case too? To me, this
seems like another variation of the above where conflicting entries
are given at the time of sub-creation itself. The root is excluded but
parittion is included .

postgres=# create publication pub1 for table s2.tab_part_1, tables in
schema s2 except (table tab_root);
CREATE PUBLICATION
postgres=# \dRp+
                                                      Publication pub1
 Owner  | All tables | All sequences | Inserts | Updates | Deletes |
Truncates | Generated columns | Via root | Description
--------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+-------------
 shveta | f          | f             | t       | t       | t       | t
        | none              | f        |
Tables:
    "s2.tab_part_1"
Tables from schemas:
    "s2"
Except tables:
    "s2.tab_root"

thanks
Shveta





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-07 10:43  shveta malik <shveta.malik@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: shveta malik @ 2026-07-07 10:43 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; shveta malik <shvetamalik@gmail.com>

On Tue, Jul 7, 2026 at 2:31 PM shveta malik <shveta.malik@gmail.com> wrote:
>
> On Fri, Jul 3, 2026 at 10:15 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
> >
> >
> > postgres=# alter publication pub2 add table t_part_p1;
> > ERROR:  cannot add table "public.t_part_p1" to publication "pub2"
> > DETAIL:  Partition ancestor "public.t_part" of table
> > "public.t_part_p1" is currently listed in the EXCEPT clause of the
> > publication.
> > HINT:  Change EXCEPT list using ALTER PUBLICATION ... SET TABLES IN
> > SCHEMA ... EXCEPT.
> > ~~~
>
> Thanks. Do you think we should restrict this case too? To me, this
> seems like another variation of the above where conflicting entries
> are given at the time of sub-creation itself. The root is excluded but
> parittion is included .
>
> postgres=# create publication pub1 for table s2.tab_part_1, tables in
> schema s2 except (table tab_root);
> CREATE PUBLICATION
> postgres=# \dRp+
>                                                       Publication pub1
>  Owner  | All tables | All sequences | Inserts | Updates | Deletes |
> Truncates | Generated columns | Via root | Description
> --------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+-------------
>  shveta | f          | f             | t       | t       | t       | t
>         | none              | f        |
> Tables:
>     "s2.tab_part_1"
> Tables from schemas:
>     "s2"
> Except tables:
>     "s2.tab_root"
>

Since alter is blocked for above case while create-sub is not, I had a
look at the new check added in check_publication_add_relation

a) The check introduced in this function for partitions/ancestors is
sufficient for cases where an except-list is already present, but not
for cases where we are in the process of adding one. Thus the
create-sub scenario above is not covered by this.

b) Also the new check in check_publication_add_relation() gets and
traverses complete list of ancestors

+ List    *ancestors = get_partition_ancestors(relid);
+
+ foreach_oid(ancestor, ancestors)

Isn't getting root (llast_oid(ancestors)) and checking that alone in
EXCEPT list will suffice? Or am I missing something?

thanks
Shveta





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-08 06:28  Amit Kapila <amit.kapila16@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  0 siblings, 2 replies; 196+ messages in thread

From: Amit Kapila @ 2026-07-08 06:28 UTC (permalink / raw)
  To: shveta malik <shveta.malik@gmail.com>; +Cc: Nisha Moond <nisha.moond412@gmail.com>; Peter Smith <smithpb2250@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; shveta malik <shvetamalik@gmail.com>

On Tue, Jul 7, 2026 at 4:13 PM shveta malik <shveta.malik@gmail.com> wrote:
>
> On Tue, Jul 7, 2026 at 2:31 PM shveta malik <shveta.malik@gmail.com> wrote:
> >
> > On Fri, Jul 3, 2026 at 10:15 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
> > >
> > >
> > > postgres=# alter publication pub2 add table t_part_p1;
> > > ERROR:  cannot add table "public.t_part_p1" to publication "pub2"
> > > DETAIL:  Partition ancestor "public.t_part" of table
> > > "public.t_part_p1" is currently listed in the EXCEPT clause of the
> > > publication.
> > > HINT:  Change EXCEPT list using ALTER PUBLICATION ... SET TABLES IN
> > > SCHEMA ... EXCEPT.
> > > ~~~
> >
> > Thanks. Do you think we should restrict this case too? To me, this
> > seems like another variation of the above where conflicting entries
> > are given at the time of sub-creation itself. The root is excluded but
> > parittion is included .
> >
> > postgres=# create publication pub1 for table s2.tab_part_1, tables in
> > schema s2 except (table tab_root);
> > CREATE PUBLICATION
> > postgres=# \dRp+
> >                                                       Publication pub1
> >  Owner  | All tables | All sequences | Inserts | Updates | Deletes |
> > Truncates | Generated columns | Via root | Description
> > --------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+-------------
> >  shveta | f          | f             | t       | t       | t       | t
> >         | none              | f        |
> > Tables:
> >     "s2.tab_part_1"
> > Tables from schemas:
> >     "s2"
> > Except tables:
> >     "s2.tab_root"
> >
>
> Since alter is blocked for above case while create-sub is not,
>

If a combination is not supported in ALTER, we should disallow the
same in CREATE as well. So, +1 to restrict the case you reported.

> I had a
> look at the new check added in check_publication_add_relation
>
> a) The check introduced in this function for partitions/ancestors is
> sufficient for cases where an except-list is already present, but not
> for cases where we are in the process of adding one. Thus the
> create-sub scenario above is not covered by this.
>
> b) Also the new check in check_publication_add_relation() gets and
> traverses complete list of ancestors
>
> + List    *ancestors = get_partition_ancestors(relid);
> +
> + foreach_oid(ancestor, ancestors)
>
> Isn't getting root (llast_oid(ancestors)) and checking that alone in
> EXCEPT list will suffice? Or am I missing something?
>

I think this should be possible because we allow only root tables in
the EXCEPT list. If so, and we are planning to change as per your
suggestion then we should add a comment as to why checking only last
is okay here.

-- 
With Regards,
Amit Kapila.





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-08 08:52  shveta malik <shveta.malik@gmail.com>
  parent: Amit Kapila <amit.kapila16@gmail.com>
  1 sibling, 1 reply; 196+ messages in thread

From: shveta malik @ 2026-07-08 08:52 UTC (permalink / raw)
  To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: Nisha Moond <nisha.moond412@gmail.com>; Peter Smith <smithpb2250@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; shveta malik <shveta.malik@gmail.com>

Nisha, the patch (testing wise) is okay, but some code-optimization
might help. I am stuck on reveiw of GetTopMostAncestorInPublication()
and all its callers.

1)
caller 1: pub_rf_contains_invalid_column():

It is not understood why pub_rf_contains_invalid_column() does not
pass 'exceptPubids' to GetTopMostAncestorInPublication(). Perhaps a
comment will help. IIUC, a parittion (for which we are trying to
verify row-filter expression) can not co-exist in a subscription where
its ROOT is already excluded. This assumption will be true once you
address the issue of CREATE SUB (in [1]) sent in my previous email.
After that, this will still need a comment.

2)
Both caller 2 (get_rel_sync_entry) and caller 3
(is_table_publishable_in_publication) are trying to see if partition
should be considered as included in publication and thus are trying to
see if ROOT is excluded. But the implementation is very different.

The get_rel_sync_entry() does that by passing except_pubids to
GetTopMostAncestorInPublication(). This except_pubids was computed for
topmost ROOT of the parition in the caller and then it skips checking
pg_pub_namepspace if given pubid is part of except_pubids arguement.

While is_table_publishable_in_publication() does that by selecting
topmost ancestor incuded in a given pubid using
GetTopMostAncestorInPublication(), without consulting/computing
except_pubids. And then later checks if the ancestor returned by
GetTopMostAncestorInPublication() is in pg_publicaiton_rel with
'prexcept' true.

IMO, GetTopMostAncestorInPublication() should itself be inclusive of
logic where it filters out the table (does not return it as result) if
ROOT is excluded. And even we should not be passing an argument for
that (this is my initial thought). By making such a logic, we need not
to bother about all
the callers to see if caller has correct logic to deal with output of
GetTopMostAncestorInPublication(). Can you think on this line and
check the feasibility.

3)
I have yet to reveiw pub_contains_invalid_column, but I have a initial
understanding, that it will be similar to the case of
pub_rf_contains_invalid_column. Please verify on your end.

[1]: https://www.postgresql.org/message-id/CAJpy0uAuL7SqowL7T6HCELuVUr5ubwoGsjV1SQQRCXGme5L%3DpA%40mail.g...

thanks
Shveta





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-08 09:28  shveta malik <shveta.malik@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: shveta malik @ 2026-07-08 09:28 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; Amit Kapila <amit.kapila16@gmail.com>; shveta malik <shveta.malik@gmail.com>

On Wed, Jul 8, 2026 at 2:22 PM shveta malik <shveta.malik@gmail.com> wrote:
>
> Nisha, the patch (testing wise) is okay, but some code-optimization
> might help. I am stuck on reveiw of GetTopMostAncestorInPublication()
> and all its callers.
>
> 1)
> caller 1: pub_rf_contains_invalid_column():
>
> It is not understood why pub_rf_contains_invalid_column() does not
> pass 'exceptPubids' to GetTopMostAncestorInPublication(). Perhaps a
> comment will help. IIUC, a parittion (for which we are trying to
> verify row-filter expression) can not co-exist in a subscription where
> its ROOT is already excluded. This assumption will be true once you
> address the issue of CREATE SUB (in [1]) sent in my previous email.
> After that, this will still need a comment.
>
> 2)
> Both caller 2 (get_rel_sync_entry) and caller 3
> (is_table_publishable_in_publication) are trying to see if partition
> should be considered as included in publication and thus are trying to
> see if ROOT is excluded. But the implementation is very different.
>
> The get_rel_sync_entry() does that by passing except_pubids to
> GetTopMostAncestorInPublication(). This except_pubids was computed for
> topmost ROOT of the parition in the caller and then it skips checking
> pg_pub_namepspace if given pubid is part of except_pubids arguement.
>
> While is_table_publishable_in_publication() does that by selecting
> topmost ancestor incuded in a given pubid using
> GetTopMostAncestorInPublication(), without consulting/computing
> except_pubids. And then later checks if the ancestor returned by
> GetTopMostAncestorInPublication() is in pg_publicaiton_rel with
> 'prexcept' true.
>
> IMO, GetTopMostAncestorInPublication() should itself be inclusive of
> logic where it filters out the table (does not return it as result) if
> ROOT is excluded. And even we should not be passing an argument for
> that (this is my initial thought). By making such a logic, we need not
> to bother about all
> the callers to see if caller has correct logic to deal with output of
> GetTopMostAncestorInPublication(). Can you think on this line and
> check the feasibility.
>

I thought more on this. Do you think we can do this?

GetTopMostAncestorInPublication() is already accepting a list of
ancestors in a ordered fashion, root at the end. We get root from this
ancestor list, check if root is in pg_publication_rel with
except=true. If so, we skip the rest of the logic and return
InvalidOid from GetTopMostAncestorInPublication().

The 'except_pubids' argument is not required. Callers need not to have
special logic to send this arguement or to have extra-processing on
output as done by is_table_publishable_in_publication() currently.
Let me know if I have missed anything.

thanks
Shveta





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-08 15:20  Nisha Moond <nisha.moond412@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: Nisha Moond @ 2026-07-08 15:20 UTC (permalink / raw)
  To: shveta malik <shveta.malik@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Tue, Jul 7, 2026 at 8:40 AM shveta malik <shveta.malik@gmail.com> wrote:
>
> On Tue, Jul 7, 2026 at 4:31 AM Peter Smith <smithpb2250@gmail.com> wrote:
> >
> > Hi Nisha.
> >
> > Bug: The current patch is allowing conflicting exclusion lists...
> >
> > ======
> >
> > Background:
> >
> > It's always been possible for CREATE PUBLICATION to specify the same
> > schema or same table multiple times.
> >
> > test_pub=# CREATE SCHEMA MYSCHEMA;
> > CREATE SCHEMA
> > test_pub=# CREATE TABLE T1(A INT);
> > CREATE TABLE
> > test_pub=# CREATE TABLE MYSCHEMA.T2(A INT);
> > CREATE TABLE
> > test_pub=# CREATE TABLE MYSCHEMA.T3(A INT);
> > CREATE TABLE
> >
> > // same table multiple times is OK
> > test_pub=# CREATE PUBLICATION PUB3 FOR TABLE T1,T1,T1,T1;
> > CREATE PUBLICATION
> >
> > // same schema multiple times is OK
> > test_pub=# CREATE PUBLICATION PUB1 FOR TABLES IN SCHEMA MYSCHEMA,
> > MYSCHEMA, MYSCHEMA;
> > CREATE PUBLICATION
> >
> > ~~~
> >
> > But, this behaviour is only allowed if there are no specification
> > conflicts. e.g. You can't have multiple tables with column lists:
> >
> > test_pub=# CREATE PUBLICATION PUB4 FOR TABLE T1,T1(A),T1,T1;
> > ERROR:  conflicting or redundant column lists for table "t1"
> >
> > ======
> >
> > Bug:
> >
> > IMO similar restrictions and a similar error message needs to happen
> > for clashing schema exclusions. Specifying the same schema multiple
> > times is fine, but it must be disallowed if there are conflicting
> > exclusion lists.
> >
>
> +1. Good Catch.
>

Thanks for the bug report. I've fixed it and attached the fix as a
separate top-up patch, v19-0002.

Until v18, schema qualification checks for EXCEPT tables were split
between two places:

1) TABLES IN SCHEMA <schema-name> (EXCEPT TABLE <table-name>);
 -- the schema qualification check was performed in gram.y, since all
required information was available during parsing.

2) TABLES IN SCHEMA CURRENT_SCHEMA (EXCEPT TABLE <table-name>);
 -- CURRENT_SCHEMA is resolved only at execution time, so the schema
qualification and eligibility checks were performed there.

The reported bug also affects cases such as:
CREATE PUBLICATION PUB2 FOR TABLES IN SCHEMA MYSCHEMA EXCEPT (TABLE
T2), CURRENT_SCHEMA EXCEPT (TABLE T3);
 -- where CURRENT_SCHEMA = myschema. Correct handling of this case
requires the checks to be performed after schema resolution, i.e., at
execution time. To reduce duplicate code, I moved the schema
qualification and eligibility checks for both cases to execution time
and removed the corresponding processing from gram.y.

Since this changes a fair amount of code, I've kept it as a separate
patch (v19-0002) to make review easier. Depending on the feedback, we
can optimize the implementation or move parts of it back into gram.y
before merging it into patch 0001.
~~~

Attached is the v19 patch set.
 -- Also Addressed all comments from Peter at [1] and Shveta at [2].
 -- The code optimization suggestions from Shveta at [3] are still
pending. I'm evaluating them and plan to address them in the next
version.
~~~

[1] https://www.postgresql.org/message-id/CAHut%2BPt-%2B6Q4-kmhqCZ2_FpaNRR%3DhaJk-GK1eEyTXcTTDnRnXA%40ma...
[2] https://www.postgresql.org/message-id/CAJpy0uAuL7SqowL7T6HCELuVUr5ubwoGsjV1SQQRCXGme5L%3DpA%40mail.g...
[3] https://www.postgresql.org/message-id/CAJpy0uA_d-K-f94d-9Xw66Fqv7gdSGBYGzi9YcybtuEkYdQocQ%40mail.gma...

--
Thanks,
Nisha

Attachments: download all (5 files, .tar.gz)

v19-0001-Support-EXCEPT-clause-for-schema-level-publicati.patch (application/octet-stream, 72.8K) download From 2f1beeb9ac3bc88bb50e498b289f8e4ef32be461 Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Tue, 16 Jun 2026 10:58:49 +0530 Subject: [PATCH v19 1/5] Support EXCEPT clause for schema-level publications Extend table exclusion support in publications to allow specific tables to be excluded from schema-level publications using an EXCEPT clause in CREATE PUBLICATION. Supported syntax: CREATE PUBLICATION <pub> FOR TABLES IN SCHEMA s EXCEPT (TABLE t1,...); --- src/backend/catalog/pg_publication.c | 258 ++++++++++++++++---- src/backend/commands/publicationcmds.c | 189 +++++++++++++- src/backend/commands/tablecmds.c | 11 + src/backend/parser/gram.y | 54 +++- src/backend/replication/pgoutput/pgoutput.c | 39 ++- src/backend/utils/cache/relcache.c | 41 ++-- src/bin/psql/describe.c | 18 ++ src/bin/psql/tab-complete.in.c | 35 ++- src/include/catalog/pg_publication.h | 3 +- src/include/commands/publicationcmds.h | 2 + src/include/nodes/parsenodes.h | 2 + src/test/regress/expected/publication.out | 195 ++++++++++++++- src/test/regress/sql/publication.sql | 120 ++++++++- src/test/subscription/t/037_except.pl | 133 +++++++++- 14 files changed, 1006 insertions(+), 94 deletions(-) diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index 1ec94c851b2..21857296f49 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -53,9 +53,10 @@ typedef struct * error if not. */ static void -check_publication_add_relation(PublicationRelInfo *pri) +check_publication_add_relation(PublicationRelInfo *pri, Oid pubid) { Relation targetrel = pri->relation; + Oid relid = RelationGetRelid(targetrel); const char *relname; const char *errormsg; @@ -70,12 +71,57 @@ check_publication_add_relation(PublicationRelInfo *pri) errormsg = gettext_noop("cannot add relation \"%s\" to publication"); } - /* If in EXCEPT clause, must be root partitioned table */ - if (pri->except && targetrel->rd_rel->relispartition) - ereport(ERROR, - (errcode(ERRCODE_INVALID_PARAMETER_VALUE), - errmsg(errormsg, relname), - errdetail("This operation is not supported for individual partitions."))); + if (targetrel->rd_rel->relispartition) + { + if (pri->except) + { + /* If in EXCEPT clause, must be root partitioned table */ + ereport(ERROR, + (errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg(errormsg, relname), + errdetail("This operation is not supported for individual partitions."))); + } + else + { + /* + * If not in EXCEPT clause, a partition cannot be independently + * included when its partition root is in this publication's + * EXCEPT list. Doing so would leave the catalog inconsistent + * (root excluded, partition explicitly included) and the + * ancestor-cascade rule would silently override the include at + * replication time. + * + * Only the root of a partition hierarchy can ever appear in an + * EXCEPT clause (a partition itself is rejected just above), so + * checking any intermediate ancestor cannot find a match; the + * root is the only one worth a catalog lookup. + */ + Oid root = llast_oid(get_partition_ancestors(relid)); + HeapTuple atup; + + atup = SearchSysCache2(PUBLICATIONRELMAP, + ObjectIdGetDatum(root), + ObjectIdGetDatum(pubid)); + if (HeapTupleIsValid(atup)) + { + bool root_except = ((Form_pg_publication_rel) GETSTRUCT(atup))->prexcept; + + ReleaseSysCache(atup); + + if (root_except) + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("cannot add partition \"%s\" to publication \"%s\"", + RelationGetQualifiedRelationName(targetrel), + get_publication_name(pubid, false)), + errdetail("Ancestor \"%s\" of partition \"%s\" is currently listed in the EXCEPT clause of the publication.", + quote_qualified_identifier(get_namespace_name(get_rel_namespace(root)), + get_rel_name(root)), + RelationGetQualifiedRelationName(targetrel)), + errhint("Change EXCEPT list using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT."))); + } + } + } /* Must be a regular or partitioned table */ if (RelationGetForm(targetrel)->relkind != RELKIND_RELATION && @@ -340,19 +386,20 @@ is_table_publication(Oid pubid) scan = systable_beginscan(pubrelsrel, PublicationRelPrpubidIndexId, true, NULL, 1, &scankey); - tup = systable_getnext(scan); - if (HeapTupleIsValid(tup)) - { - Form_pg_publication_rel pubrel; - pubrel = (Form_pg_publication_rel) GETSTRUCT(tup); - - /* - * For any publication, pg_publication_rel contains either only EXCEPT - * entries or only explicitly included tables. Therefore, examining - * the first tuple is sufficient to determine table inclusion. - */ - result = !pubrel->prexcept; + /* + * A publication can hold both explicit-include (prexcept=false) + * and EXCEPT (prexcept=true) rows for the same pubid. Scan until + * we find an explicit-include row, rather than relying on the first row's + * prexcept value. + */ + while (HeapTupleIsValid(tup = systable_getnext(scan))) + { + if (!((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept) + { + result = true; + break; + } } systable_endscan(scan); @@ -454,14 +501,27 @@ GetPubPartitionOptionRelations(List *result, PublicationPartOpt pub_partopt, * * Note that the list of ancestors should be ordered such that the topmost * ancestor is at the end of the list. + * + * except_pubids is a list of publication OIDs whose schema membership + * should be ignored for the ancestor (because the ancestor is in their + * EXCEPT clause). */ Oid -GetTopMostAncestorInPublication(Oid puboid, List *ancestors, int *ancestor_level) +GetTopMostAncestorInPublication(Oid puboid, List *ancestors, + int *ancestor_level, List *except_pubids) { ListCell *lc; Oid topmost_relid = InvalidOid; int level = 0; + /* + * except_pubids is computed once from the partition root and reused + * across the ancestor walk. Re-fetching exclusion information for each + * ancestor is unnecessary because only the root can have prexcept=true; + * partitions themselves cannot be added to EXCEPT. + */ + bool check_schemas = !list_member_oid(except_pubids, puboid); + /* * Find the "topmost" ancestor that is in this publication. */ @@ -480,7 +540,7 @@ GetTopMostAncestorInPublication(Oid puboid, List *ancestors, int *ancestor_level if (ancestor_level) *ancestor_level = level; } - else + else if (check_schemas) { aschemaPubids = GetSchemaPublications(get_rel_namespace(ancestor)); if (list_member_oid(aschemaPubids, puboid)) @@ -555,21 +615,35 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, * duplicates, it's here just to provide nicer error message in common * case. The real protection is the unique key on the catalog. */ - if (SearchSysCacheExists2(PUBLICATIONRELMAP, ObjectIdGetDatum(relid), - ObjectIdGetDatum(pubid))) + tup = SearchSysCache2(PUBLICATIONRELMAP, ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + + if (HeapTupleIsValid(tup)) { + bool is_except = ((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept; + + ReleaseSysCache(tup); table_close(rel, RowExclusiveLock); if (if_not_exists) return InvalidObjectAddress; - ereport(ERROR, - (errcode(ERRCODE_DUPLICATE_OBJECT), - errmsg("relation \"%s\" is already member of publication \"%s\"", - RelationGetRelationName(targetrel), pub->name))); + if (is_except) + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("cannot add table \"%s\" to publication \"%s\"", + RelationGetQualifiedRelationName(targetrel), + pub->name), + errdetail("The table is currently listed in the EXCEPT clause of the publication."), + errhint("Change EXCEPT list using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT."))); + else + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("relation \"%s\" is already member of publication \"%s\"", + RelationGetRelationName(targetrel), pub->name))); } - check_publication_add_relation(pri); + check_publication_add_relation(pri, pubid); /* Validate and translate column names into a Bitmapset of attnums. */ attnums = pub_collist_validate(pri->relation, pri->columns); @@ -992,12 +1066,13 @@ GetIncludedPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) * Gets list of table oids that were specified in the EXCEPT clause for a * publication. * - * This should only be used FOR ALL TABLES publications. + * This is used for FOR ALL TABLES and FOR TABLES IN SCHEMA publications, + * both of which support EXCEPT TABLE. */ List * GetExcludedPublicationTables(Oid pubid, PublicationPartOpt pub_partopt) { - Assert(GetPublication(pubid)->alltables); + Assert(GetPublication(pubid)->alltables || is_schema_publication(pubid)); return get_publication_relations(pubid, pub_partopt, true); } @@ -1059,15 +1134,15 @@ GetAllPublicationRelations(Oid pubid, char relkind, bool pubviaroot) TableScanDesc scan; HeapTuple tuple; List *result = NIL; - List *exceptlist = NIL; + List *except_relids = NIL; Assert(!(relkind == RELKIND_SEQUENCE && pubviaroot)); /* EXCEPT filtering applies only to relations, not sequences */ if (relkind == RELKIND_RELATION) - exceptlist = GetExcludedPublicationTables(pubid, pubviaroot ? - PUBLICATION_PART_ROOT : - PUBLICATION_PART_LEAF); + except_relids = GetExcludedPublicationTables(pubid, pubviaroot ? + PUBLICATION_PART_ROOT : + PUBLICATION_PART_LEAF); classRel = table_open(RelationRelationId, AccessShareLock); @@ -1085,7 +1160,7 @@ GetAllPublicationRelations(Oid pubid, char relkind, bool pubviaroot) if (is_publishable_class(relid, relForm) && !(relForm->relispartition && pubviaroot) && - !list_member_oid(exceptlist, relid)) + !list_member_oid(except_relids, relid)) result = lappend_oid(result, relid); } @@ -1107,7 +1182,7 @@ GetAllPublicationRelations(Oid pubid, char relkind, bool pubviaroot) if (is_publishable_class(relid, relForm) && !relForm->relispartition && - !list_member_oid(exceptlist, relid)) + !list_member_oid(except_relids, relid)) result = lappend_oid(result, relid); } @@ -1242,22 +1317,68 @@ GetSchemaPublicationRelations(Oid schemaid, PublicationPartOpt pub_partopt) /* * Gets the list of all relations published by FOR TABLES IN SCHEMA - * publication. + * publication, excluding any tables listed in the EXCEPT clause. */ List * GetAllSchemaPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) { List *result = NIL; List *pubschemalist = GetPublicationSchemas(pubid); + List *except_relids = NIL; ListCell *cell; + /* get the list of tables excluded via EXCEPT TABLE for this publication */ + if (pubschemalist != NIL) + except_relids = GetExcludedPublicationTables(pubid, pub_partopt); + foreach(cell, pubschemalist) { Oid schemaid = lfirst_oid(cell); List *schemaRels = NIL; schemaRels = GetSchemaPublicationRelations(schemaid, pub_partopt); - result = list_concat(result, schemaRels); + + if (except_relids != NIL) + { + /* filter out any tables that appear in the EXCEPT list */ + ListCell *rlc; + + foreach(rlc, schemaRels) + { + Oid relid = lfirst_oid(rlc); + bool excluded = list_member_oid(except_relids, relid); + + /* + * A partition whose ancestor is in the publication's EXCEPT + * list is also excluded, even if the partition itself lives + * in a different (included) schema. Individual partitions + * cannot appear in EXCEPT, so cascading from the root is the + * only way to exclude a partition; this matches the ALL + * TABLES EXCEPT (TABLE root) behavior. + */ + if (!excluded && get_rel_relispartition(relid)) + { + List *ancestors = get_partition_ancestors(relid); + ListCell *alc; + + foreach(alc, ancestors) + { + if (list_member_oid(except_relids, lfirst_oid(alc))) + { + excluded = true; + break; + } + } + list_free(ancestors); + } + + if (!excluded) + result = lappend_oid(result, relid); + } + list_free(schemaRels); + } + else + result = list_concat(result, schemaRels); } return result; @@ -1334,6 +1455,7 @@ is_table_publishable_in_publication(Oid relid, Publication *pub) { bool relispartition; List *ancestors = NIL; + HeapTuple tup; /* * For non-pubviaroot publications, a partitioned table is never the @@ -1390,20 +1512,62 @@ is_table_publishable_in_publication(Oid relid, Publication *pub) * If it's false, the partition is covered by its ancestor's presence in * the publication, it should be included (return true). */ - if (relispartition && - OidIsValid(GetTopMostAncestorInPublication(pub->oid, ancestors, NULL))) - return !pub->pubviaroot; + if (relispartition) + { + Oid ancestor_oid; + + ancestor_oid = GetTopMostAncestorInPublication(pub->oid, ancestors, NULL, NIL); + if (OidIsValid(ancestor_oid)) + { + /* + * The ancestor was found in the publication (via explicit + * membership or schema membership), but it may be excluded. Check + * for a prexcept row before concluding the partition is + * published. + */ + tup = SearchSysCache2(PUBLICATIONRELMAP, + ObjectIdGetDatum(ancestor_oid), + ObjectIdGetDatum(pub->oid)); + if (HeapTupleIsValid(tup)) + { + bool is_except; + + is_except = ((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept; + ReleaseSysCache(tup); + if (is_except) + return false; + } + return !pub->pubviaroot; + } + } /* * Check whether the table is explicitly published via pg_publication_rel * or pg_publication_namespace. + * + * A pg_publication_rel row with prexcept=true means the table is + * explicitly excluded via EXCEPT and must not be reported as published, + * even if its schema is otherwise included. A row with prexcept=false + * means it is explicitly included. If no pg_publication_rel row exists, + * the table is published iff its schema appears in + * pg_publication_namespace. */ - return (SearchSysCacheExists2(PUBLICATIONRELMAP, - ObjectIdGetDatum(relid), - ObjectIdGetDatum(pub->oid)) || - SearchSysCacheExists2(PUBLICATIONNAMESPACEMAP, - ObjectIdGetDatum(get_rel_namespace(relid)), - ObjectIdGetDatum(pub->oid))); + + tup = SearchSysCache2(PUBLICATIONRELMAP, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pub->oid)); + if (HeapTupleIsValid(tup)) + { + bool is_except; + + is_except = ((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept; + ReleaseSysCache(tup); + return !is_except; + } + + return SearchSysCacheExists2(PUBLICATIONNAMESPACEMAP, + ObjectIdGetDatum(get_rel_namespace(relid)), + ObjectIdGetDatum(pub->oid)); } /* diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 440adb356ad..226ddafda93 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -22,6 +22,7 @@ #include "catalog/namespace.h" #include "catalog/objectaccess.h" #include "catalog/objectaddress.h" +#include "catalog/partition.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" #include "catalog/pg_namespace.h" @@ -71,6 +72,7 @@ static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); static char defGetGeneratedColsOption(DefElem *def); +static void CheckExceptNotInTableList(List *except_rels, List *explicitrelids); static void @@ -181,7 +183,7 @@ parse_publication_options(ParseState *pstate, */ static void ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, - List **rels, List **exceptrels, List **schemas) + List **rels, List **except_pubtables, List **schemas) { ListCell *cell; PublicationObjSpec *pubobj; @@ -200,7 +202,7 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, { case PUBLICATIONOBJ_EXCEPT_TABLE: pubobj->pubtable->except = true; - *exceptrels = lappend(*exceptrels, pubobj->pubtable); + *except_pubtables = lappend(*except_pubtables, pubobj->pubtable); break; case PUBLICATIONOBJ_TABLE: pubobj->pubtable->except = false; @@ -224,6 +226,38 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, /* Filter out duplicates if user specifies "sch1, sch1" */ *schemas = list_append_unique_oid(*schemas, schemaid); + + /* + * Qualify unqualified EXCEPT table names with the resolved + * current schema and reject any explicitly cross-schema + * entries. This mirrors the parse-time handling done for + * TABLES_IN_SCHEMA in preprocess_pubobj_list(), deferred here + * because CURRENT_SCHEMA is not known until execution time. + */ + if (pubobj->except_tables != NIL) + { + char *cur_schema_name = get_namespace_name(schemaid); + + foreach_ptr(PublicationObjSpec, eobj, pubobj->except_tables) + { + const char *eobj_schemaname = + eobj->pubtable->relation->schemaname; + const char *eobj_relname = + eobj->pubtable->relation->relname; + + if (eobj_schemaname == NULL) + eobj->pubtable->relation->schemaname = cur_schema_name; + else if (strcmp(eobj_schemaname, cur_schema_name) != 0) + ereport(ERROR, + errcode(ERRCODE_INVALID_OBJECT_DEFINITION), + errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", + quote_qualified_identifier(eobj_schemaname, eobj_relname), + cur_schema_name)); + + *except_pubtables = lappend(*except_pubtables, + eobj->pubtable); + } + } break; default: /* shouldn't happen */ @@ -305,7 +339,7 @@ pub_rf_contains_invalid_column(Oid pubid, Relation relation, List *ancestors, if (pubviaroot && relation->rd_rel->relispartition) { publish_as_relid - = GetTopMostAncestorInPublication(pubid, ancestors, NULL); + = GetTopMostAncestorInPublication(pubid, ancestors, NULL, NIL); if (!OidIsValid(publish_as_relid)) publish_as_relid = relid; @@ -389,7 +423,7 @@ pub_contains_invalid_column(Oid pubid, Relation relation, List *ancestors, */ if (pubviaroot && relation->rd_rel->relispartition) { - publish_as_relid = GetTopMostAncestorInPublication(pubid, ancestors, NULL); + publish_as_relid = GetTopMostAncestorInPublication(pubid, ancestors, NULL, NIL); if (!OidIsValid(publish_as_relid)) publish_as_relid = relid; @@ -770,6 +804,48 @@ TransformPubWhereClauses(List *tables, const char *queryString, } } +/* + * Check that no relation in except_rels is also present in explicitrelids, + * the list of OIDs added to the publication by the explicit TABLE list. A + * table cannot be both explicitly published and excluded in the same DDL. + * + * Also check that no relation in explicitrelids is a partition whose + * partition root is in except_rels; that would leave the catalog + * inconsistent (root excluded, partition explicitly included) with the + * ancestor-cascade rule silently overriding the include at replication + * time. + */ +static void +CheckExceptNotInTableList(List *except_rels, List *explicitrelids) +{ + foreach_oid(explicitrelid, explicitrelids) + { + Oid root = InvalidOid; + + if (get_rel_relispartition(explicitrelid)) + root = llast_oid(get_partition_ancestors(explicitrelid)); + + foreach_ptr(PublicationRelInfo, pri, except_rels) + { + Oid exceptrelid = RelationGetRelid(pri->relation); + + if (exceptrelid == explicitrelid) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" cannot be both published and excluded", + RelationGetQualifiedRelationName(pri->relation))); + + if (OidIsValid(root) && exceptrelid == root) + ereport(ERROR, + (errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("partition \"%s\" cannot be both published and excluded", + quote_qualified_identifier(get_namespace_name(get_rel_namespace(explicitrelid)), + get_rel_name(explicitrelid))), + errdetail("Ancestor \"%s\" is also being excluded by this same command.", + RelationGetQualifiedRelationName(pri->relation)))); + } + } +} /* * Given a list of tables that are going to be added to a publication, @@ -849,7 +925,7 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) char publish_generated_columns; AclResult aclresult; List *relations = NIL; - List *exceptrelations = NIL; + List *except_pubtables = NIL; List *schemaidlist = NIL; /* must have CREATE privilege on database */ @@ -936,16 +1012,16 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) /* Associate objects with the publication. */ ObjectsInPublicationToOids(stmt->pubobjects, pstate, &relations, - &exceptrelations, &schemaidlist); + &except_pubtables, &schemaidlist); if (stmt->for_all_tables) { /* Process EXCEPT table list */ - if (exceptrelations != NIL) + if (except_pubtables != NIL) { List *rels; - rels = OpenTableList(exceptrelations); + rels = OpenTableList(except_pubtables); PublicationAddTables(puboid, rels, true, NULL); CloseTableList(rels); } @@ -959,6 +1035,8 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) } else if (!stmt->for_all_sequences) { + List *explicitrelids = NIL; + /* FOR TABLES IN SCHEMA requires superuser */ if (schemaidlist != NIL && !superuser()) ereport(ERROR, @@ -977,6 +1055,19 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) schemaidlist != NIL, publish_via_partition_root); + /* + * Collect explicit table OIDs now, before we close the relation + * list, so that except-table validation below can check for + * contradictions without relying on a catalog scan that might not + * yet see the just-inserted rows. + */ + if (except_pubtables != NIL) + { + foreach_ptr(PublicationRelInfo, pri, rels) + explicitrelids = lappend_oid(explicitrelids, + RelationGetRelid(pri->relation)); + } + PublicationAddTables(puboid, rels, true, NULL); CloseTableList(rels); } @@ -989,6 +1080,26 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) */ LockSchemaList(schemaidlist); PublicationAddSchemas(puboid, schemaidlist, true, NULL); + + if (except_pubtables != NIL) + { + List *except_rels; + + except_rels = OpenTableList(except_pubtables); + + /* + * Validate that each excluded table is not also in the + * explicit table list (which would be contradictory), and + * that no explicit partition's root is in the except list. + * Use the in-memory explicitrelids collected above rather + * than re-reading the catalog, which may not yet see the + * just-inserted rows. + */ + CheckExceptNotInTableList(except_rels, explicitrelids); + + PublicationAddTables(puboid, except_rels, true, NULL); + CloseTableList(except_rels); + } } } @@ -1683,12 +1794,12 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) else { List *relations = NIL; - List *exceptrelations = NIL; + List *except_pubtables = NIL; List *schemaidlist = NIL; Oid pubid = pubform->oid; ObjectsInPublicationToOids(stmt->pubobjects, pstate, &relations, - &exceptrelations, &schemaidlist); + &except_pubtables, &schemaidlist); CheckAlterPublication(stmt, tup, relations, schemaidlist); @@ -1711,7 +1822,7 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) errmsg("publication \"%s\" does not exist", stmt->pubname)); - relations = list_concat(relations, exceptrelations); + relations = list_concat(relations, except_pubtables); AlterPublicationTables(stmt, tup, relations, pstate->p_sourcetext, schemaidlist != NIL); AlterPublicationSchemas(stmt, tup, schemaidlist); @@ -1829,6 +1940,62 @@ RemovePublicationSchemaById(Oid psoid) table_close(rel, RowExclusiveLock); } +/* + * Remove any EXCEPT clause entries for a relation from schema publications. + * Called when a table changes schema (ALTER TABLE ... SET SCHEMA), so that + * a schema-scoped exclusion does not silently follow the table to its new + * schema. + */ +void +RemoveSchemaPubExceptForRel(Oid relid, Oid oldNspOid, Oid newNspOid) +{ + List *pubids; + + /* + * If the table is not actually moving to a different schema (no-op + * ALTER TABLE ... SET SCHEMA <current_schema>), there is nothing to do. + */ + if (oldNspOid == newNspOid) + return; + + pubids = GetRelationExcludedPublications(relid); + + foreach_oid(pubid, pubids) + { + Oid proid; + + /* + * This problem does not apply to FOR ALL TABLES publications, because + * their EXCEPT clause is publication-scoped, not schema-scoped: the + * exclusion should persist regardless of what schema the table is in. + */ + if (!is_schema_publication(pubid)) + continue; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddress obj; + + ObjectAddressSet(obj, PublicationRelRelationId, proid); + + ereport(DEBUG2, + errmsg_internal("auto-remove exclusion of table \"%s.%s\" from publication \"%s\": table moved to schema \"%s\"", + get_namespace_name(oldNspOid), + get_rel_name(relid), + get_publication_name(pubid, false), + get_namespace_name(newNspOid))); + + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + list_free(pubids); +} + /* * Open relations specified by a PublicationTable list. * The returned tables are locked in ShareUpdateExclusiveLock mode in order to diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 95abaf4890c..a6afb262967 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -63,6 +63,7 @@ #include "commands/event_trigger.h" #include "commands/extension.h" #include "commands/repack.h" +#include "commands/publicationcmds.h" #include "commands/sequence.h" #include "commands/tablecmds.h" #include "commands/tablespace.h" @@ -19569,6 +19570,16 @@ AlterTableNamespaceInternal(Relation rel, Oid oldNspOid, Oid nspOid, AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid, false, objsMoved); + /* + * Remove any EXCEPT clause entries for this relation from schema + * publications. A schema-scoped exclusion is no longer meaningful once + * the table moves to a different schema. + */ + if (rel->rd_rel->relkind == RELKIND_RELATION || + rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE) + RemoveSchemaPubExceptForRel(RelationGetRelid(rel), oldNspOid, + nspOid); + table_close(classRel, RowExclusiveLock); } diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y index ff4e1388c55..6a7a1bc5f8d 100644 --- a/src/backend/parser/gram.y +++ b/src/backend/parser/gram.y @@ -58,6 +58,7 @@ #include "nodes/makefuncs.h" #include "nodes/nodeFuncs.h" #include "parser/parser.h" +#include "utils/builtins.h" #include "utils/datetime.h" #include "utils/xml.h" @@ -11272,7 +11273,7 @@ AlterOwnerStmt: ALTER AGGREGATE aggregate_with_argtypes OWNER TO RoleSpec * pub_obj is one of: * * TABLE table [, ...] - * TABLES IN SCHEMA schema [, ...] + * TABLES IN SCHEMA schema [EXCEPT (TABLE table [, ...] )] [, ...] * *****************************************************************************/ @@ -11332,23 +11333,26 @@ PublicationObjSpec: $$->pubtable->columns = $3; $$->pubtable->whereClause = $4; } - | TABLES IN_P SCHEMA ColId + | TABLES IN_P SCHEMA ColId opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_SCHEMA; $$->name = $4; + $$->except_tables = $5; $$->location = @4; } - | TABLES IN_P SCHEMA CURRENT_SCHEMA + | TABLES IN_P SCHEMA CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_CUR_SCHEMA; + $$->except_tables = $5; $$->location = @4; } - | ColId opt_column_list OptWhereClause + | ColId opt_column_list OptWhereClause opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $4; /* * If either a row filter or column list is specified, create * a PublicationTable object. @@ -11392,10 +11396,11 @@ PublicationObjSpec: $$->pubtable->columns = $2; $$->pubtable->whereClause = $3; } - | CURRENT_SCHEMA + | CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $2; $$->location = @1; } ; @@ -20784,6 +20789,8 @@ preprocess_pub_all_objtype_list(List *all_objects_list, List **pubobjects, /* * Process pubobjspec_list to check for errors in any of the objects and * convert PUBLICATIONOBJ_CONTINUATION into appropriate PublicationObjSpecType. + * Also flattens except_tables from TABLES IN SCHEMA nodes into the list so + * that ObjectsInPublicationToOids() sees them as top-level EXCEPT_TABLE entries. */ static void preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) @@ -20812,6 +20819,13 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLE) { + /* EXCEPT is not valid for table objects */ + if (pubobj->except_tables != NIL) + ereport(ERROR, + errcode(ERRCODE_SYNTAX_ERROR), + errmsg("EXCEPT is not allowed for TABLE publication objects"), + parser_errposition(pubobj->location)); + /* relation name or pubtable must be set for this type of object */ if (!pubobj->name && !pubobj->pubtable) ereport(ERROR, @@ -20860,6 +20874,36 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) errcode(ERRCODE_SYNTAX_ERROR), errmsg("invalid schema name"), parser_errposition(pubobj->location)); + + /* + * For TABLES_IN_SCHEMA, qualify unqualified EXCEPT table names + * with the parent schema and reject cross-schema entries at parse + * time, then flatten into the top-level list. + * + * For TABLES_IN_CUR_SCHEMA the schema name is not yet known, so + * skip both steps here; ObjectsInPublicationToOids() will + * qualify names and validate schema membership at execution time. + */ + if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLES_IN_SCHEMA) + { + foreach_ptr(PublicationObjSpec, eobj, pubobj->except_tables) + { + const char *eobj_schemaname = eobj->pubtable->relation->schemaname; + const char *eobj_relname = eobj->pubtable->relation->relname; + + if (eobj_schemaname == NULL) + eobj->pubtable->relation->schemaname = pubobj->name; + else if (strcmp(eobj_schemaname, pubobj->name) != 0) + ereport(ERROR, + errcode(ERRCODE_INVALID_OBJECT_DEFINITION), + errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", + quote_qualified_identifier(eobj_schemaname, eobj_relname), + pubobj->name), + parser_errposition(eobj->location)); + } + pubobjspec_list = list_concat(pubobjspec_list, pubobj->except_tables); + pubobj->except_tables = NIL; + } } prevobjtype = pubobj->pubobjtype; diff --git a/src/backend/replication/pgoutput/pgoutput.c b/src/backend/replication/pgoutput/pgoutput.c index 4ecfcbff7ab..b0983775a03 100644 --- a/src/backend/replication/pgoutput/pgoutput.c +++ b/src/backend/replication/pgoutput/pgoutput.c @@ -2097,6 +2097,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) * are absorbed while decoding WAL. */ List *schemaPubids = GetSchemaPublications(schemaId); + List *except_pubids; ListCell *lc; Oid publish_as_relid = relid; int publish_ancestor_level = 0; @@ -2104,6 +2105,28 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) char relkind = get_rel_relkind(relid); List *rel_publications = NIL; + /* + * For the schema EXCEPT check, we must look up the top-most ancestor + * rather than the relation itself. check_publication_add_relation() + * prevents individual partitions from appearing in the EXCEPT clause, + * so only a root (non-partition) table can have prexcept = true. + * Using the partition's own OID would always return NIL and miss the + * exclusion. + */ + Oid root_relid; + + if (am_partition) + { + List *ancestors = get_partition_ancestors(relid); + + root_relid = llast_oid(ancestors); + list_free(ancestors); + } + else + root_relid = relid; + + except_pubids = GetRelationExcludedPublications(root_relid); + /* Reload publications if needed before use. */ if (!publications_valid) { @@ -2265,9 +2288,19 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) int level; List *ancestors = get_partition_ancestors(relid); + /* + * Reach here for FOR TABLE, FOR TABLES IN SCHEMA, or + * mixed publications. except_pubids lets + * GetTopMostAncestorInPublication() skip schema-based + * ancestor matches when the partition root is excluded + * via this publication's EXCEPT clause. It has no effect + * for pure FOR TABLE publications, which cannot have + * prexcept rows. + */ ancestor = GetTopMostAncestorInPublication(pub->oid, ancestors, - &level); + &level, + except_pubids); if (ancestor != InvalidOid) { @@ -2281,7 +2314,8 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) } if (list_member_oid(pubids, pub->oid) || - list_member_oid(schemaPubids, pub->oid) || + (list_member_oid(schemaPubids, pub->oid) && + !list_member_oid(except_pubids, pub->oid)) || ancestor_published) publish = true; } @@ -2360,6 +2394,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) list_free(pubids); list_free(schemaPubids); + list_free(except_pubids); list_free(rel_publications); entry->replicate_valid = true; diff --git a/src/backend/utils/cache/relcache.c b/src/backend/utils/cache/relcache.c index fb4e042be8a..92ff89fa2a4 100644 --- a/src/backend/utils/cache/relcache.c +++ b/src/backend/utils/cache/relcache.c @@ -5845,16 +5845,29 @@ RelationBuildPublicationDesc(Relation relation, PublicationDesc *pubdesc) /* Fetch the publication membership info. */ puboids = GetRelationIncludedPublications(relid); schemaid = RelationGetNamespace(relation); - puboids = list_concat_unique_oid(puboids, GetSchemaPublications(schemaid)); if (relation->rd_rel->relispartition) { - Oid last_ancestor_relid; - - /* Add publications that the ancestors are in too. */ ancestors = get_partition_ancestors(relid); - last_ancestor_relid = llast_oid(ancestors); + exceptpuboids = GetRelationExcludedPublications(llast_oid(ancestors)); + } + else + exceptpuboids = GetRelationExcludedPublications(relid); + /* + * Subtract exceptpuboids from the schema-publication contribution so that + * a relation EXCEPT'd from a schema publication does not inherit that + * publication's pubactions. Without this filter, + * CheckCmdReplicaIdentity() would demand REPLICA IDENTITY for + * UPDATE/DELETE even on a explicitly excluded table. + */ + puboids = list_concat_unique_oid(puboids, + list_difference_oid(GetSchemaPublications(schemaid), + exceptpuboids)); + + if (relation->rd_rel->relispartition) + { + /* Add publications that the ancestors are in too. */ foreach(lc, ancestors) { Oid ancestor = lfirst_oid(lc); @@ -5863,23 +5876,9 @@ RelationBuildPublicationDesc(Relation relation, PublicationDesc *pubdesc) GetRelationIncludedPublications(ancestor)); schemaid = get_rel_namespace(ancestor); puboids = list_concat_unique_oid(puboids, - GetSchemaPublications(schemaid)); + list_difference_oid(GetSchemaPublications(schemaid), + exceptpuboids)); } - - /* - * Only the top-most ancestor can appear in the EXCEPT clause. - * Therefore, for a partition, exclusion must be evaluated at the - * top-most ancestor. - */ - exceptpuboids = GetRelationExcludedPublications(last_ancestor_relid); - } - else - { - /* - * For a regular table or a root partitioned table, check exclusion on - * table itself. - */ - exceptpuboids = GetRelationExcludedPublications(relid); } alltablespuboids = GetAllTablesPublications(); diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c index fef86b4cca3..72e8f58fc3e 100644 --- a/src/bin/psql/describe.c +++ b/src/bin/psql/describe.c @@ -6815,6 +6815,24 @@ describePublications(const char *pattern) if (!addFooterToPublicationDesc(&buf, _("Tables from schemas:"), true, &cont)) goto error_return; + + if (pset.sversion >= 190000) + { + /* + * Get tables in the EXCEPT clause for this schema + * publication. + */ + printfPQExpBuffer(&buf, + "SELECT concat(c.relnamespace::regnamespace, '.', c.relname)\n" + "FROM pg_catalog.pg_class c\n" + " JOIN pg_catalog.pg_publication_rel pr ON c.oid = pr.prrelid\n" + "WHERE pr.prpubid = '%s'\n" + " AND pr.prexcept\n" + "ORDER BY 1", pubid); + if (!addFooterToPublicationDesc(&buf, _("Except tables:"), + true, &cont)) + goto error_return; + } } } else diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index 49ea584cd4f..067168699f6 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -1065,6 +1065,24 @@ static const SchemaQuery Query_for_trigger_of_table = { "SELECT nspname FROM pg_catalog.pg_namespace "\ " WHERE nspname LIKE '%s'" +#define Query_for_list_of_tables_in_schema \ +"SELECT n.nspname || '.' || c.relname "\ +" FROM pg_catalog.pg_class c "\ +" JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "\ +" WHERE c.relkind IN (" CppAsString2(RELKIND_RELATION) ", " \ + CppAsString2(RELKIND_PARTITIONED_TABLE) ") "\ +" AND (n.nspname || '.' || c.relname) LIKE '%s' "\ +" AND n.nspname = '%s'" + +#define Query_for_list_of_tables_in_current_schema \ +"SELECT c.relname "\ +" FROM pg_catalog.pg_class c "\ +" JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "\ +" WHERE c.relkind IN (" CppAsString2(RELKIND_RELATION) ", " \ + CppAsString2(RELKIND_PARTITIONED_TABLE) ") "\ +" AND c.relname LIKE '%s' "\ +" AND n.nspname = pg_catalog.current_schema()" + /* Use COMPLETE_WITH_QUERY_VERBATIM with these queries for GUC names: */ #define Query_for_list_of_alter_system_set_vars \ "SELECT pg_catalog.lower(name) FROM pg_catalog.pg_settings "\ @@ -3774,8 +3792,21 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); - else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && (!ends_with(prev_wd, ','))) - COMPLETE_WITH("WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE", "WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* Complete "CREATE PUBLICATION <name> [...] WITH" */ else if (Matches("CREATE", "PUBLICATION", MatchAnyN, "WITH", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/include/catalog/pg_publication.h b/src/include/catalog/pg_publication.h index 89b4bb14f62..53e3d7c6f3d 100644 --- a/src/include/catalog/pg_publication.h +++ b/src/include/catalog/pg_publication.h @@ -191,7 +191,8 @@ extern List *GetPubPartitionOptionRelations(List *result, PublicationPartOpt pub_partopt, Oid relid); extern Oid GetTopMostAncestorInPublication(Oid puboid, List *ancestors, - int *ancestor_level); + int *ancestor_level, + List *except_pubids); extern bool is_publishable_relation(Relation rel); extern bool is_schema_publication(Oid pubid); diff --git a/src/include/commands/publicationcmds.h b/src/include/commands/publicationcmds.h index 4cf45c17cc5..fb1703aa675 100644 --- a/src/include/commands/publicationcmds.h +++ b/src/include/commands/publicationcmds.h @@ -27,6 +27,8 @@ extern void AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt); extern void RemovePublicationById(Oid pubid); extern void RemovePublicationRelById(Oid proid); extern void RemovePublicationSchemaById(Oid psoid); +extern void RemoveSchemaPubExceptForRel(Oid relid, Oid oldNspOid, + Oid newNspOid); extern ObjectAddress AlterPublicationOwner(const char *name, Oid newOwnerId); extern void AlterPublicationOwner_oid(Oid pubid, Oid newOwnerId); diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h index e03556399ab..1f3697ccd23 100644 --- a/src/include/nodes/parsenodes.h +++ b/src/include/nodes/parsenodes.h @@ -4489,6 +4489,8 @@ typedef struct PublicationObjSpec PublicationObjSpecType pubobjtype; /* type of this publication object */ char *name; PublicationTable *pubtable; + List *except_tables; /* tables specified in the EXCEPT clause (for + * TABLES IN SCHEMA) */ ParseLoc location; /* token location, or -1 if unknown */ } PublicationObjSpec; diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 29e54b214a0..1acdcf44932 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -270,6 +270,12 @@ CREATE PUBLICATION testpub_foralltables_excepttable2 FOR ALL TABLES EXCEPT (test ERROR: syntax error at or near "testpub_tbl1" LINE 1: ..._foralltables_excepttable2 FOR ALL TABLES EXCEPT (testpub_tb... ^ +-- fail - EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testpub_tbl3); +ERROR: EXCEPT is not allowed for TABLE publication objects +LINE 2: FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testp... + ^ --------------------------------------------- -- SET ALL TABLES/SEQUENCES --------------------------------------------- @@ -470,7 +476,154 @@ HINT: Change the publication's EXCEPT clause using ALTER PUBLICATION ... SET AL RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Create same-named tables in public to verify unqualified EXCEPT entries +-- are qualified with the named schema, not public +CREATE TABLE testpub_nopk (foo int, bar int); +CREATE TABLE testpub_tbl_s1 (a int primary key, b text); +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + Publication testpub_schema_except1 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- Exclude multiple tables using unqualified names; same-named tables exist in +-- public to confirm unqualified names resolve to pub_test, not public +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + Publication testpub_schema_except2 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_nopk" + "pub_test.testpub_tbl_s1" + +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testp... + ^ +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); +ERROR: table "pub_test.testpub_tbl_s1" in EXCEPT clause does not belong to schema "public" +LINE 2: ...R TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.t... + ^ +-- Multiple schemas each with their own EXCEPT clause +CREATE PUBLICATION testpub_schema_except_multi + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_schema_except_multi + Publication testpub_schema_except_multi + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- ALTER TABLE ... SET SCHEMA on a table excluded by a schema publication: +-- the schema-scoped exclusion is no longer meaningful once the table moves +-- out of its schema, so the exclusion is auto-removed. +CREATE PUBLICATION testpub_schema_except_setsch + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_schema_except_setsch + Publication testpub_schema_except_setsch + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s2" + +ALTER TABLE pub_test.testpub_tbl_s2 SET SCHEMA public; +\dRp+ testpub_schema_except_setsch + Publication testpub_schema_except_setsch + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + +DROP PUBLICATION testpub_schema_except_setsch; +-- Restore for further tests +ALTER TABLE public.testpub_tbl_s2 SET SCHEMA pub_test; +-- fail: table appears in both the explicit table list and the EXCEPT clause +CREATE PUBLICATION testpub_except_conflict + FOR TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot be both published and excluded +-- fail: nonexistent table in EXCEPT clause +CREATE PUBLICATION testpub_except_norel + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- fail: partition cannot appear in EXCEPT clause; only root tables are allowed +CREATE TABLE pub_test.testpub_parted_s (a int) PARTITION BY LIST (a); +CREATE TABLE pub_test.testpub_part_s PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (1); +CREATE PUBLICATION testpub_except_partition + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); +ERROR: cannot specify relation "pub_test.testpub_part_s" in the publication EXCEPT clause +DETAIL: This operation is not supported for individual partitions. +-- fail: partition still rejected from EXCEPT even when its own root is also +-- named in the same EXCEPT list +CREATE PUBLICATION testpub_except_partition_with_root + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s, TABLE pub_test.testpub_parted_s); +ERROR: cannot specify relation "pub_test.testpub_part_s" in the publication EXCEPT clause +DETAIL: This operation is not supported for individual partitions. +-- fail: TABLE keyword is required for the first entry in the EXCEPT clause +CREATE PUBLICATION testpub_except_nokw + FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +ERROR: syntax error at or near "testpub_nopk" +LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + ^ +-- fail: ADD TABLE for a partition is rejected when a partition ancestor +-- is currently in the publication's EXCEPT list. +CREATE PUBLICATION testpub_except_ancestor + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ALTER PUBLICATION testpub_except_ancestor ADD TABLE pub_test.testpub_part_s; +ERROR: cannot add partition "pub_test.testpub_part_s" to publication "testpub_except_ancestor" +DETAIL: Ancestor "pub_test.testpub_parted_s" of partition "pub_test.testpub_part_s" is currently listed in the EXCEPT clause of the publication. +HINT: Change EXCEPT list using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT. +DROP PUBLICATION testpub_except_ancestor; +-- fail: same contradiction (explicit partition + EXCEPT-ed ancestor), but +-- given in a single statement instead of two separate ones; the ancestor's +-- EXCEPT row doesn't exist in the catalog yet when the explicit partition is +-- validated, so this must be caught by comparing the in-memory lists +CREATE PUBLICATION testpub_except_ancestor_same_create + FOR TABLE pub_test.testpub_part_s, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ERROR: partition "pub_test.testpub_part_s" cannot be both published and excluded +DETAIL: Ancestor "pub_test.testpub_parted_s" is also being excluded by this same command. +-- Cleanup +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP TABLE pub_test.testpub_parted_s CASCADE; +DROP TABLE testpub_nopk, testpub_tbl_s1; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +--------------------------------------------- +-- Tests for publications with SEQUENCES +--------------------------------------------- CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; -- FOR ALL SEQUENCES @@ -1953,6 +2106,27 @@ ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b); ERROR: column specification not allowed for schema LINE 1: ...TION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b)... ^ +-- EXCEPT clause with CURRENT_SCHEMA: cross-schema entry must be rejected +SET search_path = pub_test1; +-- qualified name from wrong schema -> error +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.tbl1); +ERROR: table "pub_test2.tbl1" in EXCEPT clause does not belong to schema "pub_test1" +-- unqualified name implicitly qualified with current schema (pub_test1.tbl) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl); +RESET client_min_messages; +\dRp+ testpub_cursch_except + Publication testpub_cursch_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test1" +Except tables: + "pub_test1.tbl" + +DROP PUBLICATION testpub_cursch_except; +RESET search_path; -- cleanup pub_test1 schema for invalidation tests ALTER PUBLICATION testpub2_forschema DROP TABLES IN SCHEMA pub_test1; DROP PUBLICATION testpub3_forschema, testpub4_forschema, testpub5_forschema, testpub6_forschema, testpub_fortable; @@ -2304,6 +2478,7 @@ DROP ROLE regress_publication_user_dummy; -- Test pg_get_publication_tables(text[], oid) function CREATE SCHEMA gpt_test_sch; CREATE TABLE gpt_test_sch.tbl_sch (id int); +CREATE TABLE gpt_test_sch.tbl_sch2 (id int); CREATE TABLE tbl_normal (id int); CREATE TABLE tbl_parent (id1 int, id2 int, id3 int) PARTITION BY RANGE (id1); CREATE TABLE tbl_part1 PARTITION OF tbl_parent FOR VALUES FROM (1) TO (10); @@ -2314,6 +2489,7 @@ CREATE PUBLICATION pub_all_no_viaroot FOR ALL TABLES WITH (publish_via_partition CREATE PUBLICATION pub_all_except FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = true); CREATE PUBLICATION pub_all_except_no_viaroot FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_schema FOR TABLES IN SCHEMA gpt_test_sch; +CREATE PUBLICATION pub_schema_except FOR TABLES IN SCHEMA gpt_test_sch EXCEPT (TABLE gpt_test_sch.tbl_sch); CREATE PUBLICATION pub_normal FOR TABLE tbl_normal WHERE (id < 10); CREATE PUBLICATION pub_part_leaf FOR TABLE tbl_part1 WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_part_parent FOR TABLE tbl_parent (id1, id2) WHERE (id1 = 10) WITH (publish_via_partition_root = true); @@ -2465,6 +2641,18 @@ SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_part1'); -- no r ---------+---------+-------+------ (0 rows) +-- test for EXCEPT clause with schema publication +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch'); -- no result (excluded) + pubname | relname | attrs | qual +---------+---------+-------+------ +(0 rows) + +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch2'); -- one row (included via schema) + pubname | relname | attrs | qual +-------------------+----------+-------+------ + pub_schema_except | tbl_sch2 | 1 | +(1 row) + -- two rows with different row filter SELECT * FROM test_gpt(ARRAY['pub_all', 'pub_normal'], 'tbl_normal'); pubname | relname | attrs | qual @@ -2517,6 +2705,7 @@ DROP PUBLICATION pub_all_no_viaroot; DROP PUBLICATION pub_all_except; DROP PUBLICATION pub_all_except_no_viaroot; DROP PUBLICATION pub_schema; +DROP PUBLICATION pub_schema_except; DROP PUBLICATION pub_normal; DROP PUBLICATION pub_part_leaf; DROP PUBLICATION pub_part_parent; @@ -2525,7 +2714,9 @@ DROP PUBLICATION pub_part_parent_child; DROP VIEW gpt_test_view; DROP TABLE tbl_normal, tbl_parent, tbl_part1; DROP SCHEMA gpt_test_sch CASCADE; -NOTICE: drop cascades to table gpt_test_sch.tbl_sch +NOTICE: drop cascades to 2 other objects +DETAIL: drop cascades to table gpt_test_sch.tbl_sch +drop cascades to table gpt_test_sch.tbl_sch2 -- stage objects for pg_dump tests CREATE SCHEMA pubme CREATE TABLE t0 (c int, d int) CREATE TABLE t1 (c int); CREATE SCHEMA pubme2 CREATE TABLE t0 (c int, d int); diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 041e14a4de6..c0d7c2f9d82 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -123,6 +123,9 @@ CREATE PUBLICATION testpub_foralltables_excepttable1 FOR ALL TABLES EXCEPT (TABL \d testpub_tbl1 -- fail - first table in the EXCEPT list should use TABLE keyword CREATE PUBLICATION testpub_foralltables_excepttable2 FOR ALL TABLES EXCEPT (testpub_tbl1, testpub_tbl2); +-- fail - EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testpub_tbl3); --------------------------------------------- -- SET ALL TABLES/SEQUENCES @@ -220,7 +223,103 @@ RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Create same-named tables in public to verify unqualified EXCEPT entries +-- are qualified with the named schema, not public +CREATE TABLE testpub_nopk (foo int, bar int); +CREATE TABLE testpub_tbl_s1 (a int primary key, b text); + +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + +-- Exclude multiple tables using unqualified names; same-named tables exist in +-- public to confirm unqualified names resolve to pub_test, not public +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); + +-- Multiple schemas each with their own EXCEPT clause +CREATE PUBLICATION testpub_schema_except_multi + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_schema_except_multi + +-- ALTER TABLE ... SET SCHEMA on a table excluded by a schema publication: +-- the schema-scoped exclusion is no longer meaningful once the table moves +-- out of its schema, so the exclusion is auto-removed. +CREATE PUBLICATION testpub_schema_except_setsch + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_schema_except_setsch +ALTER TABLE pub_test.testpub_tbl_s2 SET SCHEMA public; +\dRp+ testpub_schema_except_setsch +DROP PUBLICATION testpub_schema_except_setsch; +-- Restore for further tests +ALTER TABLE public.testpub_tbl_s2 SET SCHEMA pub_test; + +-- fail: table appears in both the explicit table list and the EXCEPT clause +CREATE PUBLICATION testpub_except_conflict + FOR TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: nonexistent table in EXCEPT clause +CREATE PUBLICATION testpub_except_norel + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- fail: partition cannot appear in EXCEPT clause; only root tables are allowed +CREATE TABLE pub_test.testpub_parted_s (a int) PARTITION BY LIST (a); +CREATE TABLE pub_test.testpub_part_s PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (1); +CREATE PUBLICATION testpub_except_partition + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); + +-- fail: partition still rejected from EXCEPT even when its own root is also +-- named in the same EXCEPT list +CREATE PUBLICATION testpub_except_partition_with_root + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s, TABLE pub_test.testpub_parted_s); + +-- fail: TABLE keyword is required for the first entry in the EXCEPT clause +CREATE PUBLICATION testpub_except_nokw + FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + +-- fail: ADD TABLE for a partition is rejected when a partition ancestor +-- is currently in the publication's EXCEPT list. +CREATE PUBLICATION testpub_except_ancestor + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ALTER PUBLICATION testpub_except_ancestor ADD TABLE pub_test.testpub_part_s; +DROP PUBLICATION testpub_except_ancestor; + +-- fail: same contradiction (explicit partition + EXCEPT-ed ancestor), but +-- given in a single statement instead of two separate ones; the ancestor's +-- EXCEPT row doesn't exist in the catalog yet when the explicit partition is +-- validated, so this must be caught by comparing the in-memory lists +CREATE PUBLICATION testpub_except_ancestor_same_create + FOR TABLE pub_test.testpub_part_s, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); + +-- Cleanup +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP TABLE pub_test.testpub_parted_s CASCADE; +DROP TABLE testpub_nopk, testpub_tbl_s1; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; + +--------------------------------------------- +-- Tests for publications with SEQUENCES +--------------------------------------------- CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; @@ -1189,6 +1288,18 @@ ALTER PUBLICATION testpub1_forschema SET TABLES IN SCHEMA pub_test1, pub_test1; ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo (a, b); ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b); +-- EXCEPT clause with CURRENT_SCHEMA: cross-schema entry must be rejected +SET search_path = pub_test1; +-- qualified name from wrong schema -> error +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.tbl1); +-- unqualified name implicitly qualified with current schema (pub_test1.tbl) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl); +RESET client_min_messages; +\dRp+ testpub_cursch_except +DROP PUBLICATION testpub_cursch_except; +RESET search_path; + -- cleanup pub_test1 schema for invalidation tests ALTER PUBLICATION testpub2_forschema DROP TABLES IN SCHEMA pub_test1; DROP PUBLICATION testpub3_forschema, testpub4_forschema, testpub5_forschema, testpub6_forschema, testpub_fortable; @@ -1443,6 +1554,7 @@ DROP ROLE regress_publication_user_dummy; -- Test pg_get_publication_tables(text[], oid) function CREATE SCHEMA gpt_test_sch; CREATE TABLE gpt_test_sch.tbl_sch (id int); +CREATE TABLE gpt_test_sch.tbl_sch2 (id int); CREATE TABLE tbl_normal (id int); CREATE TABLE tbl_parent (id1 int, id2 int, id3 int) PARTITION BY RANGE (id1); CREATE TABLE tbl_part1 PARTITION OF tbl_parent FOR VALUES FROM (1) TO (10); @@ -1454,6 +1566,7 @@ CREATE PUBLICATION pub_all_no_viaroot FOR ALL TABLES WITH (publish_via_partition CREATE PUBLICATION pub_all_except FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = true); CREATE PUBLICATION pub_all_except_no_viaroot FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_schema FOR TABLES IN SCHEMA gpt_test_sch; +CREATE PUBLICATION pub_schema_except FOR TABLES IN SCHEMA gpt_test_sch EXCEPT (TABLE gpt_test_sch.tbl_sch); CREATE PUBLICATION pub_normal FOR TABLE tbl_normal WHERE (id < 10); CREATE PUBLICATION pub_part_leaf FOR TABLE tbl_part1 WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_part_parent FOR TABLE tbl_parent (id1, id2) WHERE (id1 = 10) WITH (publish_via_partition_root = true); @@ -1510,6 +1623,10 @@ SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'gpt_test_sch.tbl_sch SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_parent'); -- no result (excluded) SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_part1'); -- no result +-- test for EXCEPT clause with schema publication +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch'); -- no result (excluded) +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch2'); -- one row (included via schema) + -- two rows with different row filter SELECT * FROM test_gpt(ARRAY['pub_all', 'pub_normal'], 'tbl_normal'); @@ -1538,6 +1655,7 @@ DROP PUBLICATION pub_all_no_viaroot; DROP PUBLICATION pub_all_except; DROP PUBLICATION pub_all_except_no_viaroot; DROP PUBLICATION pub_schema; +DROP PUBLICATION pub_schema_except; DROP PUBLICATION pub_normal; DROP PUBLICATION pub_part_leaf; DROP PUBLICATION pub_part_parent; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 8c58d282eee..18c7b2c1fca 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -24,14 +24,17 @@ my $result; sub test_except_root_partition { - my ($pubviaroot) = @_; + my ($pubviaroot, $pubsql) = @_; + $pubsql //= + "CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1)"; + $pubsql .= " WITH (publish_via_partition_root = $pubviaroot)"; # If the root partitioned table is in the EXCEPT clause, all its # partitions are excluded from publication, regardless of the # publish_via_partition_root setting. $node_publisher->safe_psql( 'postgres', qq( - CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1) WITH (publish_via_partition_root = $pubviaroot); + $pubsql; INSERT INTO root1 VALUES (1), (101); )); $node_subscriber->safe_psql('postgres', @@ -223,6 +226,131 @@ $node_subscriber->safe_psql( test_except_root_partition('false'); test_except_root_partition('true'); +# Same validation using TABLES IN SCHEMA instead of FOR ALL TABLES. +my $schema_pub = + "CREATE PUBLICATION tap_pub_part FOR TABLES IN SCHEMA public EXCEPT (TABLE public.root1)"; +test_except_root_partition('false', $schema_pub); +test_except_root_partition('true', $schema_pub); + +# ============================================ +# EXCEPT test cases for TABLES IN SCHEMA +# ============================================ + +# Create a dedicated schema with two tables: one to be published and one to be +# excluded. Also create inherited tables to verify ONLY semantics. +$node_publisher->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_published AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.tab_excluded AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.parent (a int); + CREATE TABLE sch1.child (b int) INHERITS (sch1.parent); +)); + +$node_subscriber->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_published (a int); + CREATE TABLE sch1.tab_excluded (a int); + CREATE TABLE sch1.parent (a int); + CREATE TABLE sch1.child (b int) INHERITS (sch1.parent); +)); + +# Basic test: initial sync respects EXCEPT. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_excluded)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: initial sync copies included table'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: initial sync skips excluded table'); + +# DML: only the included table should be replicated. +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (6); + INSERT INTO sch1.tab_excluded VALUES (6); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(6), + 'TABLES IN SCHEMA EXCEPT: DML on included table is replicated'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: DML on excluded table is not replicated'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Inherited tables: excluding the parent (without ONLY) also excludes the child. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.parent)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.child VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.child"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: excluding parent (without ONLY) also excludes child' +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Test that EXCEPT (TABLE ONLY parent) excludes only the parent itself, not its +# child. Truncate child first so rows from the previous test are not copied by +# the initial table sync of the next subscription. +$node_publisher->safe_psql('postgres', 'TRUNCATE sch1.child'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE sch1.child'); +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE ONLY sch1.parent)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.child VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.child"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: ONLY parent in EXCEPT does not exclude child'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Cleanup schema tables before the multi-publication section. +$node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); +$node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); + # ============================================ # Test when a subscription is subscribing to multiple publications # ============================================ @@ -254,6 +382,7 @@ $node_publisher->safe_psql( DROP PUBLICATION tap_pub2; TRUNCATE tab1; )); +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_subscriber->safe_psql('postgres', qq(TRUNCATE tab1)); # OK when a table is excluded by pub1 EXCEPT clause, but it is included by pub2 -- 2.50.1 (Apple Git-155)
v19-0002-Restrict-conflicting-EXCEPT-lists-in-multi-schem.patch (application/octet-stream, 18.9K) download From 941c3a44ead8c0046ab17745646d448b128d3f4a Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Wed, 8 Jul 2026 15:07:22 +0530 Subject: [PATCH v19 2/5] Restrict conflicting EXCEPT lists in multi-schema publications Add ProcessSchemaExceptTables() to qualify each mention's EXCEPT entries, build a sorted signature per schema OID, and compare it against any prior mention of the same schema in the same statement, erroring on a mismatch. --- src/backend/commands/publicationcmds.c | 171 ++++++++++++++++++---- src/backend/parser/gram.y | 35 +---- src/test/regress/expected/publication.out | 61 ++++++++ src/test/regress/sql/publication.sql | 44 ++++++ 4 files changed, 248 insertions(+), 63 deletions(-) diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 226ddafda93..4289b6bd802 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -62,6 +62,18 @@ typedef struct rf_context Oid parentid; /* relid of the parent relation */ } rf_context; +/* + * Records the EXCEPT-table signature already seen for a schema mentioned in + * a TABLES IN SCHEMA / TABLES IN SCHEMA CURRENT_SCHEMA list, so that a later + * mention of the same schema OID can be checked for consistency. See + * ProcessSchemaExceptTables(). + */ +typedef struct SchemaExceptSig +{ + Oid schemaid; + List *sig; /* sorted list of qualified-name strings */ +} SchemaExceptSig; + static List *OpenTableList(List *tables); static void CloseTableList(List *rels); static void LockSchemaList(List *schemalist); @@ -73,6 +85,10 @@ static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); static char defGetGeneratedColsOption(DefElem *def); static void CheckExceptNotInTableList(List *except_rels, List *explicitrelids); +static void ProcessSchemaExceptTables(Oid schemaid, const char *schema_name, + List *except_tables, ParseState *pstate, + List **schema_except_seen, + List **except_pubtables); static void @@ -177,6 +193,119 @@ parse_publication_options(ParseState *pstate, } } +/* + * list_sort() comparator for ProcessSchemaExceptTables()'s signature lists. + */ +static int +pub_except_sig_cmp(const ListCell *a, const ListCell *b) +{ + return strcmp((const char *) lfirst(a), (const char *) lfirst(b)); +} + +/* + * Returns true if the two (already-sorted) EXCEPT-table signature lists + * built by ProcessSchemaExceptTables() are identical. + */ +static bool +pub_except_sig_equal(List *sig1, List *sig2) +{ + ListCell *lc1; + ListCell *lc2; + + if (list_length(sig1) != list_length(sig2)) + return false; + + forboth(lc1, sig1, lc2, sig2) + { + if (strcmp((const char *) lfirst(lc1), (const char *) lfirst(lc2)) != 0) + return false; + } + + return true; +} + +/* + * Qualify unqualified EXCEPT table names with schema_name, reject entries + * explicitly qualified with a different schema, and append the (now + * qualified) tables to *except_pubtables. + * + * Also detects the case where schemaid was already mentioned earlier in the + * same TABLES IN SCHEMA list with a different EXCEPT list: since each + * mention flattens its except_tables independently, without this check two + * (or more) mentions of the same schema with differing EXCEPT lists would + * silently union together instead of being rejected as contradictory. + * *schema_except_seen accumulates the signature (sorted list of qualified + * relation names) seen so far for each schema OID in this statement. + */ +static void +ProcessSchemaExceptTables(Oid schemaid, const char *schema_name, + List *except_tables, ParseState *pstate, + List **schema_except_seen, List **except_pubtables) +{ + List *sig = NIL; + SchemaExceptSig *seen = NULL; + + foreach_ptr(PublicationObjSpec, eobj, except_tables) + { + const char *eobj_schemaname = eobj->pubtable->relation->schemaname; + const char *eobj_relname = eobj->pubtable->relation->relname; + + if (eobj_schemaname == NULL) + eobj->pubtable->relation->schemaname = pstrdup(schema_name); + else if (strcmp(eobj_schemaname, schema_name) != 0) + ereport(ERROR, + errcode(ERRCODE_INVALID_OBJECT_DEFINITION), + errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", + quote_qualified_identifier(eobj_schemaname, eobj_relname), + schema_name), + parser_errposition(pstate, eobj->location)); + + /* + * Include the ONLY-ness of this entry in its signature. EXCEPT + * (TABLE parent) excludes parent and its inheritance children, + * while EXCEPT (TABLE ONLY parent) excludes only parent itself. + * These are different exclusion sets, so two mentions of this + * schema that differ only in ONLY must not compare equal below -- + * otherwise they'd look like a harmless repeat instead of the + * genuine conflict they are. + */ + sig = lappend(sig, psprintf("%s%s", + eobj->pubtable->relation->inh ? "" : "ONLY ", + quote_qualified_identifier(NULL, eobj_relname))); + } + + list_sort(sig, pub_except_sig_cmp); + + foreach_ptr(SchemaExceptSig, entry, *schema_except_seen) + { + if (entry->schemaid == schemaid) + { + seen = entry; + break; + } + } + + if (seen) + { + if (!pub_except_sig_equal(seen->sig, sig)) + ereport(ERROR, + errcode(ERRCODE_INVALID_OBJECT_DEFINITION), + errmsg("schema \"%s\" specified with conflicting EXCEPT lists", + schema_name)); + } + else + { + SchemaExceptSig *entry = palloc_object(SchemaExceptSig); + + entry->schemaid = schemaid; + entry->sig = sig; + *schema_except_seen = lappend(*schema_except_seen, entry); + } + + foreach_ptr(PublicationObjSpec, eobj, except_tables) + *except_pubtables = lappend(*except_pubtables, eobj->pubtable); +} + /* * Convert the PublicationObjSpecType list into schema oid list and * PublicationTable list. @@ -187,6 +316,7 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, { ListCell *cell; PublicationObjSpec *pubobj; + List *schema_except_seen = NIL; if (!pubobjspec_list) return; @@ -194,6 +324,7 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, foreach(cell, pubobjspec_list) { Oid schemaid; + char *schema_name; List *search_path; pubobj = (PublicationObjSpec *) lfirst(cell); @@ -210,9 +341,14 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, break; case PUBLICATIONOBJ_TABLES_IN_SCHEMA: schemaid = get_namespace_oid(pubobj->name, false); + schema_name = pubobj->name; /* Filter out duplicates if user specifies "sch1, sch1" */ *schemas = list_append_unique_oid(*schemas, schemaid); + + ProcessSchemaExceptTables(schemaid, schema_name, + pubobj->except_tables, pstate, + &schema_except_seen, except_pubtables); break; case PUBLICATIONOBJ_TABLES_IN_CUR_SCHEMA: search_path = fetch_search_path(false); @@ -223,41 +359,14 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, schemaid = linitial_oid(search_path); list_free(search_path); + schema_name = get_namespace_name(schemaid); /* Filter out duplicates if user specifies "sch1, sch1" */ *schemas = list_append_unique_oid(*schemas, schemaid); - /* - * Qualify unqualified EXCEPT table names with the resolved - * current schema and reject any explicitly cross-schema - * entries. This mirrors the parse-time handling done for - * TABLES_IN_SCHEMA in preprocess_pubobj_list(), deferred here - * because CURRENT_SCHEMA is not known until execution time. - */ - if (pubobj->except_tables != NIL) - { - char *cur_schema_name = get_namespace_name(schemaid); - - foreach_ptr(PublicationObjSpec, eobj, pubobj->except_tables) - { - const char *eobj_schemaname = - eobj->pubtable->relation->schemaname; - const char *eobj_relname = - eobj->pubtable->relation->relname; - - if (eobj_schemaname == NULL) - eobj->pubtable->relation->schemaname = cur_schema_name; - else if (strcmp(eobj_schemaname, cur_schema_name) != 0) - ereport(ERROR, - errcode(ERRCODE_INVALID_OBJECT_DEFINITION), - errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", - quote_qualified_identifier(eobj_schemaname, eobj_relname), - cur_schema_name)); - - *except_pubtables = lappend(*except_pubtables, - eobj->pubtable); - } - } + ProcessSchemaExceptTables(schemaid, schema_name, + pubobj->except_tables, pstate, + &schema_except_seen, except_pubtables); break; default: /* shouldn't happen */ diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y index 6a7a1bc5f8d..df1fa3356d9 100644 --- a/src/backend/parser/gram.y +++ b/src/backend/parser/gram.y @@ -20789,8 +20789,9 @@ preprocess_pub_all_objtype_list(List *all_objects_list, List **pubobjects, /* * Process pubobjspec_list to check for errors in any of the objects and * convert PUBLICATIONOBJ_CONTINUATION into appropriate PublicationObjSpecType. - * Also flattens except_tables from TABLES IN SCHEMA nodes into the list so - * that ObjectsInPublicationToOids() sees them as top-level EXCEPT_TABLE entries. + * The except_tables attached to TABLES IN SCHEMA nodes are left in place; + * ObjectsInPublicationToOids() qualifies names, validates schema membership, + * and flattens them once the schema OID is known. */ static void preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) @@ -20874,36 +20875,6 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) errcode(ERRCODE_SYNTAX_ERROR), errmsg("invalid schema name"), parser_errposition(pubobj->location)); - - /* - * For TABLES_IN_SCHEMA, qualify unqualified EXCEPT table names - * with the parent schema and reject cross-schema entries at parse - * time, then flatten into the top-level list. - * - * For TABLES_IN_CUR_SCHEMA the schema name is not yet known, so - * skip both steps here; ObjectsInPublicationToOids() will - * qualify names and validate schema membership at execution time. - */ - if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLES_IN_SCHEMA) - { - foreach_ptr(PublicationObjSpec, eobj, pubobj->except_tables) - { - const char *eobj_schemaname = eobj->pubtable->relation->schemaname; - const char *eobj_relname = eobj->pubtable->relation->relname; - - if (eobj_schemaname == NULL) - eobj->pubtable->relation->schemaname = pubobj->name; - else if (strcmp(eobj_schemaname, pubobj->name) != 0) - ereport(ERROR, - errcode(ERRCODE_INVALID_OBJECT_DEFINITION), - errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", - quote_qualified_identifier(eobj_schemaname, eobj_relname), - pubobj->name), - parser_errposition(eobj->location)); - } - pubobjspec_list = list_concat(pubobjspec_list, pubobj->except_tables); - pubobj->except_tables = NIL; - } } prevobjtype = pubobj->pubobjtype; diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 1acdcf44932..1f26cdc2966 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -543,6 +543,34 @@ Except tables: "pub_test.testpub_tbl_s1" "public.testpub_tbl1" +-- Repeating the same schema with an identical EXCEPT list is allowed, same +-- as repeating a schema with no EXCEPT list at all ("sch1, sch1") +CREATE PUBLICATION testpub_schema_except_samerepeat + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except_samerepeat + Publication testpub_schema_except_samerepeat + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +DROP PUBLICATION testpub_schema_except_samerepeat; +-- fail: same schema repeated with conflicting EXCEPT lists +CREATE PUBLICATION testpub_schema_except_conflict + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +ERROR: schema "pub_test" specified with conflicting EXCEPT lists +-- fail: same schema repeated where a later mention drops the EXCEPT list +-- entirely (an empty EXCEPT list still conflicts with a non-empty one) +CREATE PUBLICATION testpub_schema_except_conflict2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2), + pub_test; +ERROR: schema "pub_test" specified with conflicting EXCEPT lists -- ALTER TABLE ... SET SCHEMA on a table excluded by a schema publication: -- the schema-scoped exclusion is no longer meaningful once the table moves -- out of its schema, so the exclusion is auto-removed. @@ -2111,6 +2139,8 @@ SET search_path = pub_test1; -- qualified name from wrong schema -> error CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.tbl1); ERROR: table "pub_test2.tbl1" in EXCEPT clause does not belong to schema "pub_test1" +LINE 1: ...FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.... + ^ -- unqualified name implicitly qualified with current schema (pub_test1.tbl) SET client_min_messages = 'ERROR'; CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl); @@ -2126,6 +2156,37 @@ Except tables: "pub_test1.tbl" DROP PUBLICATION testpub_cursch_except; +-- CURRENT_SCHEMA and a named schema that resolve to the same OID must be +-- treated as the same schema for EXCEPT-list consistency checking, just +-- like two mentions of the same schema name +-- fail: CURRENT_SCHEMA and pub_test1 (same schema) have conflicting EXCEPT lists +CREATE PUBLICATION testpub_cursch_named_conflict + FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl), + pub_test1 EXCEPT (TABLE tbl1); +ERROR: schema "pub_test1" specified with conflicting EXCEPT lists +-- succeeds: CURRENT_SCHEMA and pub_test1 (same schema) share the same EXCEPT list +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_named_same + FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl), + pub_test1 EXCEPT (TABLE tbl); +RESET client_min_messages; +\dRp+ testpub_cursch_named_same + Publication testpub_cursch_named_same + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test1" +Except tables: + "pub_test1.tbl" + +DROP PUBLICATION testpub_cursch_named_same; +-- fail: two CURRENT_SCHEMA mentions (both resolving to pub_test1) with +-- conflicting EXCEPT lists +CREATE PUBLICATION testpub_cursch_cursch_conflict + FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl), + CURRENT_SCHEMA EXCEPT (TABLE tbl1); +ERROR: schema "pub_test1" specified with conflicting EXCEPT lists RESET search_path; -- cleanup pub_test1 schema for invalidation tests ALTER PUBLICATION testpub2_forschema DROP TABLES IN SCHEMA pub_test1; diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index c0d7c2f9d82..97ef5decfb4 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -260,6 +260,26 @@ CREATE PUBLICATION testpub_schema_except_multi public EXCEPT (TABLE testpub_tbl1); \dRp+ testpub_schema_except_multi +-- Repeating the same schema with an identical EXCEPT list is allowed, same +-- as repeating a schema with no EXCEPT list at all ("sch1, sch1") +CREATE PUBLICATION testpub_schema_except_samerepeat + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except_samerepeat +DROP PUBLICATION testpub_schema_except_samerepeat; + +-- fail: same schema repeated with conflicting EXCEPT lists +CREATE PUBLICATION testpub_schema_except_conflict + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); + +-- fail: same schema repeated where a later mention drops the EXCEPT list +-- entirely (an empty EXCEPT list still conflicts with a non-empty one) +CREATE PUBLICATION testpub_schema_except_conflict2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2), + pub_test; + -- ALTER TABLE ... SET SCHEMA on a table excluded by a schema publication: -- the schema-scoped exclusion is no longer meaningful once the table moves -- out of its schema, so the exclusion is auto-removed. @@ -1298,6 +1318,30 @@ CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXC RESET client_min_messages; \dRp+ testpub_cursch_except DROP PUBLICATION testpub_cursch_except; + +-- CURRENT_SCHEMA and a named schema that resolve to the same OID must be +-- treated as the same schema for EXCEPT-list consistency checking, just +-- like two mentions of the same schema name +-- fail: CURRENT_SCHEMA and pub_test1 (same schema) have conflicting EXCEPT lists +CREATE PUBLICATION testpub_cursch_named_conflict + FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl), + pub_test1 EXCEPT (TABLE tbl1); + +-- succeeds: CURRENT_SCHEMA and pub_test1 (same schema) share the same EXCEPT list +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_named_same + FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl), + pub_test1 EXCEPT (TABLE tbl); +RESET client_min_messages; +\dRp+ testpub_cursch_named_same +DROP PUBLICATION testpub_cursch_named_same; + +-- fail: two CURRENT_SCHEMA mentions (both resolving to pub_test1) with +-- conflicting EXCEPT lists +CREATE PUBLICATION testpub_cursch_cursch_conflict + FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl), + CURRENT_SCHEMA EXCEPT (TABLE tbl1); + RESET search_path; -- cleanup pub_test1 schema for invalidation tests -- 2.50.1 (Apple Git-155)
v19-0003-Add-EXCEPT-support-to-ALTER-PUBLICATION-ADD-TABL.patch (application/octet-stream, 22.5K) download From 8ab91efe0d82212a9d637cbe14fde16ee7c431ac Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Wed, 8 Jul 2026 17:09:06 +0530 Subject: [PATCH v19 3/5] Add EXCEPT support to ALTER PUBLICATION ADD TABLES IN SCHEMA Extend the EXCEPT clause support to allow tables to be excluded when adding a schema to a publication via ALTER PUBLICATION ... ADD. Syntax: ALTER PUBLICATION pub ADD TABLES IN SCHEMA s EXCEPT (TABLE s.t1); Since pg_dump uses ALTER PUBLICATION ... ADD, support for it is included in this patch. --- src/backend/catalog/pg_publication.c | 19 +++-- src/backend/commands/publicationcmds.c | 98 ++++++++++++++++++++++- src/bin/pg_dump/pg_dump.c | 30 ++++++- src/bin/pg_dump/t/002_pg_dump.pl | 24 ++++++ src/bin/psql/tab-complete.in.c | 17 ++++ src/test/regress/expected/publication.out | 66 ++++++++++++++- src/test/regress/sql/publication.sql | 50 +++++++++++- src/test/subscription/t/037_except.pl | 32 ++++++++ 8 files changed, 322 insertions(+), 14 deletions(-) diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index 21857296f49..4ae4b756c95 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -715,15 +715,18 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, * here, as CreatePublication() function invalidates all relations as part * of defining a FOR ALL TABLES publication. * - * For ALTER PUBLICATION, invalidation is needed only when adding an - * EXCEPT table to a publication already marked as ALL TABLES. For - * publications that were originally empty or defined as ALL SEQUENCES and - * are being converted to ALL TABLES, invalidation is skipped here, as - * AlterPublicationAllFlags() function invalidates all relations while - * marking the publication as ALL TABLES publication. + * For ALTER PUBLICATION, invalidation is needed when adding an EXCEPT + * table to either a FOR ALL TABLES publication (pub->alltables is true) + * or a FOR TABLES IN SCHEMA publication (is_schema_publication is true). + * The exception: when a publication is being converted to FOR ALL TABLES + * (pub->alltables is still false at this point), + * AlterPublicationAllFlags() will perform a full invalidation, so we skip + * it here. */ - inval_except_table = (alter_stmt != NULL) && pub->alltables && - (alter_stmt->for_all_tables && pri->except); + inval_except_table = (alter_stmt != NULL) && pri->except && + (pub->alltables + ? alter_stmt->for_all_tables + : is_schema_publication(pubid)); if (!pri->except || inval_except_table) { diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 4289b6bd802..1096ff84ace 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -83,6 +83,13 @@ static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok); static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); +static void AlterPublicationSchemas(AlterPublicationStmt *stmt, + HeapTuple tup, List *schemaidlist, + List *except_pubtables); +static void AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, + List *except_pubtables, + List *schemaidlist); static char defGetGeneratedColsOption(DefElem *def); static void CheckExceptNotInTableList(List *except_rels, List *explicitrelids); static void ProcessSchemaExceptTables(Oid schemaid, const char *schema_name, @@ -1645,7 +1652,8 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, */ static void AlterPublicationSchemas(AlterPublicationStmt *stmt, - HeapTuple tup, List *schemaidlist) + HeapTuple tup, List *schemaidlist, + List *except_pubtables) { Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); @@ -1722,6 +1730,88 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, */ PublicationAddSchemas(pubform->oid, schemaidlist, true, stmt); } + + /* + * Increment the command counter so that is_schema_publication() in + * GetExcludedPublicationTables() can see the just-inserted schema + * rows when AlterPublicationSchemaExceptTables runs next. + */ + if (stmt->action == AP_AddObjects || stmt->action == AP_SetObjects) + CommandCounterIncrement(); + + AlterPublicationSchemaExceptTables(stmt, tup, except_pubtables, schemaidlist); +} + +/* + * Alter the EXCEPT list of a schema-level publication. + * + * Adds, removes, or replaces except-table entries in pg_publication_rel + * (rows with prexcept = true). These entries suppress publication of the + * named tables that would otherwise be covered by a FOR TABLES IN SCHEMA + * clause. + */ +static void +AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, List *except_pubtables, + List *schemaidlist) +{ + Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); + Oid pubid = pubform->oid; + + /* + * Nothing to do if no EXCEPT entries. + */ + if (!except_pubtables) + return; + + /* + * This function handles EXCEPT entries for schema-level publications + * only. For FOR ALL TABLES publications, EXCEPT entries are already + * processed by AlterPublicationTables(). + */ + if (schemaidlist == NIL && !is_schema_publication(pubid)) + return; + + /* + * Dropping a schema from a publication removes all its EXCEPT entries via + * cascade. The concept of "drop all schema tables from the publication + * EXCEPT these ones" is not supported. + */ + if (stmt->action == AP_DropObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); + + /* + * XXX EXCEPT with SET is not currently implemented. Workaround: DROP and + * re-ADD the schema with the desired EXCEPT list. + */ + if (stmt->action == AP_SetObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"), + errhint("Drop and re-add the schema with the desired EXCEPT list."))); + + if (stmt->action == AP_AddObjects) + { + List *rels; + List *explicitrelids; + + rels = OpenTableList(except_pubtables); + + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + /* + * Validate that each excluded table is not also in the explicit table + * list (which would be contradictory). + */ + CheckExceptNotInTableList(rels, explicitrelids); + + PublicationAddTables(pubid, rels, false, stmt); + + CloseTableList(rels); + } } /* @@ -1931,10 +2021,12 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) errmsg("publication \"%s\" does not exist", stmt->pubname)); - relations = list_concat(relations, except_pubtables); + if (stmt->for_all_tables) + relations = list_concat(relations, except_pubtables); + AlterPublicationTables(stmt, tup, relations, pstate->p_sourcetext, schemaidlist != NIL); - AlterPublicationSchemas(stmt, tup, schemaidlist); + AlterPublicationSchemas(stmt, tup, schemaidlist, except_pubtables); AlterPublicationAllFlags(stmt, rel, tup); } diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c index 4d660d14b4c..4877fd4546c 100644 --- a/src/bin/pg_dump/pg_dump.c +++ b/src/bin/pg_dump/pg_dump.c @@ -4973,6 +4973,7 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) PublicationInfo *pubinfo = pubsinfo->publication; PQExpBuffer query; char *tag; + bool has_except = false; /* Do nothing if not dumping schema */ if (!dopt->dumpSchema) @@ -4983,7 +4984,34 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) query = createPQExpBuffer(); appendPQExpBuffer(query, "ALTER PUBLICATION %s ", fmtId(pubinfo->dobj.name)); - appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s;\n", fmtId(schemainfo->dobj.name)); + appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s", fmtId(schemainfo->dobj.name)); + + /* + * Append EXCEPT clause for any tables that belong to this schema + * and are excluded from the publication. + */ + for (SimplePtrListCell *cell = pubinfo->except_tables.head; cell; cell = cell->next) + { + TableInfo *tbinfo = (TableInfo *) cell->ptr; + + if (strcmp(tbinfo->dobj.namespace->dobj.name, schemainfo->dobj.name) == 0) + { + if (!has_except) + { + appendPQExpBufferStr(query, " EXCEPT ("); + has_except = true; + } + else + appendPQExpBufferStr(query, ", "); + + appendPQExpBuffer(query, "TABLE ONLY %s", fmtId(tbinfo->dobj.name)); + } + } + + if (has_except) + appendPQExpBufferStr(query, ")"); + + appendPQExpBufferStr(query, ";\n"); /* * There is no point in creating drop query as the drop is done by schema diff --git a/src/bin/pg_dump/t/002_pg_dump.pl b/src/bin/pg_dump/t/002_pg_dump.pl index 9258948b583..d18b3b0d7b9 100644 --- a/src/bin/pg_dump/t/002_pg_dump.pl +++ b/src/bin/pg_dump/t/002_pg_dump.pl @@ -3283,6 +3283,30 @@ my %tests = ( like => { %full_runs, section_post_data => 1, }, }, + 'CREATE PUBLICATION pub11' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub11 FOR TABLES IN SCHEMA dump_test EXCEPT (TABLE test_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub11 WITH (publish = 'insert, update, delete, truncate');\E + .*? + \QALTER PUBLICATION pub11 ADD TABLES IN SCHEMA dump_test EXCEPT (TABLE ONLY test_table);\E + /xms, + like => { %full_runs, section_post_data => 1, }, + }, + + 'CREATE PUBLICATION pub12' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub12 FOR TABLES IN SCHEMA dump_test EXCEPT (TABLE test_table, dump_test.test_second_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub12 WITH (publish = 'insert, update, delete, truncate');\E + .*? + \QALTER PUBLICATION pub12 ADD TABLES IN SCHEMA dump_test EXCEPT (TABLE ONLY test_table, TABLE ONLY test_second_table);\E + /xms, + like => { %full_runs, section_post_data => 1, }, + }, + 'CREATE SUBSCRIPTION sub1' => { create_order => 50, create_sql => 'CREATE SUBSCRIPTION sub1 diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index 067168699f6..23009ca2f40 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2359,6 +2359,23 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); + /* After a single schema name in ADD context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 1f26cdc2966..d583709cf7c 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -643,12 +643,76 @@ CREATE PUBLICATION testpub_except_ancestor_same_create TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); ERROR: partition "pub_test.testpub_part_s" cannot be both published and excluded DETAIL: Ancestor "pub_test.testpub_parted_s" is also being excluded by this same command. +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; +-- fail: non-existing table in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- fail: EXCEPT table belongs to a different schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 1: ...xcept ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.tes... + ^ +-- fail: TABLE keyword is required for the first entry in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +ERROR: syntax error at or near "testpub_nopk" +LINE 1: ...lter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_no... + ^ +-- fail: exact same table given as both explicitly published and excluded +-- in a single ALTER ... ADD +ALTER PUBLICATION testpub_alter_except + ADD TABLE pub_test.testpub_tbl_s1, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot be both published and excluded +-- fail: add explicit partition and EXCEPT ancestor, given in a +-- single ALTER ... ADD statement +ALTER PUBLICATION testpub_alter_except + ADD TABLE pub_test.testpub_part_s, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ERROR: partition "pub_test.testpub_part_s" cannot be both published and excluded +DETAIL: Ancestor "pub_test.testpub_parted_s" is also being excluded by this same command. +-- fail: partition still rejected from EXCEPT even when its own root is also +-- named in the same EXCEPT list, via ALTER ... ADD +ALTER PUBLICATION testpub_alter_except + ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s, TABLE pub_test.testpub_parted_s); +ERROR: cannot specify relation "pub_test.testpub_part_s" in the publication EXCEPT clause +DETAIL: This operation is not supported for individual partitions. +-- fail: partition already explicitly published, then its root is EXCEPT-ed +-- via a later, separate ALTER ... ADD +ALTER PUBLICATION testpub_alter_except ADD TABLE pub_test.testpub_part_s; +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ERROR: partition "pub_test.testpub_part_s" cannot be both published and excluded +DETAIL: Ancestor "pub_test.testpub_parted_s" is also being excluded by this same command. +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_part_s; +-- fail: root already explicitly published, then its partition is rejected +-- from EXCEPT via a later, separate ALTER ... ADD (partitions can never +-- appear in EXCEPT, independent of the root's state) +ALTER PUBLICATION testpub_alter_except ADD TABLE pub_test.testpub_parted_s; +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); +ERROR: cannot specify relation "pub_test.testpub_part_s" in the publication EXCEPT clause +DETAIL: This operation is not supported for individual partitions. +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_parted_s; +-- ADD: qualified and unqualified names; unqualified is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + "pub_test.testpub_tbl_s2" + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP TABLE pub_test.testpub_parted_s CASCADE; DROP TABLE testpub_nopk, testpub_tbl_s1; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi, testpub_alter_except; --------------------------------------------- -- Tests for publications with SEQUENCES --------------------------------------------- diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 97ef5decfb4..30589ecded4 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -330,12 +330,60 @@ CREATE PUBLICATION testpub_except_ancestor_same_create FOR TABLE pub_test.testpub_part_s, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; + +-- fail: non-existing table in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- fail: EXCEPT table belongs to a different schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- fail: TABLE keyword is required for the first entry in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + +-- fail: exact same table given as both explicitly published and excluded +-- in a single ALTER ... ADD +ALTER PUBLICATION testpub_alter_except + ADD TABLE pub_test.testpub_tbl_s1, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: add explicit partition and EXCEPT ancestor, given in a +-- single ALTER ... ADD statement +ALTER PUBLICATION testpub_alter_except + ADD TABLE pub_test.testpub_part_s, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); + +-- fail: partition still rejected from EXCEPT even when its own root is also +-- named in the same EXCEPT list, via ALTER ... ADD +ALTER PUBLICATION testpub_alter_except + ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s, TABLE pub_test.testpub_parted_s); + +-- fail: partition already explicitly published, then its root is EXCEPT-ed +-- via a later, separate ALTER ... ADD +ALTER PUBLICATION testpub_alter_except ADD TABLE pub_test.testpub_part_s; +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_part_s; + +-- fail: root already explicitly published, then its partition is rejected +-- from EXCEPT via a later, separate ALTER ... ADD (partitions can never +-- appear in EXCEPT, independent of the root's state) +ALTER PUBLICATION testpub_alter_except ADD TABLE pub_test.testpub_parted_s; +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_parted_s; + +-- ADD: qualified and unqualified names; unqualified is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); +\dRp+ testpub_alter_except + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP TABLE pub_test.testpub_parted_s CASCADE; DROP TABLE testpub_nopk, testpub_tbl_s1; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi, testpub_alter_except; --------------------------------------------- -- Tests for publications with SEQUENCES diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 18c7b2c1fca..0ba6d6f8bb2 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -347,6 +347,38 @@ is($result, qq(5), $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); +# ============================================ +# ALTER PUBLICATION EXCEPT for TABLES IN SCHEMA +# ============================================ + +# Truncate subscriber tables to remove data accumulated from previous tests. +$node_subscriber->safe_psql('postgres', + 'TRUNCATE sch1.tab_published, sch1.tab_excluded, sch1.parent, sch1.child'); + +# ADD: add a schema with an excepted table; verify the except entry takes effect. +$node_publisher->safe_psql('postgres', "CREATE PUBLICATION sch_pub"); +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub ADD TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_excluded)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(6), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: included table synced'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + # Cleanup schema tables before the multi-publication section. $node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); $node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); -- 2.50.1 (Apple Git-155)
v19-0004-Add-EXCEPT-support-to-ALTER-PUBLICATION-SET-TABL.patch (application/octet-stream, 27.5K) download From d92667b42adfb5c97eadfb62911fc4638112905a Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Thu, 18 Jun 2026 11:32:32 +0530 Subject: [PATCH v19 4/5] Add EXCEPT support to ALTER PUBLICATION SET TABLES IN SCHEMA Extend AlterPublicationExceptTables() with the AP_SetObjects case, which redefines the publication and replaces the entire EXCEPT list. Syntax: ALTER PUBLICATION pub SET TABLES IN SCHEMA s EXCEPT (TABLE t1); This patch also cleans up EXCEPT entries when a schema is dropped from the publication. --- src/backend/commands/publicationcmds.c | 181 +++++++++++++++++++--- src/bin/psql/tab-complete.in.c | 17 ++ src/test/regress/expected/publication.out | 109 +++++++++++++ src/test/regress/sql/publication.sql | 47 ++++++ src/test/subscription/t/037_except.pl | 85 ++++++++++ 5 files changed, 414 insertions(+), 25 deletions(-) diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 1096ff84ace..c3c151f1854 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -79,7 +79,8 @@ static void CloseTableList(List *rels); static void LockSchemaList(List *schemalist); static void PublicationAddTables(Oid pubid, List *rels, bool if_not_exists, AlterPublicationStmt *stmt); -static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok); +static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok, + bool delete_excluded); static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); @@ -1496,7 +1497,7 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, PublicationAddTables(pubid, rels, false, stmt); } else if (stmt->action == AP_DropObjects) - PublicationDropTables(pubid, rels, false); + PublicationDropTables(pubid, rels, false, false); else /* AP_SetObjects */ { List *oldrelids = NIL; @@ -1631,7 +1632,7 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, } /* And drop them. */ - PublicationDropTables(pubid, delrels, true); + PublicationDropTables(pubid, delrels, true, true); /* * Don't bother calculating the difference for adding, we'll catch and @@ -1733,8 +1734,8 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, /* * Increment the command counter so that is_schema_publication() in - * GetExcludedPublicationTables() can see the just-inserted schema - * rows when AlterPublicationSchemaExceptTables runs next. + * GetExcludedPublicationTables() can see the just-inserted schema rows + * when AlterPublicationSchemaExceptTables runs next. */ if (stmt->action == AP_AddObjects || stmt->action == AP_SetObjects) CommandCounterIncrement(); @@ -1752,16 +1753,18 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, */ static void AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, - HeapTuple tup, List *except_pubtables, - List *schemaidlist) + HeapTuple tup, List *except_pubtables, + List *schemaidlist) { Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); Oid pubid = pubform->oid; /* - * Nothing to do if no EXCEPT entries. + * Nothing to do if there are no EXCEPT entries, unless handling the SET + * command, because if the user has removed all exceptions we need to drop + * any existing ones. */ - if (!except_pubtables) + if (!except_pubtables && stmt->action != AP_SetObjects) return; /* @@ -1782,16 +1785,6 @@ AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); - /* - * XXX EXCEPT with SET is not currently implemented. Workaround: DROP and - * re-ADD the schema with the desired EXCEPT list. - */ - if (stmt->action == AP_SetObjects) - ereport(ERROR, - (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"), - errhint("Drop and re-add the schema with the desired EXCEPT list."))); - if (stmt->action == AP_AddObjects) { List *rels; @@ -1810,6 +1803,76 @@ AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, PublicationAddTables(pubid, rels, false, stmt); + CloseTableList(rels); + } + else /* AP_SetObjects */ + { + List *oldexceptrelids = NIL; + List *newexceptrelids = NIL; + List *delrelids = NIL; + List *rels; + List *explicitrelids; + + rels = OpenTableList(except_pubtables); + + /* Collect OIDs of the desired new EXCEPT list. */ + foreach_ptr(PublicationRelInfo, pri, rels) + newexceptrelids = lappend_oid(newexceptrelids, + RelationGetRelid(pri->relation)); + + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + /* + * Validate that no excluded table is also already explicitly + * published (exact match), and that no already-published partition + * has its root among the tables being newly excluded here. + */ + CheckExceptNotInTableList(rels, explicitrelids); + + /* + * Get the current set of EXCEPT entries. Only FOR ALL TABLES and + * schema-level publications can have EXCEPT entries; for any other + * publication type oldexceptrelids stays NIL. + * + * Note: we check is_schema_publication() against the current catalog + * state (before AlterPublicationSchemas has run), so if the caller is + * doing SET TABLE t1 to convert a schema publication into a plain + * table publication, is_schema_publication() still returns true here. + * That is intentional: it lets us discover and clean up any stale + * EXCEPT entries that belong to the old schema definition. + */ + if (GetPublication(pubid)->alltables || is_schema_publication(pubid)) + oldexceptrelids = GetExcludedPublicationTables(pubid, + PUBLICATION_PART_ROOT); + + /* Build a list of old EXCEPT entries not present in the new list. */ + foreach_oid(oldrelid, oldexceptrelids) + { + if (!list_member_oid(newexceptrelids, oldrelid)) + delrelids = lappend_oid(delrelids, oldrelid); + } + + /* Drop old EXCEPT entries not present in the new list. */ + foreach_oid(relid, delrelids) + { + Oid proid; + ObjectAddress obj; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + /* Add new EXCEPT entries, skipping any already present. */ + PublicationAddTables(pubid, rels, true, stmt); + CloseTableList(rels); } } @@ -2433,33 +2496,68 @@ PublicationAddTables(Oid pubid, List *rels, bool if_not_exists, /* * Remove listed tables from the publication. + * + * delete_excluded controls how EXCEPT (prexcept=true) rows are handled: + * true - delete them silently. Used by the SET path to clear stale + * EXCEPT rows that are being replaced by a new EXCEPT list. + * false - treat them as "not a member". Used by ALTER ... DROP TABLE: an + * EXCEPT entry is not something DROP TABLE is expected to remove. */ static void -PublicationDropTables(Oid pubid, List *rels, bool missing_ok) +PublicationDropTables(Oid pubid, List *rels, bool missing_ok, + bool delete_excluded) { ObjectAddress obj; ListCell *lc; - Oid prid; foreach(lc, rels) { PublicationRelInfo *pubrel = (PublicationRelInfo *) lfirst(lc); Relation rel = pubrel->relation; Oid relid = RelationGetRelid(rel); + HeapTuple tup; + Form_pg_publication_rel pubrelform; + Oid prid = InvalidOid; + bool is_except = false; if (pubrel->columns) ereport(ERROR, errcode(ERRCODE_SYNTAX_ERROR), errmsg("column list must not be specified in ALTER PUBLICATION ... DROP")); - prid = GetSysCacheOid2(PUBLICATIONRELMAP, Anum_pg_publication_rel_oid, - ObjectIdGetDatum(relid), - ObjectIdGetDatum(pubid)); - if (!OidIsValid(prid)) + tup = SearchSysCache2(PUBLICATIONRELMAP, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (HeapTupleIsValid(tup)) + { + pubrelform = (Form_pg_publication_rel) GETSTRUCT(tup); + is_except = pubrelform->prexcept; + prid = pubrelform->oid; + ReleaseSysCache(tup); + } + + /* + * DROP TABLE operates only on regular member rows. A missing row + * and an EXCEPT row both mean the table isn't currently published, + * but we distinguish them so the EXCEPT case can carry a hint + * pointing the user at the EXCEPT list. The SET-cleanup caller + * (delete_excluded = true) intends to remove EXCEPT rows and so + * bypasses the EXCEPT half of this check. + */ + if (!OidIsValid(prid) || (is_except && !delete_excluded)) { if (missing_ok) continue; + if (is_except) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("cannot drop table \"%s\" from publication \"%s\"", + RelationGetQualifiedRelationName(rel), + get_publication_name(pubid, false)), + errdetail("The table is currently listed in the EXCEPT clause of the publication."), + errhint("Use ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT to drop the table from the EXCEPT list."))); + ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("relation \"%s\" is not part of the publication", @@ -2515,6 +2613,7 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) foreach(lc, schemas) { Oid schemaid = lfirst_oid(lc); + List *except_relids; psid = GetSysCacheOid2(PUBLICATIONNAMESPACEMAP, Anum_pg_publication_namespace_oid, @@ -2531,8 +2630,40 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) get_namespace_name(schemaid)))); } + /* + * Collect EXCEPT entries for tables belonging to this schema before + * removing the schema entry. + */ + except_relids = GetExcludedPublicationTables(pubid, PUBLICATION_PART_ROOT); + ObjectAddressSet(obj, PublicationNamespaceRelationId, psid); performDeletion(&obj, DROP_CASCADE, 0); + + /* + * Drop any prexcept rows for tables belonging to this schema. These + * rows have no pg_depend entry pointing at the + * pg_publication_namespace row, so they are not cascaded by the + * performDeletion() call above and must be cleaned up explicitly. + */ + foreach_oid(relid, except_relids) + { + Oid proid; + + if (get_rel_namespace(relid) != schemaid) + continue; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + list_free(except_relids); } } diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index 23009ca2f40..dcdc3893112 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2376,6 +2376,23 @@ match_previous_words(int pattern_id, } else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) COMPLETE_WITH(")"); + /* After a single schema name in SET context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index d583709cf7c..3ded05cb733 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -707,6 +707,115 @@ Except tables: "pub_test.testpub_tbl_s1" "pub_test.testpub_tbl_s2" +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s2" + +-- fail: table in EXCEPT clause also appears in the explicit table list +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot be both published and excluded +-- fail: explicit partition + EXCEPT-ed root, given in a single SET statement +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_part_s, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ERROR: partition "pub_test.testpub_part_s" cannot be both published and excluded +DETAIL: Ancestor "pub_test.testpub_parted_s" is also being excluded by this same command. +-- fail: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 1: ...xcept SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.tes... + ^ +-- SET: unqualified name in EXCEPT is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- SET without EXCEPT clears the existing except list +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + +-- SET to a different schema removes old schema's EXCEPT entries +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA public; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "public" + +-- fail: nonexistent table in EXCEPT clause (SET path) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- SET: multiple schemas each with their own EXCEPT clause +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- fail: ALTER PUBLICATION ... DROP TABLE on an excluded table is rejected +-- with an EXCEPT-specific error. +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_tbl_s1; +ERROR: cannot drop table "pub_test.testpub_tbl_s1" from publication "testpub_alter_except" +DETAIL: The table is currently listed in the EXCEPT clause of the publication. +HINT: Use ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT to drop the table from the EXCEPT list. +-- the EXCEPT entry is still present after the rejected DROP TABLE +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- fail: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +ERROR: EXCEPT clause is not supported with DROP in ALTER PUBLICATION +-- DROP TABLES IN SCHEMA removes associated EXCEPT entries +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "public" +Except tables: + "public.testpub_tbl1" + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 30589ecded4..d219e74cf53 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -378,6 +378,53 @@ ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_parted_s; ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); \dRp+ testpub_alter_except +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + +-- fail: table in EXCEPT clause also appears in the explicit table list +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: explicit partition + EXCEPT-ed root, given in a single SET statement +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_part_s, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); + +-- fail: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- SET: unqualified name in EXCEPT is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +\dRp+ testpub_alter_except + +-- SET without EXCEPT clears the existing except list +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + +-- SET to a different schema removes old schema's EXCEPT entries +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA public; +\dRp+ testpub_alter_except + +-- fail: nonexistent table in EXCEPT clause (SET path) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- SET: multiple schemas each with their own EXCEPT clause +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_alter_except + +-- fail: ALTER PUBLICATION ... DROP TABLE on an excluded table is rejected +-- with an EXCEPT-specific error. +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_tbl_s1; +-- the EXCEPT entry is still present after the rejected DROP TABLE +\dRp+ testpub_alter_except + +-- fail: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); + +-- DROP TABLES IN SCHEMA removes associated EXCEPT entries +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 0ba6d6f8bb2..01eafb5b7c8 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -376,6 +376,61 @@ $result = is($result, qq(0), 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); +# SET: replace the except list; tab_excluded is now included and tab_published is excluded. +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_published)" +); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (7); + INSERT INTO sch1.tab_excluded VALUES (7); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded WHERE a = 7"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: newly included table is replicated' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published WHERE a = 7"); +is($result, qq(0), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: now-excluded table is not replicated' +); + +# SET without EXCEPT: clears the except list; both tables are now published. +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1"); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (8); + INSERT INTO sch1.tab_excluded VALUES (8); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published WHERE a = 8"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_published replicated after except list cleared' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded WHERE a = 8"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_excluded replicated after except list cleared' +); + $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); @@ -443,6 +498,36 @@ $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); +# OK when a table is excluded by a TABLES IN SCHEMA EXCEPT publication, +# but is included by another publication. +$node_publisher->safe_psql('postgres', 'TRUNCATE tab1'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE tab1'); + +$node_publisher->safe_psql( + 'postgres', qq( + CREATE PUBLICATION tap_pub1 FOR TABLES IN SCHEMA public EXCEPT (TABLE public.tab1); + CREATE PUBLICATION tap_pub2 FOR TABLE tab1; + INSERT INTO tab1 VALUES(1); +)); +$node_subscriber->psql('postgres', + "CREATE SUBSCRIPTION tap_sub CONNECTION '$publisher_connstr' PUBLICATION tap_pub1, tap_pub2" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'tap_sub'); + +$node_publisher->safe_psql('postgres', qq(INSERT INTO tab1 VALUES(2))); +$node_publisher->wait_for_catchup('tap_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT * FROM tab1 ORDER BY a"); +is( $result, qq(1 +2), + "TABLES IN SCHEMA EXCEPT: table excluded in schema pub but included by another pub is replicated" +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); + $node_publisher->stop('fast'); done_testing(); -- 2.50.1 (Apple Git-155)
v19-0005-Documentation-Patch.patch (application/octet-stream, 11.6K) download From 6698fd007d74c6626030a556887560cc9d6e7f9b Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Thu, 18 Jun 2026 09:03:08 +0530 Subject: [PATCH v19 5/5] Documentation Patch --- doc/src/sgml/logical-replication.sgml | 3 +- doc/src/sgml/ref/alter_publication.sgml | 58 +++++++++++++++++++++++- doc/src/sgml/ref/create_publication.sgml | 42 +++++++++++++---- 3 files changed, 91 insertions(+), 12 deletions(-) diff --git a/doc/src/sgml/logical-replication.sgml b/doc/src/sgml/logical-replication.sgml index 3b22ee229b9..89ee9c3486b 100644 --- a/doc/src/sgml/logical-replication.sgml +++ b/doc/src/sgml/logical-replication.sgml @@ -117,7 +117,8 @@ or <literal>FOR ALL SEQUENCES</literal>. Unlike tables, sequences can be synchronized at any time. For more information, see <xref linkend="logical-replication-sequences"/>. When a publication is - created with <literal>FOR ALL TABLES</literal>, a table or set of tables can + created with <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal>, a table or set of tables can be explicitly excluded from publication using the <link linkend="sql-createpublication-params-for-except-table"><literal>EXCEPT</literal></link> clause. diff --git a/doc/src/sgml/ref/alter_publication.sgml b/doc/src/sgml/ref/alter_publication.sgml index 52114a16a39..037ddfa9404 100644 --- a/doc/src/sgml/ref/alter_publication.sgml +++ b/doc/src/sgml/ref/alter_publication.sgml @@ -31,7 +31,7 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA <replaceable class="parameter">tables_in_schema</replaceable> [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -47,6 +47,10 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <replaceable class="parameter">table_object</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] [ WHERE ( <replaceable class="parameter">expression</replaceable> ) ] +<phrase>and <replaceable class="parameter">tables_in_schema</replaceable> is:</phrase> + + { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] + <phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> TABLE <replaceable class="parameter">table_object</replaceable> [, ... ] @@ -69,6 +73,9 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r The first two variants modify which tables/schemas are part of the publication. The <literal>ADD</literal> and <literal>DROP</literal> clauses will add and remove one or more tables/schemas from the publication. + The <literal>EXCEPT</literal> clause can be used with + <literal>ADD TABLES IN SCHEMA</literal> to exclude specific tables from a + schema-level publication. </para> <para> @@ -93,7 +100,11 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r used with a publication defined with <literal>FOR TABLE</literal> or <literal>FOR TABLES IN SCHEMA</literal>, replaces the list of tables/schemas in the publication with the specified list; the existing tables or schemas - that were present in the publication will be removed. + that were present in the publication will be removed. When + <literal>SET TABLES IN SCHEMA</literal> is used with an + <literal>EXCEPT</literal> clause, the excluded tables for each schema are + replaced with the specified list; if <literal>EXCEPT</literal> is omitted + for a schema, any existing exclusions for that schema are cleared. </para> <para> @@ -198,6 +209,27 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r </listitem> </varlistentry> + <varlistentry> + <term><literal>EXCEPT</literal></term> + <listitem> + <para> + When used with <literal>ADD TABLES IN SCHEMA</literal> + or <literal>SET TABLES IN SCHEMA</literal>, specifies + tables to be excluded from the publication. Each named + table must belong to the schema specified in the same + <literal>TABLES IN SCHEMA</literal> clause. Table names may be + schema-qualified or unqualified; unqualified names are implicitly + qualified with the schema named in the same clause. See + <xref linkend="sql-createpublication"/> for further details on the + semantics of <literal>EXCEPT</literal>. + </para> + <para> + Dropping a table always removes it from the <literal>EXCEPT</literal> + clause. + </para> + </listitem> + </varlistentry> + <varlistentry> <term><literal>SET ( <replaceable class="parameter">publication_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] )</literal></term> <listitem> @@ -288,6 +320,28 @@ ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA marketing, sales; </programlisting> </para> + <para> + Add schema <structname>sales</structname> to the publication + <structname>sales_publication</structname>, excluding the + <structname>sales.internal</structname> and + <structname>sales.drafts</structname> tables: +<programlisting> +ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA sales EXCEPT (TABLE internal, drafts); +</programlisting> + </para> + + <para> + Replace the schema list of <structname>sales_publication</structname> with + <structname>sales</structname>, excluding only + <structname>sales.drafts</structname>. Other than + <structname>sales.drafts</structname>, any previously excluded tables for schema + <structname>sales</structname> are no longer excluded. Any schemas previously in + <structname>sales_publication</structname> are removed: +<programlisting> +ALTER PUBLICATION sales_publication SET TABLES IN SCHEMA sales EXCEPT (TABLE drafts); +</programlisting> + </para> + <para> Add tables <structname>users</structname>, <structname>departments</structname> and schema diff --git a/doc/src/sgml/ref/create_publication.sgml b/doc/src/sgml/ref/create_publication.sgml index 85cfcaddafa..26cb536e90b 100644 --- a/doc/src/sgml/ref/create_publication.sgml +++ b/doc/src/sgml/ref/create_publication.sgml @@ -28,7 +28,7 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA <replaceable class="parameter">tables_in_schema</replaceable> [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -39,6 +39,10 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <replaceable class="parameter">table_object</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] [ WHERE ( <replaceable class="parameter">expression</replaceable> ) ] +<phrase>and <replaceable class="parameter">tables_in_schema</replaceable> is:</phrase> + + { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] + <phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> TABLE <replaceable class="parameter">table_object</replaceable> [, ... ] @@ -142,6 +146,8 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <para> Marks the publication as one that replicates changes for all tables in the specified list of schemas, including tables created in the future. + Tables listed in the <literal>EXCEPT</literal> clause for a given schema + are excluded from the publication. </para> <para> @@ -173,7 +179,7 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <para> Marks the publication as one that replicates changes for all tables in the database, including tables created in the future. Tables listed in - <literal>EXCEPT</literal> clause are excluded from the publication. + the <literal>EXCEPT</literal> clause are excluded from the publication. </para> </listitem> </varlistentry> @@ -198,13 +204,21 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <listitem> <para> This clause specifies a list of tables to be excluded from the - publication. + publication. It can be used with <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal>. For <literal>FOR TABLES IN + SCHEMA</literal>, the exclusion applies only to tables in the schema + associated with the <literal>EXCEPT</literal>. </para> <para> - Once a table is excluded, the exclusion applies to that table - regardless of its name or schema. Renaming the table or moving it to - another schema using <command>ALTER TABLE ... SET SCHEMA</command> does - not remove the exclusion. + Once a table is excluded under <literal>FOR ALL TABLES</literal>, the + exclusion applies to that table regardless of its name or schema. + Renaming the table or moving it to another schema using + <command>ALTER TABLE ... SET SCHEMA</command> does not remove the + exclusion. However, for <literal>FOR TABLES IN SCHEMA</literal>, because + the <literal>EXCEPT</literal> is schema-scoped, moving a schema-excluded + table to another schema does remove the exclusion; if the table is later + moved back, the exclusion is not restored and must be re-established + with <command>ALTER PUBLICATION</command>. </para> <para> For inherited tables, if <literal>ONLY</literal> is specified before the @@ -216,8 +230,9 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> </para> <para> For partitioned tables, only the root partitioned table may be specified - in <literal>EXCEPT</literal>. Doing so excludes the root table and - all of its partitions from replication. The optional + in <literal>EXCEPT</literal>. Excluding the root table automatically + excludes all of its partitions from replication, including those in + schemas that are otherwise included in the publication. The optional <literal>ONLY</literal> and <literal>*</literal> has no effect for partitioned tables. </para> @@ -521,6 +536,15 @@ CREATE PUBLICATION production_publication FOR TABLE users, departments, TABLES I CREATE PUBLICATION sales_publication FOR TABLES IN SCHEMA marketing, sales; </programlisting></para> + <para> + Create a publication that publishes all changes for all the tables present in + the schema <structname>sales</structname>, except + <structname>internal</structname> and <structname>drafts</structname>: +<programlisting> +CREATE PUBLICATION sales_filtered FOR TABLES IN SCHEMA sales EXCEPT (TABLE internal, drafts); +</programlisting> + </para> + <para> Create a publication that publishes all changes for table <structname>users</structname>, but replicates only columns <structname>user_id</structname> and -- 2.50.1 (Apple Git-155)
^ permalink raw reply [nested|flat] 196+ messages in thread

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-08 15:22  Nisha Moond <nisha.moond412@gmail.com>
  parent: Peter Smith <smithpb2250@gmail.com>
  0 siblings, 0 replies; 196+ messages in thread

From: Nisha Moond @ 2026-07-08 15:22 UTC (permalink / raw)
  To: Peter Smith <smithpb2250@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Mon, Jul 6, 2026 at 1:25 PM Peter Smith <smithpb2250@gmail.com> wrote:
>
> Hi Nisha.
>
> Some review comments for v18.
>
> //////////
> Patch v18-0001
> //////////
...
>
> ~
>
> 1b.
> Why hint to change the except list -- who says the EXCEPT list is wrong?
>
> It seemed more like a user error to me if they are trying to drop
> something from a publication when it is already excluded. Why does
> this need any hint at all?

Okay, I see your point. The intent of the hint was to guide users who
are actually trying to remove a table from the EXCEPT list by pointing
them to SET.

I've reworded it to:
HINT: Use ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT to
drop the table from the EXCEPT list.

Hopefully this is clearer and more helpful. Let me know if this works,
or if you still think no hint is the better option.

>
> ======
> src/test/regress/sql/publication.sql
>
> 2.
> I did not recognise the distinction in the test comments between
> "fail:" and "error:".
>

Fixed. I now use "fail" consistently throughout.

...
>
> //////////
> Patch v18-0004
> //////////
>
> doc/src/sgml/ref/create_publication.sgml
>
> 1.
>       <para>
>        For partitioned tables, only the root partitioned table may be specified
>        in <literal>EXCEPT</literal>. Doing so excludes the root table and
> -      all of its partitions from replication. The optional
> +      all of its partitions from replication, even any partition that lives
> +      in a schema which is itself included in the publication.
>
> BEFORE
> For partitioned tables, only the root partitioned table may be
> specified in EXCEPT. Doing so excludes the root table and all of its
> partitions from replication, even any partition that lives in a schema
> which is itself included in the publication.
>
> SUGGESTION #1
> For partitioned tables, only the root partitioned table may be
> specified in EXCEPT. Excluding the root table automatically excludes
> all of its partitions from replication, including those in schemas
> that are otherwise included in the publication.
>
> SUGGESTION #2 (TI doubt you even needed to mention about other schemas)
> For partitioned tables, only the root partitioned table may be
> specified in EXCEPT. Excluding the root table automatically excludes
> all of its partitions from replication, including those that would
> otherwise be included in the publication.
>

I lean towards Suggestion #1, as not publishing a table/partition when
its schema is published without any exception is a non-obvious case
and should be stated explicitly.

--
Thanks,
Nisha





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-08 15:22  Nisha Moond <nisha.moond412@gmail.com>
  parent: Amit Kapila <amit.kapila16@gmail.com>
  1 sibling, 0 replies; 196+ messages in thread

From: Nisha Moond @ 2026-07-08 15:22 UTC (permalink / raw)
  To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Peter Smith <smithpb2250@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; shveta malik <shvetamalik@gmail.com>

On Wed, Jul 8, 2026 at 11:58 AM Amit Kapila <amit.kapila16@gmail.com> wrote:
>
> On Tue, Jul 7, 2026 at 4:13 PM shveta malik <shveta.malik@gmail.com> wrote:
> >
> > On Tue, Jul 7, 2026 at 2:31 PM shveta malik <shveta.malik@gmail.com> wrote:
> > >
> > > On Fri, Jul 3, 2026 at 10:15 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
> > > >
> > > >
> > > > postgres=# alter publication pub2 add table t_part_p1;
> > > > ERROR:  cannot add table "public.t_part_p1" to publication "pub2"
> > > > DETAIL:  Partition ancestor "public.t_part" of table
> > > > "public.t_part_p1" is currently listed in the EXCEPT clause of the
> > > > publication.
> > > > HINT:  Change EXCEPT list using ALTER PUBLICATION ... SET TABLES IN
> > > > SCHEMA ... EXCEPT.
> > > > ~~~
> > >
> > > Thanks. Do you think we should restrict this case too? To me, this
> > > seems like another variation of the above where conflicting entries
> > > are given at the time of sub-creation itself. The root is excluded but
> > > parittion is included .
> > >
> > > postgres=# create publication pub1 for table s2.tab_part_1, tables in
> > > schema s2 except (table tab_root);
> > > CREATE PUBLICATION
> > > postgres=# \dRp+
> > >                                                       Publication pub1
> > >  Owner  | All tables | All sequences | Inserts | Updates | Deletes |
> > > Truncates | Generated columns | Via root | Description
> > > --------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+-------------
> > >  shveta | f          | f             | t       | t       | t       | t
> > >         | none              | f        |
> > > Tables:
> > >     "s2.tab_part_1"
> > > Tables from schemas:
> > >     "s2"
> > > Except tables:
> > >     "s2.tab_root"
> > >
> >
> > Since alter is blocked for above case while create-sub is not,
> >
>
> If a combination is not supported in ALTER, we should disallow the
> same in CREATE as well. So, +1 to restrict the case you reported.
>

Fixed in v19.

> > I had a
> > look at the new check added in check_publication_add_relation
> >
> > a) The check introduced in this function for partitions/ancestors is
> > sufficient for cases where an except-list is already present, but not
> > for cases where we are in the process of adding one. Thus the
> > create-sub scenario above is not covered by this.
> >
> > b) Also the new check in check_publication_add_relation() gets and
> > traverses complete list of ancestors
> >
> > + List    *ancestors = get_partition_ancestors(relid);
> > +
> > + foreach_oid(ancestor, ancestors)
> >
> > Isn't getting root (llast_oid(ancestors)) and checking that alone in
> > EXCEPT list will suffice? Or am I missing something?
> >
>
> I think this should be possible because we allow only root tables in
> the EXCEPT list. If so, and we are planning to change as per your
> suggestion then we should add a comment as to why checking only last
> is okay here.
>

Agreed; I implemented the suggested optimization and added comments
explaining why checking only the last element is sufficient.

--
Thanks,
Nisha





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-09 09:23  shveta malik <shveta.malik@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: shveta malik @ 2026-07-09 09:23 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; shveta malik <shveta.malik@gmail.com>

On Wed, Jul 8, 2026 at 8:50 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
>
> On Tue, Jul 7, 2026 at 8:40 AM shveta malik <shveta.malik@gmail.com> wrote:
> >
> > On Tue, Jul 7, 2026 at 4:31 AM Peter Smith <smithpb2250@gmail.com> wrote:
> > >
> > > Hi Nisha.
> > >
> > > Bug: The current patch is allowing conflicting exclusion lists...
> > >
> > > ======
> > >
> > > Background:
> > >
> > > It's always been possible for CREATE PUBLICATION to specify the same
> > > schema or same table multiple times.
> > >
> > > test_pub=# CREATE SCHEMA MYSCHEMA;
> > > CREATE SCHEMA
> > > test_pub=# CREATE TABLE T1(A INT);
> > > CREATE TABLE
> > > test_pub=# CREATE TABLE MYSCHEMA.T2(A INT);
> > > CREATE TABLE
> > > test_pub=# CREATE TABLE MYSCHEMA.T3(A INT);
> > > CREATE TABLE
> > >
> > > // same table multiple times is OK
> > > test_pub=# CREATE PUBLICATION PUB3 FOR TABLE T1,T1,T1,T1;
> > > CREATE PUBLICATION
> > >
> > > // same schema multiple times is OK
> > > test_pub=# CREATE PUBLICATION PUB1 FOR TABLES IN SCHEMA MYSCHEMA,
> > > MYSCHEMA, MYSCHEMA;
> > > CREATE PUBLICATION
> > >
> > > ~~~
> > >
> > > But, this behaviour is only allowed if there are no specification
> > > conflicts. e.g. You can't have multiple tables with column lists:
> > >
> > > test_pub=# CREATE PUBLICATION PUB4 FOR TABLE T1,T1(A),T1,T1;
> > > ERROR:  conflicting or redundant column lists for table "t1"
> > >
> > > ======
> > >
> > > Bug:
> > >
> > > IMO similar restrictions and a similar error message needs to happen
> > > for clashing schema exclusions. Specifying the same schema multiple
> > > times is fine, but it must be disallowed if there are conflicting
> > > exclusion lists.
> > >
> >
> > +1. Good Catch.
> >
>
> Thanks for the bug report. I've fixed it and attached the fix as a
> separate top-up patch, v19-0002.
>
> Until v18, schema qualification checks for EXCEPT tables were split
> between two places:
>
> 1) TABLES IN SCHEMA <schema-name> (EXCEPT TABLE <table-name>);
>  -- the schema qualification check was performed in gram.y, since all
> required information was available during parsing.
>
> 2) TABLES IN SCHEMA CURRENT_SCHEMA (EXCEPT TABLE <table-name>);
>  -- CURRENT_SCHEMA is resolved only at execution time, so the schema
> qualification and eligibility checks were performed there.
>
> The reported bug also affects cases such as:
> CREATE PUBLICATION PUB2 FOR TABLES IN SCHEMA MYSCHEMA EXCEPT (TABLE
> T2), CURRENT_SCHEMA EXCEPT (TABLE T3);
>  -- where CURRENT_SCHEMA = myschema. Correct handling of this case
> requires the checks to be performed after schema resolution, i.e., at
> execution time. To reduce duplicate code, I moved the schema
> qualification and eligibility checks for both cases to execution time
> and removed the corresponding processing from gram.y.
>
> Since this changes a fair amount of code, I've kept it as a separate
> patch (v19-0002) to make review easier. Depending on the feedback, we
> can optimize the implementation or move parts of it back into gram.y
> before merging it into patch 0001.
> ~~~
>

Nisha,

- * Also flattens except_tables from TABLES IN SCHEMA nodes into the list so
- * that ObjectsInPublicationToOids() sees them as top-level
EXCEPT_TABLE entries.
+ * The except_tables attached to TABLES IN SCHEMA nodes are left in place;
+ * ObjectsInPublicationToOids() qualifies names, validates schema membership,
+ * and flattens them once the schema OID is known.

Can you please explain what does 'flatten' mean here.

The flatten logic here is added by your patch001 only, it is not an
existing logic. To me (in my initial round of review), it seems okay
if we moved it to ObjectsInPublicationToOids(). The only thing is that
the one error (table in EXCEPT clause does not belong to schema) which
is possible to get at the parsing stage will now be emitted during
pub-creation stage. But since it will keep the entire logic of
except-list verification at one place and considering that
creat/alter-pub is not so frequent operation, I am fine with it. But
lets see if others have any comment here.

~~

I had a quick look at the changes:

+ * Include the ONLY-ness of this entry in its signature. EXCEPT
+ * (TABLE parent) excludes parent and its inheritance children,
+ * while EXCEPT (TABLE ONLY parent) excludes only parent itself.

I think this will unconditionally apply to paritioned tables as well
but for paritioned table, EXCEPT doc says that ONLY and * has no
effect, but here it shows the effect:

Thsi gives error:
postgres=# CREATE PUBLICATION pub1 FOR TABLES IN SCHEMA public EXCEPT
(TABLE ONLY tab_root), TABLES IN SCHEMA public EXCEPT (TABLE
tab_root);
ERROR:  42P17: schema "public" specified with conflicting EXCEPT lists
LOCATION:  ProcessSchemaExceptTables, publicationcmds.c:299

While this does not:
postgres=#  CREATE PUBLICATION pub1 FOR TABLES IN SCHEMA public EXCEPT
(TABLE tab_root), TABLES IN SCHEMA public EXCEPT (TABLE tab_root);
CREATE PUBLICATION

But I also checked column-list errors and found that even if columns
are exact sames, we get error:

postgres=# CREATE PUBLICATION PUB4 FOR TABLE T1(i), T1(i);
ERROR:  42710: conflicting or redundant column lists for table "t1"
LOCATION:  OpenTableList, publicationcmds.c:2312

While this works:
postgres=# CREATE PUBLICATION PUB4 FOR TABLE T1, T1;
CREATE PUBLICATION

This makes me think that even introducing the smartness of identifying
ONLY in case of inherited tables and distinguishing it from
parititoned tables is not required. We can just change your error
message to 'conflicting or redundant EXCEPT lists for schmea "s1"' and
throw error in all cases where schmea with except list repeats without
actually comparing them. Does this sound reasonable?

thanks
Shveta





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-10 11:33  Nisha Moond <nisha.moond412@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  0 siblings, 2 replies; 196+ messages in thread

From: Nisha Moond @ 2026-07-10 11:33 UTC (permalink / raw)
  To: shveta malik <shveta.malik@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; Amit Kapila <amit.kapila16@gmail.com>

On Wed, Jul 8, 2026 at 2:58 PM shveta malik <shveta.malik@gmail.com> wrote:
>
> On Wed, Jul 8, 2026 at 2:22 PM shveta malik <shveta.malik@gmail.com> wrote:
> >
> > Nisha, the patch (testing wise) is okay, but some code-optimization
> > might help. I am stuck on reveiw of GetTopMostAncestorInPublication()
> > and all its callers.
> >

Thanks, Shveta.

> > 1)
> > caller 1: pub_rf_contains_invalid_column():
> >
> > It is not understood why pub_rf_contains_invalid_column() does not
> > pass 'exceptPubids' to GetTopMostAncestorInPublication(). Perhaps a
> > comment will help. IIUC, a parittion (for which we are trying to
> > verify row-filter expression) can not co-exist in a subscription where
> > its ROOT is already excluded. This assumption will be true once you
> > address the issue of CREATE SUB (in [1]) sent in my previous email.
> > After that, this will still need a comment.
> >

You're right. Neither pub_rf_contains_invalid_column() nor
pub_contains_invalid_column() depends on
GetTopMostAncestorInPublication(), since
RelationBuildPublicationDesc() already prepares puboids after
excluding GetRelationExcludedPublications(). This follows the same
approach used for the FOR ALL TABLES case.

With your suggestion below, the except_pubids argument is no longer
needed, so I don't think any additional comments are necessary.

> > 2)
> > Both caller 2 (get_rel_sync_entry) and caller 3
> > (is_table_publishable_in_publication) are trying to see if partition
> > should be considered as included in publication and thus are trying to
> > see if ROOT is excluded. But the implementation is very different.
> >
> > The get_rel_sync_entry() does that by passing except_pubids to
> > GetTopMostAncestorInPublication(). This except_pubids was computed for
> > topmost ROOT of the parition in the caller and then it skips checking
> > pg_pub_namepspace if given pubid is part of except_pubids arguement.
> >
> > While is_table_publishable_in_publication() does that by selecting
> > topmost ancestor incuded in a given pubid using
> > GetTopMostAncestorInPublication(), without consulting/computing
> > except_pubids. And then later checks if the ancestor returned by
> > GetTopMostAncestorInPublication() is in pg_publicaiton_rel with
> > 'prexcept' true.
> >
> > IMO, GetTopMostAncestorInPublication() should itself be inclusive of
> > logic where it filters out the table (does not return it as result) if
> > ROOT is excluded. And even we should not be passing an argument for
> > that (this is my initial thought). By making such a logic, we need not
> > to bother about all
> > the callers to see if caller has correct logic to deal with output of
> > GetTopMostAncestorInPublication(). Can you think on this line and
> > check the feasibility.
> >
>
> I thought more on this. Do you think we can do this?
>
> GetTopMostAncestorInPublication() is already accepting a list of
> ancestors in a ordered fashion, root at the end. We get root from this
> ancestor list, check if root is in pg_publication_rel with
> except=true. If so, we skip the rest of the logic and return
> InvalidOid from GetTopMostAncestorInPublication().
>
> The 'except_pubids' argument is not required. Callers need not to have
> special logic to send this arguement or to have extra-processing on
> output as done by is_table_publishable_in_publication() currently.
> Let me know if I have missed anything.

The suggested optimization looks reasonable to me. I verified the test
cases for both callers (2 and 3) and finalized the changes.

During verification, I found it easy to miss cross-schema partition
cases i.e., when the partition root is excluded from one schema while
a child partition belongs to another included schema. To cover this, I
added tests in patch 0001 that tests both get_rel_sync_entry() and
is_table_publishable_in_publication().

Attached is the v20 patch set.

--
Thanks,
Nisha

Attachments: download all (5 files, .tar.gz)

v20-0001-Support-EXCEPT-clause-for-schema-level-publicati.patch (application/octet-stream, 76.4K) download From e8823fca2f98530a6248307fadd948c87ecb0f03 Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Tue, 16 Jun 2026 10:58:49 +0530 Subject: [PATCH v20 1/5] Support EXCEPT clause for schema-level publications Extend table exclusion support in publications to allow specific tables to be excluded from schema-level publications using an EXCEPT clause in CREATE PUBLICATION. Supported syntax: CREATE PUBLICATION <pub> FOR TABLES IN SCHEMA s EXCEPT (TABLE t1,...); --- src/backend/catalog/pg_publication.c | 268 ++++++++++++++++---- src/backend/commands/publicationcmds.c | 185 +++++++++++++- src/backend/commands/tablecmds.c | 11 + src/backend/parser/gram.y | 54 +++- src/backend/replication/pgoutput/pgoutput.c | 46 +++- src/backend/utils/cache/relcache.c | 41 ++- src/bin/psql/describe.c | 18 ++ src/bin/psql/tab-complete.in.c | 35 ++- src/include/commands/publicationcmds.h | 2 + src/include/nodes/parsenodes.h | 2 + src/test/regress/expected/publication.out | 221 +++++++++++++++- src/test/regress/sql/publication.sql | 142 ++++++++++- src/test/subscription/t/037_except.pl | 208 ++++++++++++++- 13 files changed, 1142 insertions(+), 91 deletions(-) diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index 1ec94c851b2..0bdcc07c42d 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -53,9 +53,10 @@ typedef struct * error if not. */ static void -check_publication_add_relation(PublicationRelInfo *pri) +check_publication_add_relation(PublicationRelInfo *pri, Oid pubid) { Relation targetrel = pri->relation; + Oid relid = RelationGetRelid(targetrel); const char *relname; const char *errormsg; @@ -70,12 +71,57 @@ check_publication_add_relation(PublicationRelInfo *pri) errormsg = gettext_noop("cannot add relation \"%s\" to publication"); } - /* If in EXCEPT clause, must be root partitioned table */ - if (pri->except && targetrel->rd_rel->relispartition) - ereport(ERROR, - (errcode(ERRCODE_INVALID_PARAMETER_VALUE), - errmsg(errormsg, relname), - errdetail("This operation is not supported for individual partitions."))); + if (targetrel->rd_rel->relispartition) + { + if (pri->except) + { + /* If in EXCEPT clause, must be root partitioned table */ + ereport(ERROR, + (errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg(errormsg, relname), + errdetail("This operation is not supported for individual partitions."))); + } + else + { + /* + * If not in EXCEPT clause, a partition cannot be independently + * included when its partition root is in this publication's + * EXCEPT list. Doing so would leave the catalog inconsistent + * (root excluded, partition explicitly included) and the + * ancestor-cascade rule would silently override the include at + * replication time. + * + * Only the root of a partition hierarchy can ever appear in an + * EXCEPT clause (a partition itself is rejected just above), so + * checking any intermediate ancestor cannot find a match; the + * root is the only one worth a catalog lookup. + */ + Oid root = llast_oid(get_partition_ancestors(relid)); + HeapTuple atup; + + atup = SearchSysCache2(PUBLICATIONRELMAP, + ObjectIdGetDatum(root), + ObjectIdGetDatum(pubid)); + if (HeapTupleIsValid(atup)) + { + bool root_except = ((Form_pg_publication_rel) GETSTRUCT(atup))->prexcept; + + ReleaseSysCache(atup); + + if (root_except) + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("cannot add partition \"%s\" to publication \"%s\"", + RelationGetQualifiedRelationName(targetrel), + get_publication_name(pubid, false)), + errdetail("Ancestor \"%s\" of partition \"%s\" is currently listed in the EXCEPT clause of the publication.", + quote_qualified_identifier(get_namespace_name(get_rel_namespace(root)), + get_rel_name(root)), + RelationGetQualifiedRelationName(targetrel)), + errhint("Change EXCEPT list using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT."))); + } + } + } /* Must be a regular or partitioned table */ if (RelationGetForm(targetrel)->relkind != RELKIND_RELATION && @@ -340,19 +386,20 @@ is_table_publication(Oid pubid) scan = systable_beginscan(pubrelsrel, PublicationRelPrpubidIndexId, true, NULL, 1, &scankey); - tup = systable_getnext(scan); - if (HeapTupleIsValid(tup)) - { - Form_pg_publication_rel pubrel; - - pubrel = (Form_pg_publication_rel) GETSTRUCT(tup); - /* - * For any publication, pg_publication_rel contains either only EXCEPT - * entries or only explicitly included tables. Therefore, examining - * the first tuple is sufficient to determine table inclusion. - */ - result = !pubrel->prexcept; + /* + * A publication can hold both explicit-include (prexcept=false) and + * EXCEPT (prexcept=true) rows for the same pubid. Scan until we find an + * explicit-include row, rather than relying on the first row's prexcept + * value. + */ + while (HeapTupleIsValid(tup = systable_getnext(scan))) + { + if (!((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept) + { + result = true; + break; + } } systable_endscan(scan); @@ -456,11 +503,38 @@ GetPubPartitionOptionRelations(List *result, PublicationPartOpt pub_partopt, * ancestor is at the end of the list. */ Oid -GetTopMostAncestorInPublication(Oid puboid, List *ancestors, int *ancestor_level) +GetTopMostAncestorInPublication(Oid puboid, List *ancestors, + int *ancestor_level) { ListCell *lc; Oid topmost_relid = InvalidOid; int level = 0; + HeapTuple tup; + + if (ancestors == NIL) + return InvalidOid; + + /* + * If the partition root (the last element of ancestors) is excluded from + * this publication via its EXCEPT clause, the partition is not published + * through this publication at all, so we short-circuit and return + * InvalidOid without walking the ancestor list. Only the root of a + * partition hierarchy can ever appear in a publication's EXCEPT clause (a + * partition itself is rejected from EXCEPT elsewhere), so it's the only + * one worth a catalog lookup. + */ + tup = SearchSysCache2(PUBLICATIONRELMAP, + ObjectIdGetDatum(llast_oid(ancestors)), + ObjectIdGetDatum(puboid)); + if (HeapTupleIsValid(tup)) + { + bool root_except = ((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept; + + ReleaseSysCache(tup); + + if (root_except) + return InvalidOid; + } /* * Find the "topmost" ancestor that is in this publication. @@ -555,21 +629,35 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, * duplicates, it's here just to provide nicer error message in common * case. The real protection is the unique key on the catalog. */ - if (SearchSysCacheExists2(PUBLICATIONRELMAP, ObjectIdGetDatum(relid), - ObjectIdGetDatum(pubid))) + tup = SearchSysCache2(PUBLICATIONRELMAP, ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + + if (HeapTupleIsValid(tup)) { + bool is_except = ((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept; + + ReleaseSysCache(tup); table_close(rel, RowExclusiveLock); if (if_not_exists) return InvalidObjectAddress; - ereport(ERROR, - (errcode(ERRCODE_DUPLICATE_OBJECT), - errmsg("relation \"%s\" is already member of publication \"%s\"", - RelationGetRelationName(targetrel), pub->name))); + if (is_except) + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("cannot add table \"%s\" to publication \"%s\"", + RelationGetQualifiedRelationName(targetrel), + pub->name), + errdetail("The table is currently listed in the EXCEPT clause of the publication."), + errhint("Change EXCEPT list using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT."))); + else + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("relation \"%s\" is already member of publication \"%s\"", + RelationGetRelationName(targetrel), pub->name))); } - check_publication_add_relation(pri); + check_publication_add_relation(pri, pubid); /* Validate and translate column names into a Bitmapset of attnums. */ attnums = pub_collist_validate(pri->relation, pri->columns); @@ -992,12 +1080,13 @@ GetIncludedPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) * Gets list of table oids that were specified in the EXCEPT clause for a * publication. * - * This should only be used FOR ALL TABLES publications. + * This is used for FOR ALL TABLES and FOR TABLES IN SCHEMA publications, + * both of which support EXCEPT TABLE. */ List * GetExcludedPublicationTables(Oid pubid, PublicationPartOpt pub_partopt) { - Assert(GetPublication(pubid)->alltables); + Assert(GetPublication(pubid)->alltables || is_schema_publication(pubid)); return get_publication_relations(pubid, pub_partopt, true); } @@ -1059,15 +1148,15 @@ GetAllPublicationRelations(Oid pubid, char relkind, bool pubviaroot) TableScanDesc scan; HeapTuple tuple; List *result = NIL; - List *exceptlist = NIL; + List *except_relids = NIL; Assert(!(relkind == RELKIND_SEQUENCE && pubviaroot)); /* EXCEPT filtering applies only to relations, not sequences */ if (relkind == RELKIND_RELATION) - exceptlist = GetExcludedPublicationTables(pubid, pubviaroot ? - PUBLICATION_PART_ROOT : - PUBLICATION_PART_LEAF); + except_relids = GetExcludedPublicationTables(pubid, pubviaroot ? + PUBLICATION_PART_ROOT : + PUBLICATION_PART_LEAF); classRel = table_open(RelationRelationId, AccessShareLock); @@ -1085,7 +1174,7 @@ GetAllPublicationRelations(Oid pubid, char relkind, bool pubviaroot) if (is_publishable_class(relid, relForm) && !(relForm->relispartition && pubviaroot) && - !list_member_oid(exceptlist, relid)) + !list_member_oid(except_relids, relid)) result = lappend_oid(result, relid); } @@ -1107,7 +1196,7 @@ GetAllPublicationRelations(Oid pubid, char relkind, bool pubviaroot) if (is_publishable_class(relid, relForm) && !relForm->relispartition && - !list_member_oid(exceptlist, relid)) + !list_member_oid(except_relids, relid)) result = lappend_oid(result, relid); } @@ -1242,22 +1331,68 @@ GetSchemaPublicationRelations(Oid schemaid, PublicationPartOpt pub_partopt) /* * Gets the list of all relations published by FOR TABLES IN SCHEMA - * publication. + * publication, excluding any tables listed in the EXCEPT clause. */ List * GetAllSchemaPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) { List *result = NIL; List *pubschemalist = GetPublicationSchemas(pubid); + List *except_relids = NIL; ListCell *cell; + /* get the list of tables excluded via EXCEPT TABLE for this publication */ + if (pubschemalist != NIL) + except_relids = GetExcludedPublicationTables(pubid, pub_partopt); + foreach(cell, pubschemalist) { Oid schemaid = lfirst_oid(cell); List *schemaRels = NIL; schemaRels = GetSchemaPublicationRelations(schemaid, pub_partopt); - result = list_concat(result, schemaRels); + + if (except_relids != NIL) + { + /* filter out any tables that appear in the EXCEPT list */ + ListCell *rlc; + + foreach(rlc, schemaRels) + { + Oid relid = lfirst_oid(rlc); + bool excluded = list_member_oid(except_relids, relid); + + /* + * A partition whose ancestor is in the publication's EXCEPT + * list is also excluded, even if the partition itself lives + * in a different (included) schema. Individual partitions + * cannot appear in EXCEPT, so cascading from the root is the + * only way to exclude a partition; this matches the ALL + * TABLES EXCEPT (TABLE root) behavior. + */ + if (!excluded && get_rel_relispartition(relid)) + { + List *ancestors = get_partition_ancestors(relid); + ListCell *alc; + + foreach(alc, ancestors) + { + if (list_member_oid(except_relids, lfirst_oid(alc))) + { + excluded = true; + break; + } + } + list_free(ancestors); + } + + if (!excluded) + result = lappend_oid(result, relid); + } + list_free(schemaRels); + } + else + result = list_concat(result, schemaRels); } return result; @@ -1334,6 +1469,7 @@ is_table_publishable_in_publication(Oid relid, Publication *pub) { bool relispartition; List *ancestors = NIL; + HeapTuple tup; /* * For non-pubviaroot publications, a partitioned table is never the @@ -1390,20 +1526,60 @@ is_table_publishable_in_publication(Oid relid, Publication *pub) * If it's false, the partition is covered by its ancestor's presence in * the publication, it should be included (return true). */ - if (relispartition && - OidIsValid(GetTopMostAncestorInPublication(pub->oid, ancestors, NULL))) - return !pub->pubviaroot; + if (relispartition) + { + HeapTuple root_tup; + + if (OidIsValid(GetTopMostAncestorInPublication(pub->oid, ancestors, NULL))) + return !pub->pubviaroot; + + /* + * GetTopMostAncestorInPublication() returns InvalidOid both when no + * ancestor matched at all, and when the root is excluded via EXCEPT. + * Disambiguate here: if the root is excluded, the partition is never + * published through this publication, regardless of whether the + * partition's own schema is separately included. + */ + root_tup = SearchSysCache2(PUBLICATIONRELMAP, + ObjectIdGetDatum(llast_oid(ancestors)), + ObjectIdGetDatum(pub->oid)); + if (HeapTupleIsValid(root_tup)) + { + bool root_except = ((Form_pg_publication_rel) GETSTRUCT(root_tup))->prexcept; + + ReleaseSysCache(root_tup); + if (root_except) + return false; + } + } /* * Check whether the table is explicitly published via pg_publication_rel * or pg_publication_namespace. + * + * A pg_publication_rel row with prexcept=true means the table is + * explicitly excluded via EXCEPT and must not be reported as published, + * even if its schema is otherwise included. A row with prexcept=false + * means it is explicitly included. If no pg_publication_rel row exists, + * the table is published iff its schema appears in + * pg_publication_namespace. */ - return (SearchSysCacheExists2(PUBLICATIONRELMAP, - ObjectIdGetDatum(relid), - ObjectIdGetDatum(pub->oid)) || - SearchSysCacheExists2(PUBLICATIONNAMESPACEMAP, - ObjectIdGetDatum(get_rel_namespace(relid)), - ObjectIdGetDatum(pub->oid))); + + tup = SearchSysCache2(PUBLICATIONRELMAP, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pub->oid)); + if (HeapTupleIsValid(tup)) + { + bool is_except; + + is_except = ((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept; + ReleaseSysCache(tup); + return !is_except; + } + + return SearchSysCacheExists2(PUBLICATIONNAMESPACEMAP, + ObjectIdGetDatum(get_rel_namespace(relid)), + ObjectIdGetDatum(pub->oid)); } /* diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 440adb356ad..9a922a6dcc3 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -22,6 +22,7 @@ #include "catalog/namespace.h" #include "catalog/objectaccess.h" #include "catalog/objectaddress.h" +#include "catalog/partition.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" #include "catalog/pg_namespace.h" @@ -71,6 +72,7 @@ static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); static char defGetGeneratedColsOption(DefElem *def); +static void CheckExceptNotInTableList(List *except_rels, List *explicitrelids); static void @@ -181,7 +183,7 @@ parse_publication_options(ParseState *pstate, */ static void ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, - List **rels, List **exceptrels, List **schemas) + List **rels, List **except_pubtables, List **schemas) { ListCell *cell; PublicationObjSpec *pubobj; @@ -200,7 +202,7 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, { case PUBLICATIONOBJ_EXCEPT_TABLE: pubobj->pubtable->except = true; - *exceptrels = lappend(*exceptrels, pubobj->pubtable); + *except_pubtables = lappend(*except_pubtables, pubobj->pubtable); break; case PUBLICATIONOBJ_TABLE: pubobj->pubtable->except = false; @@ -224,6 +226,38 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, /* Filter out duplicates if user specifies "sch1, sch1" */ *schemas = list_append_unique_oid(*schemas, schemaid); + + /* + * Qualify unqualified EXCEPT table names with the resolved + * current schema and reject any explicitly cross-schema + * entries. This mirrors the parse-time handling done for + * TABLES_IN_SCHEMA in preprocess_pubobj_list(), deferred here + * because CURRENT_SCHEMA is not known until execution time. + */ + if (pubobj->except_tables != NIL) + { + char *cur_schema_name = get_namespace_name(schemaid); + + foreach_ptr(PublicationObjSpec, eobj, pubobj->except_tables) + { + const char *eobj_schemaname = + eobj->pubtable->relation->schemaname; + const char *eobj_relname = + eobj->pubtable->relation->relname; + + if (eobj_schemaname == NULL) + eobj->pubtable->relation->schemaname = cur_schema_name; + else if (strcmp(eobj_schemaname, cur_schema_name) != 0) + ereport(ERROR, + errcode(ERRCODE_INVALID_OBJECT_DEFINITION), + errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", + quote_qualified_identifier(eobj_schemaname, eobj_relname), + cur_schema_name)); + + *except_pubtables = lappend(*except_pubtables, + eobj->pubtable); + } + } break; default: /* shouldn't happen */ @@ -770,6 +804,48 @@ TransformPubWhereClauses(List *tables, const char *queryString, } } +/* + * Check that no relation in except_rels is also present in explicitrelids, + * the list of OIDs added to the publication by the explicit TABLE list. A + * table cannot be both explicitly published and excluded in the same DDL. + * + * Also check that no relation in explicitrelids is a partition whose + * partition root is in except_rels; that would leave the catalog + * inconsistent (root excluded, partition explicitly included) with the + * ancestor-cascade rule silently overriding the include at replication + * time. + */ +static void +CheckExceptNotInTableList(List *except_rels, List *explicitrelids) +{ + foreach_oid(explicitrelid, explicitrelids) + { + Oid root = InvalidOid; + + if (get_rel_relispartition(explicitrelid)) + root = llast_oid(get_partition_ancestors(explicitrelid)); + + foreach_ptr(PublicationRelInfo, pri, except_rels) + { + Oid exceptrelid = RelationGetRelid(pri->relation); + + if (exceptrelid == explicitrelid) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" cannot be both published and excluded", + RelationGetQualifiedRelationName(pri->relation))); + + if (OidIsValid(root) && exceptrelid == root) + ereport(ERROR, + (errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("partition \"%s\" cannot be both published and excluded", + quote_qualified_identifier(get_namespace_name(get_rel_namespace(explicitrelid)), + get_rel_name(explicitrelid))), + errdetail("Ancestor \"%s\" is also being excluded by this same command.", + RelationGetQualifiedRelationName(pri->relation)))); + } + } +} /* * Given a list of tables that are going to be added to a publication, @@ -849,7 +925,7 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) char publish_generated_columns; AclResult aclresult; List *relations = NIL; - List *exceptrelations = NIL; + List *except_pubtables = NIL; List *schemaidlist = NIL; /* must have CREATE privilege on database */ @@ -936,16 +1012,16 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) /* Associate objects with the publication. */ ObjectsInPublicationToOids(stmt->pubobjects, pstate, &relations, - &exceptrelations, &schemaidlist); + &except_pubtables, &schemaidlist); if (stmt->for_all_tables) { /* Process EXCEPT table list */ - if (exceptrelations != NIL) + if (except_pubtables != NIL) { List *rels; - rels = OpenTableList(exceptrelations); + rels = OpenTableList(except_pubtables); PublicationAddTables(puboid, rels, true, NULL); CloseTableList(rels); } @@ -959,6 +1035,8 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) } else if (!stmt->for_all_sequences) { + List *explicitrelids = NIL; + /* FOR TABLES IN SCHEMA requires superuser */ if (schemaidlist != NIL && !superuser()) ereport(ERROR, @@ -977,6 +1055,19 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) schemaidlist != NIL, publish_via_partition_root); + /* + * Collect explicit table OIDs now, before we close the relation + * list, so that except-table validation below can check for + * contradictions without relying on a catalog scan that might not + * yet see the just-inserted rows. + */ + if (except_pubtables != NIL) + { + foreach_ptr(PublicationRelInfo, pri, rels) + explicitrelids = lappend_oid(explicitrelids, + RelationGetRelid(pri->relation)); + } + PublicationAddTables(puboid, rels, true, NULL); CloseTableList(rels); } @@ -989,6 +1080,26 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) */ LockSchemaList(schemaidlist); PublicationAddSchemas(puboid, schemaidlist, true, NULL); + + if (except_pubtables != NIL) + { + List *except_rels; + + except_rels = OpenTableList(except_pubtables); + + /* + * Validate that each excluded table is not also in the + * explicit table list (which would be contradictory), and + * that no explicit partition's root is in the except list. + * Use the in-memory explicitrelids collected above rather + * than re-reading the catalog, which may not yet see the + * just-inserted rows. + */ + CheckExceptNotInTableList(except_rels, explicitrelids); + + PublicationAddTables(puboid, except_rels, true, NULL); + CloseTableList(except_rels); + } } } @@ -1683,12 +1794,12 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) else { List *relations = NIL; - List *exceptrelations = NIL; + List *except_pubtables = NIL; List *schemaidlist = NIL; Oid pubid = pubform->oid; ObjectsInPublicationToOids(stmt->pubobjects, pstate, &relations, - &exceptrelations, &schemaidlist); + &except_pubtables, &schemaidlist); CheckAlterPublication(stmt, tup, relations, schemaidlist); @@ -1711,7 +1822,7 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) errmsg("publication \"%s\" does not exist", stmt->pubname)); - relations = list_concat(relations, exceptrelations); + relations = list_concat(relations, except_pubtables); AlterPublicationTables(stmt, tup, relations, pstate->p_sourcetext, schemaidlist != NIL); AlterPublicationSchemas(stmt, tup, schemaidlist); @@ -1829,6 +1940,62 @@ RemovePublicationSchemaById(Oid psoid) table_close(rel, RowExclusiveLock); } +/* + * Remove any EXCEPT clause entries for a relation from schema publications. + * Called when a table changes schema (ALTER TABLE ... SET SCHEMA), so that + * a schema-scoped exclusion does not silently follow the table to its new + * schema. + */ +void +RemoveSchemaPubExceptForRel(Oid relid, Oid oldNspOid, Oid newNspOid) +{ + List *pubids; + + /* + * If the table is not actually moving to a different schema (no-op ALTER + * TABLE ... SET SCHEMA <current_schema>), there is nothing to do. + */ + if (oldNspOid == newNspOid) + return; + + pubids = GetRelationExcludedPublications(relid); + + foreach_oid(pubid, pubids) + { + Oid proid; + + /* + * This problem does not apply to FOR ALL TABLES publications, because + * their EXCEPT clause is publication-scoped, not schema-scoped: the + * exclusion should persist regardless of what schema the table is in. + */ + if (!is_schema_publication(pubid)) + continue; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddress obj; + + ObjectAddressSet(obj, PublicationRelRelationId, proid); + + ereport(DEBUG2, + errmsg_internal("auto-remove exclusion of table \"%s.%s\" from publication \"%s\": table moved to schema \"%s\"", + get_namespace_name(oldNspOid), + get_rel_name(relid), + get_publication_name(pubid, false), + get_namespace_name(newNspOid))); + + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + list_free(pubids); +} + /* * Open relations specified by a PublicationTable list. * The returned tables are locked in ShareUpdateExclusiveLock mode in order to diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d8e1959ee6f 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -63,6 +63,7 @@ #include "commands/event_trigger.h" #include "commands/extension.h" #include "commands/repack.h" +#include "commands/publicationcmds.h" #include "commands/sequence.h" #include "commands/tablecmds.h" #include "commands/tablespace.h" @@ -19745,6 +19746,16 @@ AlterTableNamespaceInternal(Relation rel, Oid oldNspOid, Oid nspOid, AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid, false, objsMoved); + /* + * Remove any EXCEPT clause entries for this relation from schema + * publications. A schema-scoped exclusion is no longer meaningful once + * the table moves to a different schema. + */ + if (rel->rd_rel->relkind == RELKIND_RELATION || + rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE) + RemoveSchemaPubExceptForRel(RelationGetRelid(rel), oldNspOid, + nspOid); + table_close(classRel, RowExclusiveLock); } diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y index 9e05a314707..2a8f999d586 100644 --- a/src/backend/parser/gram.y +++ b/src/backend/parser/gram.y @@ -58,6 +58,7 @@ #include "nodes/makefuncs.h" #include "nodes/nodeFuncs.h" #include "parser/parser.h" +#include "utils/builtins.h" #include "utils/datetime.h" #include "utils/xml.h" @@ -11283,7 +11284,7 @@ AlterOwnerStmt: ALTER AGGREGATE aggregate_with_argtypes OWNER TO RoleSpec * pub_obj is one of: * * TABLE table [, ...] - * TABLES IN SCHEMA schema [, ...] + * TABLES IN SCHEMA schema [EXCEPT (TABLE table [, ...] )] [, ...] * *****************************************************************************/ @@ -11343,23 +11344,26 @@ PublicationObjSpec: $$->pubtable->columns = $3; $$->pubtable->whereClause = $4; } - | TABLES IN_P SCHEMA ColId + | TABLES IN_P SCHEMA ColId opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_SCHEMA; $$->name = $4; + $$->except_tables = $5; $$->location = @4; } - | TABLES IN_P SCHEMA CURRENT_SCHEMA + | TABLES IN_P SCHEMA CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_CUR_SCHEMA; + $$->except_tables = $5; $$->location = @4; } - | ColId opt_column_list OptWhereClause + | ColId opt_column_list OptWhereClause opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $4; /* * If either a row filter or column list is specified, create * a PublicationTable object. @@ -11403,10 +11407,11 @@ PublicationObjSpec: $$->pubtable->columns = $2; $$->pubtable->whereClause = $3; } - | CURRENT_SCHEMA + | CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $2; $$->location = @1; } ; @@ -20873,6 +20878,8 @@ preprocess_pub_all_objtype_list(List *all_objects_list, List **pubobjects, /* * Process pubobjspec_list to check for errors in any of the objects and * convert PUBLICATIONOBJ_CONTINUATION into appropriate PublicationObjSpecType. + * Also flattens except_tables from TABLES IN SCHEMA nodes into the list so + * that ObjectsInPublicationToOids() sees them as top-level EXCEPT_TABLE entries. */ static void preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) @@ -20901,6 +20908,13 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLE) { + /* EXCEPT is not valid for table objects */ + if (pubobj->except_tables != NIL) + ereport(ERROR, + errcode(ERRCODE_SYNTAX_ERROR), + errmsg("EXCEPT is not allowed for TABLE publication objects"), + parser_errposition(pubobj->location)); + /* relation name or pubtable must be set for this type of object */ if (!pubobj->name && !pubobj->pubtable) ereport(ERROR, @@ -20949,6 +20963,36 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) errcode(ERRCODE_SYNTAX_ERROR), errmsg("invalid schema name"), parser_errposition(pubobj->location)); + + /* + * For TABLES_IN_SCHEMA, qualify unqualified EXCEPT table names + * with the parent schema and reject cross-schema entries at parse + * time, then flatten into the top-level list. + * + * For TABLES_IN_CUR_SCHEMA the schema name is not yet known, so + * skip both steps here; ObjectsInPublicationToOids() will + * qualify names and validate schema membership at execution time. + */ + if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLES_IN_SCHEMA) + { + foreach_ptr(PublicationObjSpec, eobj, pubobj->except_tables) + { + const char *eobj_schemaname = eobj->pubtable->relation->schemaname; + const char *eobj_relname = eobj->pubtable->relation->relname; + + if (eobj_schemaname == NULL) + eobj->pubtable->relation->schemaname = pubobj->name; + else if (strcmp(eobj_schemaname, pubobj->name) != 0) + ereport(ERROR, + errcode(ERRCODE_INVALID_OBJECT_DEFINITION), + errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", + quote_qualified_identifier(eobj_schemaname, eobj_relname), + pubobj->name), + parser_errposition(eobj->location)); + } + pubobjspec_list = list_concat(pubobjspec_list, pubobj->except_tables); + pubobj->except_tables = NIL; + } } prevobjtype = pubobj->pubobjtype; diff --git a/src/backend/replication/pgoutput/pgoutput.c b/src/backend/replication/pgoutput/pgoutput.c index 4ecfcbff7ab..8d5a534ed1a 100644 --- a/src/backend/replication/pgoutput/pgoutput.c +++ b/src/backend/replication/pgoutput/pgoutput.c @@ -2265,6 +2265,11 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) int level; List *ancestors = get_partition_ancestors(relid); + /* + * GetTopMostAncestorInPublication() itself skips + * schema-based ancestor matches when the partition root + * is excluded via this publication's EXCEPT clause. + */ ancestor = GetTopMostAncestorInPublication(pub->oid, ancestors, &level); @@ -2280,10 +2285,45 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) } } - if (list_member_oid(pubids, pub->oid) || - list_member_oid(schemaPubids, pub->oid) || - ancestor_published) + if (list_member_oid(pubids, pub->oid) || ancestor_published) publish = true; + else if (list_member_oid(schemaPubids, pub->oid)) + { + Oid root_relid; + HeapTuple tup; + bool is_except = false; + + /* + * schemaPubids is relid's own schema, independent of the + * ancestor walk above -- a partition can live in a + * different schema than its root. Still need to check + * for exclusion here, using the top-most ancestor since + * only a root (non-partition) table can appear in an + * EXCEPT clause. + */ + if (am_partition) + { + List *ancestors = get_partition_ancestors(relid); + + root_relid = llast_oid(ancestors); + list_free(ancestors); + } + else + root_relid = relid; + + tup = SearchSysCache2(PUBLICATIONRELMAP, + ObjectIdGetDatum(root_relid), + ObjectIdGetDatum(pub->oid)); + + if (HeapTupleIsValid(tup)) + { + is_except = ((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept; + ReleaseSysCache(tup); + } + + if (!is_except) + publish = true; + } } /* diff --git a/src/backend/utils/cache/relcache.c b/src/backend/utils/cache/relcache.c index fb4e042be8a..92ff89fa2a4 100644 --- a/src/backend/utils/cache/relcache.c +++ b/src/backend/utils/cache/relcache.c @@ -5845,16 +5845,29 @@ RelationBuildPublicationDesc(Relation relation, PublicationDesc *pubdesc) /* Fetch the publication membership info. */ puboids = GetRelationIncludedPublications(relid); schemaid = RelationGetNamespace(relation); - puboids = list_concat_unique_oid(puboids, GetSchemaPublications(schemaid)); if (relation->rd_rel->relispartition) { - Oid last_ancestor_relid; - - /* Add publications that the ancestors are in too. */ ancestors = get_partition_ancestors(relid); - last_ancestor_relid = llast_oid(ancestors); + exceptpuboids = GetRelationExcludedPublications(llast_oid(ancestors)); + } + else + exceptpuboids = GetRelationExcludedPublications(relid); + /* + * Subtract exceptpuboids from the schema-publication contribution so that + * a relation EXCEPT'd from a schema publication does not inherit that + * publication's pubactions. Without this filter, + * CheckCmdReplicaIdentity() would demand REPLICA IDENTITY for + * UPDATE/DELETE even on a explicitly excluded table. + */ + puboids = list_concat_unique_oid(puboids, + list_difference_oid(GetSchemaPublications(schemaid), + exceptpuboids)); + + if (relation->rd_rel->relispartition) + { + /* Add publications that the ancestors are in too. */ foreach(lc, ancestors) { Oid ancestor = lfirst_oid(lc); @@ -5863,23 +5876,9 @@ RelationBuildPublicationDesc(Relation relation, PublicationDesc *pubdesc) GetRelationIncludedPublications(ancestor)); schemaid = get_rel_namespace(ancestor); puboids = list_concat_unique_oid(puboids, - GetSchemaPublications(schemaid)); + list_difference_oid(GetSchemaPublications(schemaid), + exceptpuboids)); } - - /* - * Only the top-most ancestor can appear in the EXCEPT clause. - * Therefore, for a partition, exclusion must be evaluated at the - * top-most ancestor. - */ - exceptpuboids = GetRelationExcludedPublications(last_ancestor_relid); - } - else - { - /* - * For a regular table or a root partitioned table, check exclusion on - * table itself. - */ - exceptpuboids = GetRelationExcludedPublications(relid); } alltablespuboids = GetAllTablesPublications(); diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c index fef86b4cca3..72e8f58fc3e 100644 --- a/src/bin/psql/describe.c +++ b/src/bin/psql/describe.c @@ -6815,6 +6815,24 @@ describePublications(const char *pattern) if (!addFooterToPublicationDesc(&buf, _("Tables from schemas:"), true, &cont)) goto error_return; + + if (pset.sversion >= 190000) + { + /* + * Get tables in the EXCEPT clause for this schema + * publication. + */ + printfPQExpBuffer(&buf, + "SELECT concat(c.relnamespace::regnamespace, '.', c.relname)\n" + "FROM pg_catalog.pg_class c\n" + " JOIN pg_catalog.pg_publication_rel pr ON c.oid = pr.prrelid\n" + "WHERE pr.prpubid = '%s'\n" + " AND pr.prexcept\n" + "ORDER BY 1", pubid); + if (!addFooterToPublicationDesc(&buf, _("Except tables:"), + true, &cont)) + goto error_return; + } } } else diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index 49ea584cd4f..067168699f6 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -1065,6 +1065,24 @@ static const SchemaQuery Query_for_trigger_of_table = { "SELECT nspname FROM pg_catalog.pg_namespace "\ " WHERE nspname LIKE '%s'" +#define Query_for_list_of_tables_in_schema \ +"SELECT n.nspname || '.' || c.relname "\ +" FROM pg_catalog.pg_class c "\ +" JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "\ +" WHERE c.relkind IN (" CppAsString2(RELKIND_RELATION) ", " \ + CppAsString2(RELKIND_PARTITIONED_TABLE) ") "\ +" AND (n.nspname || '.' || c.relname) LIKE '%s' "\ +" AND n.nspname = '%s'" + +#define Query_for_list_of_tables_in_current_schema \ +"SELECT c.relname "\ +" FROM pg_catalog.pg_class c "\ +" JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "\ +" WHERE c.relkind IN (" CppAsString2(RELKIND_RELATION) ", " \ + CppAsString2(RELKIND_PARTITIONED_TABLE) ") "\ +" AND c.relname LIKE '%s' "\ +" AND n.nspname = pg_catalog.current_schema()" + /* Use COMPLETE_WITH_QUERY_VERBATIM with these queries for GUC names: */ #define Query_for_list_of_alter_system_set_vars \ "SELECT pg_catalog.lower(name) FROM pg_catalog.pg_settings "\ @@ -3774,8 +3792,21 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); - else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && (!ends_with(prev_wd, ','))) - COMPLETE_WITH("WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE", "WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* Complete "CREATE PUBLICATION <name> [...] WITH" */ else if (Matches("CREATE", "PUBLICATION", MatchAnyN, "WITH", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/include/commands/publicationcmds.h b/src/include/commands/publicationcmds.h index 4cf45c17cc5..fb1703aa675 100644 --- a/src/include/commands/publicationcmds.h +++ b/src/include/commands/publicationcmds.h @@ -27,6 +27,8 @@ extern void AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt); extern void RemovePublicationById(Oid pubid); extern void RemovePublicationRelById(Oid proid); extern void RemovePublicationSchemaById(Oid psoid); +extern void RemoveSchemaPubExceptForRel(Oid relid, Oid oldNspOid, + Oid newNspOid); extern ObjectAddress AlterPublicationOwner(const char *name, Oid newOwnerId); extern void AlterPublicationOwner_oid(Oid pubid, Oid newOwnerId); diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h index 77f69f94607..63abc0b6960 100644 --- a/src/include/nodes/parsenodes.h +++ b/src/include/nodes/parsenodes.h @@ -4532,6 +4532,8 @@ typedef struct PublicationObjSpec PublicationObjSpecType pubobjtype; /* type of this publication object */ char *name; PublicationTable *pubtable; + List *except_tables; /* tables specified in the EXCEPT clause (for + * TABLES IN SCHEMA) */ ParseLoc location; /* token location, or -1 if unknown */ } PublicationObjSpec; diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 29e54b214a0..0729e546116 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -270,6 +270,12 @@ CREATE PUBLICATION testpub_foralltables_excepttable2 FOR ALL TABLES EXCEPT (test ERROR: syntax error at or near "testpub_tbl1" LINE 1: ..._foralltables_excepttable2 FOR ALL TABLES EXCEPT (testpub_tb... ^ +-- fail - EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testpub_tbl3); +ERROR: EXCEPT is not allowed for TABLE publication objects +LINE 2: FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testp... + ^ --------------------------------------------- -- SET ALL TABLES/SEQUENCES --------------------------------------------- @@ -470,7 +476,154 @@ HINT: Change the publication's EXCEPT clause using ALTER PUBLICATION ... SET AL RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Create same-named tables in public to verify unqualified EXCEPT entries +-- are qualified with the named schema, not public +CREATE TABLE testpub_nopk (foo int, bar int); +CREATE TABLE testpub_tbl_s1 (a int primary key, b text); +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + Publication testpub_schema_except1 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- Exclude multiple tables using unqualified names; same-named tables exist in +-- public to confirm unqualified names resolve to pub_test, not public +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + Publication testpub_schema_except2 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_nopk" + "pub_test.testpub_tbl_s1" + +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testp... + ^ +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); +ERROR: table "pub_test.testpub_tbl_s1" in EXCEPT clause does not belong to schema "public" +LINE 2: ...R TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.t... + ^ +-- Multiple schemas each with their own EXCEPT clause +CREATE PUBLICATION testpub_schema_except_multi + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_schema_except_multi + Publication testpub_schema_except_multi + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- ALTER TABLE ... SET SCHEMA on a table excluded by a schema publication: +-- the schema-scoped exclusion is no longer meaningful once the table moves +-- out of its schema, so the exclusion is auto-removed. +CREATE PUBLICATION testpub_schema_except_setsch + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_schema_except_setsch + Publication testpub_schema_except_setsch + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s2" + +ALTER TABLE pub_test.testpub_tbl_s2 SET SCHEMA public; +\dRp+ testpub_schema_except_setsch + Publication testpub_schema_except_setsch + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + +DROP PUBLICATION testpub_schema_except_setsch; +-- Restore for further tests +ALTER TABLE public.testpub_tbl_s2 SET SCHEMA pub_test; +-- fail: table appears in both the explicit table list and the EXCEPT clause +CREATE PUBLICATION testpub_except_conflict + FOR TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot be both published and excluded +-- fail: nonexistent table in EXCEPT clause +CREATE PUBLICATION testpub_except_norel + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- fail: partition cannot appear in EXCEPT clause; only root tables are allowed +CREATE TABLE pub_test.testpub_parted_s (a int) PARTITION BY LIST (a); +CREATE TABLE pub_test.testpub_part_s PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (1); +CREATE PUBLICATION testpub_except_partition + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); +ERROR: cannot specify relation "pub_test.testpub_part_s" in the publication EXCEPT clause +DETAIL: This operation is not supported for individual partitions. +-- fail: partition still rejected from EXCEPT even when its own root is also +-- named in the same EXCEPT list +CREATE PUBLICATION testpub_except_partition_with_root + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s, TABLE pub_test.testpub_parted_s); +ERROR: cannot specify relation "pub_test.testpub_part_s" in the publication EXCEPT clause +DETAIL: This operation is not supported for individual partitions. +-- fail: TABLE keyword is required for the first entry in the EXCEPT clause +CREATE PUBLICATION testpub_except_nokw + FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +ERROR: syntax error at or near "testpub_nopk" +LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + ^ +-- fail: ADD TABLE for a partition is rejected when a partition ancestor +-- is currently in the publication's EXCEPT list. +CREATE PUBLICATION testpub_except_ancestor + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ALTER PUBLICATION testpub_except_ancestor ADD TABLE pub_test.testpub_part_s; +ERROR: cannot add partition "pub_test.testpub_part_s" to publication "testpub_except_ancestor" +DETAIL: Ancestor "pub_test.testpub_parted_s" of partition "pub_test.testpub_part_s" is currently listed in the EXCEPT clause of the publication. +HINT: Change EXCEPT list using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT. +DROP PUBLICATION testpub_except_ancestor; +-- fail: same contradiction (explicit partition + EXCEPT-ed ancestor), but +-- given in a single statement instead of two separate ones; the ancestor's +-- EXCEPT row doesn't exist in the catalog yet when the explicit partition is +-- validated, so this must be caught by comparing the in-memory lists +CREATE PUBLICATION testpub_except_ancestor_same_create + FOR TABLE pub_test.testpub_part_s, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ERROR: partition "pub_test.testpub_part_s" cannot be both published and excluded +DETAIL: Ancestor "pub_test.testpub_parted_s" is also being excluded by this same command. +-- Cleanup +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP TABLE pub_test.testpub_parted_s CASCADE; +DROP TABLE testpub_nopk, testpub_tbl_s1; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +--------------------------------------------- +-- Tests for publications with SEQUENCES +--------------------------------------------- CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; -- FOR ALL SEQUENCES @@ -1953,6 +2106,27 @@ ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b); ERROR: column specification not allowed for schema LINE 1: ...TION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b)... ^ +-- EXCEPT clause with CURRENT_SCHEMA: cross-schema entry must be rejected +SET search_path = pub_test1; +-- qualified name from wrong schema -> error +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.tbl1); +ERROR: table "pub_test2.tbl1" in EXCEPT clause does not belong to schema "pub_test1" +-- unqualified name implicitly qualified with current schema (pub_test1.tbl) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl); +RESET client_min_messages; +\dRp+ testpub_cursch_except + Publication testpub_cursch_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test1" +Except tables: + "pub_test1.tbl" + +DROP PUBLICATION testpub_cursch_except; +RESET search_path; -- cleanup pub_test1 schema for invalidation tests ALTER PUBLICATION testpub2_forschema DROP TABLES IN SCHEMA pub_test1; DROP PUBLICATION testpub3_forschema, testpub4_forschema, testpub5_forschema, testpub6_forschema, testpub_fortable; @@ -2304,6 +2478,7 @@ DROP ROLE regress_publication_user_dummy; -- Test pg_get_publication_tables(text[], oid) function CREATE SCHEMA gpt_test_sch; CREATE TABLE gpt_test_sch.tbl_sch (id int); +CREATE TABLE gpt_test_sch.tbl_sch2 (id int); CREATE TABLE tbl_normal (id int); CREATE TABLE tbl_parent (id1 int, id2 int, id3 int) PARTITION BY RANGE (id1); CREATE TABLE tbl_part1 PARTITION OF tbl_parent FOR VALUES FROM (1) TO (10); @@ -2314,6 +2489,7 @@ CREATE PUBLICATION pub_all_no_viaroot FOR ALL TABLES WITH (publish_via_partition CREATE PUBLICATION pub_all_except FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = true); CREATE PUBLICATION pub_all_except_no_viaroot FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_schema FOR TABLES IN SCHEMA gpt_test_sch; +CREATE PUBLICATION pub_schema_except FOR TABLES IN SCHEMA gpt_test_sch EXCEPT (TABLE gpt_test_sch.tbl_sch); CREATE PUBLICATION pub_normal FOR TABLE tbl_normal WHERE (id < 10); CREATE PUBLICATION pub_part_leaf FOR TABLE tbl_part1 WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_part_parent FOR TABLE tbl_parent (id1, id2) WHERE (id1 = 10) WITH (publish_via_partition_root = true); @@ -2465,6 +2641,44 @@ SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_part1'); -- no r ---------+---------+-------+------ (0 rows) +-- test for EXCEPT clause with schema publication +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch'); -- no result (excluded) + pubname | relname | attrs | qual +---------+---------+-------+------ +(0 rows) + +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch2'); -- one row (included via schema) + pubname | relname | attrs | qual +-------------------+----------+-------+------ + pub_schema_except | tbl_sch2 | 1 | +(1 row) + +-- test for EXCEPT clause with schema publication, where the excluded root's +-- partition lives in a different schema that is separately, fully included +-- (no EXCEPT) in the same publication. The root's exclusion must cascade to +-- the partition regardless of the partition's own schema membership. +CREATE SCHEMA gpt_cross_sch1; +CREATE SCHEMA gpt_cross_sch2; +CREATE TABLE gpt_cross_sch1.croot (id int) PARTITION BY RANGE (id); +CREATE TABLE gpt_cross_sch2.cpart1 PARTITION OF gpt_cross_sch1.croot FOR VALUES FROM (1) TO (10); +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION pub_cross_schema_except FOR TABLES IN SCHEMA gpt_cross_sch1 EXCEPT (TABLE gpt_cross_sch1.croot), TABLES IN SCHEMA gpt_cross_sch2; +RESET client_min_messages; +SELECT * FROM test_gpt(ARRAY['pub_cross_schema_except'], 'gpt_cross_sch1.croot'); -- no result (excluded) + pubname | relname | attrs | qual +---------+---------+-------+------ +(0 rows) + +-- no result (excluded via cascading root exclusion, even though cpart1's own +-- schema gpt_cross_sch2 is separately, fully included with no EXCEPT) +SELECT * FROM test_gpt(ARRAY['pub_cross_schema_except'], 'gpt_cross_sch2.cpart1'); + pubname | relname | attrs | qual +---------+---------+-------+------ +(0 rows) + +DROP PUBLICATION pub_cross_schema_except; +DROP TABLE gpt_cross_sch2.cpart1, gpt_cross_sch1.croot; +DROP SCHEMA gpt_cross_sch1, gpt_cross_sch2; -- two rows with different row filter SELECT * FROM test_gpt(ARRAY['pub_all', 'pub_normal'], 'tbl_normal'); pubname | relname | attrs | qual @@ -2517,6 +2731,7 @@ DROP PUBLICATION pub_all_no_viaroot; DROP PUBLICATION pub_all_except; DROP PUBLICATION pub_all_except_no_viaroot; DROP PUBLICATION pub_schema; +DROP PUBLICATION pub_schema_except; DROP PUBLICATION pub_normal; DROP PUBLICATION pub_part_leaf; DROP PUBLICATION pub_part_parent; @@ -2525,7 +2740,9 @@ DROP PUBLICATION pub_part_parent_child; DROP VIEW gpt_test_view; DROP TABLE tbl_normal, tbl_parent, tbl_part1; DROP SCHEMA gpt_test_sch CASCADE; -NOTICE: drop cascades to table gpt_test_sch.tbl_sch +NOTICE: drop cascades to 2 other objects +DETAIL: drop cascades to table gpt_test_sch.tbl_sch +drop cascades to table gpt_test_sch.tbl_sch2 -- stage objects for pg_dump tests CREATE SCHEMA pubme CREATE TABLE t0 (c int, d int) CREATE TABLE t1 (c int); CREATE SCHEMA pubme2 CREATE TABLE t0 (c int, d int); diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 041e14a4de6..055b9e97dc1 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -123,6 +123,9 @@ CREATE PUBLICATION testpub_foralltables_excepttable1 FOR ALL TABLES EXCEPT (TABL \d testpub_tbl1 -- fail - first table in the EXCEPT list should use TABLE keyword CREATE PUBLICATION testpub_foralltables_excepttable2 FOR ALL TABLES EXCEPT (testpub_tbl1, testpub_tbl2); +-- fail - EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testpub_tbl3); --------------------------------------------- -- SET ALL TABLES/SEQUENCES @@ -220,7 +223,103 @@ RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Create same-named tables in public to verify unqualified EXCEPT entries +-- are qualified with the named schema, not public +CREATE TABLE testpub_nopk (foo int, bar int); +CREATE TABLE testpub_tbl_s1 (a int primary key, b text); + +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + +-- Exclude multiple tables using unqualified names; same-named tables exist in +-- public to confirm unqualified names resolve to pub_test, not public +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); + +-- Multiple schemas each with their own EXCEPT clause +CREATE PUBLICATION testpub_schema_except_multi + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_schema_except_multi + +-- ALTER TABLE ... SET SCHEMA on a table excluded by a schema publication: +-- the schema-scoped exclusion is no longer meaningful once the table moves +-- out of its schema, so the exclusion is auto-removed. +CREATE PUBLICATION testpub_schema_except_setsch + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_schema_except_setsch +ALTER TABLE pub_test.testpub_tbl_s2 SET SCHEMA public; +\dRp+ testpub_schema_except_setsch +DROP PUBLICATION testpub_schema_except_setsch; +-- Restore for further tests +ALTER TABLE public.testpub_tbl_s2 SET SCHEMA pub_test; + +-- fail: table appears in both the explicit table list and the EXCEPT clause +CREATE PUBLICATION testpub_except_conflict + FOR TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: nonexistent table in EXCEPT clause +CREATE PUBLICATION testpub_except_norel + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- fail: partition cannot appear in EXCEPT clause; only root tables are allowed +CREATE TABLE pub_test.testpub_parted_s (a int) PARTITION BY LIST (a); +CREATE TABLE pub_test.testpub_part_s PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (1); +CREATE PUBLICATION testpub_except_partition + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); + +-- fail: partition still rejected from EXCEPT even when its own root is also +-- named in the same EXCEPT list +CREATE PUBLICATION testpub_except_partition_with_root + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s, TABLE pub_test.testpub_parted_s); + +-- fail: TABLE keyword is required for the first entry in the EXCEPT clause +CREATE PUBLICATION testpub_except_nokw + FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + +-- fail: ADD TABLE for a partition is rejected when a partition ancestor +-- is currently in the publication's EXCEPT list. +CREATE PUBLICATION testpub_except_ancestor + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ALTER PUBLICATION testpub_except_ancestor ADD TABLE pub_test.testpub_part_s; +DROP PUBLICATION testpub_except_ancestor; + +-- fail: same contradiction (explicit partition + EXCEPT-ed ancestor), but +-- given in a single statement instead of two separate ones; the ancestor's +-- EXCEPT row doesn't exist in the catalog yet when the explicit partition is +-- validated, so this must be caught by comparing the in-memory lists +CREATE PUBLICATION testpub_except_ancestor_same_create + FOR TABLE pub_test.testpub_part_s, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); + +-- Cleanup +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP TABLE pub_test.testpub_parted_s CASCADE; +DROP TABLE testpub_nopk, testpub_tbl_s1; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; + +--------------------------------------------- +-- Tests for publications with SEQUENCES +--------------------------------------------- CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; @@ -1189,6 +1288,18 @@ ALTER PUBLICATION testpub1_forschema SET TABLES IN SCHEMA pub_test1, pub_test1; ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo (a, b); ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b); +-- EXCEPT clause with CURRENT_SCHEMA: cross-schema entry must be rejected +SET search_path = pub_test1; +-- qualified name from wrong schema -> error +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.tbl1); +-- unqualified name implicitly qualified with current schema (pub_test1.tbl) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl); +RESET client_min_messages; +\dRp+ testpub_cursch_except +DROP PUBLICATION testpub_cursch_except; +RESET search_path; + -- cleanup pub_test1 schema for invalidation tests ALTER PUBLICATION testpub2_forschema DROP TABLES IN SCHEMA pub_test1; DROP PUBLICATION testpub3_forschema, testpub4_forschema, testpub5_forschema, testpub6_forschema, testpub_fortable; @@ -1443,6 +1554,7 @@ DROP ROLE regress_publication_user_dummy; -- Test pg_get_publication_tables(text[], oid) function CREATE SCHEMA gpt_test_sch; CREATE TABLE gpt_test_sch.tbl_sch (id int); +CREATE TABLE gpt_test_sch.tbl_sch2 (id int); CREATE TABLE tbl_normal (id int); CREATE TABLE tbl_parent (id1 int, id2 int, id3 int) PARTITION BY RANGE (id1); CREATE TABLE tbl_part1 PARTITION OF tbl_parent FOR VALUES FROM (1) TO (10); @@ -1454,6 +1566,7 @@ CREATE PUBLICATION pub_all_no_viaroot FOR ALL TABLES WITH (publish_via_partition CREATE PUBLICATION pub_all_except FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = true); CREATE PUBLICATION pub_all_except_no_viaroot FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_schema FOR TABLES IN SCHEMA gpt_test_sch; +CREATE PUBLICATION pub_schema_except FOR TABLES IN SCHEMA gpt_test_sch EXCEPT (TABLE gpt_test_sch.tbl_sch); CREATE PUBLICATION pub_normal FOR TABLE tbl_normal WHERE (id < 10); CREATE PUBLICATION pub_part_leaf FOR TABLE tbl_part1 WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_part_parent FOR TABLE tbl_parent (id1, id2) WHERE (id1 = 10) WITH (publish_via_partition_root = true); @@ -1510,6 +1623,32 @@ SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'gpt_test_sch.tbl_sch SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_parent'); -- no result (excluded) SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_part1'); -- no result +-- test for EXCEPT clause with schema publication +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch'); -- no result (excluded) +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch2'); -- one row (included via schema) + +-- test for EXCEPT clause with schema publication, where the excluded root's +-- partition lives in a different schema that is separately, fully included +-- (no EXCEPT) in the same publication. The root's exclusion must cascade to +-- the partition regardless of the partition's own schema membership. +CREATE SCHEMA gpt_cross_sch1; +CREATE SCHEMA gpt_cross_sch2; +CREATE TABLE gpt_cross_sch1.croot (id int) PARTITION BY RANGE (id); +CREATE TABLE gpt_cross_sch2.cpart1 PARTITION OF gpt_cross_sch1.croot FOR VALUES FROM (1) TO (10); + +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION pub_cross_schema_except FOR TABLES IN SCHEMA gpt_cross_sch1 EXCEPT (TABLE gpt_cross_sch1.croot), TABLES IN SCHEMA gpt_cross_sch2; +RESET client_min_messages; + +SELECT * FROM test_gpt(ARRAY['pub_cross_schema_except'], 'gpt_cross_sch1.croot'); -- no result (excluded) +-- no result (excluded via cascading root exclusion, even though cpart1's own +-- schema gpt_cross_sch2 is separately, fully included with no EXCEPT) +SELECT * FROM test_gpt(ARRAY['pub_cross_schema_except'], 'gpt_cross_sch2.cpart1'); + +DROP PUBLICATION pub_cross_schema_except; +DROP TABLE gpt_cross_sch2.cpart1, gpt_cross_sch1.croot; +DROP SCHEMA gpt_cross_sch1, gpt_cross_sch2; + -- two rows with different row filter SELECT * FROM test_gpt(ARRAY['pub_all', 'pub_normal'], 'tbl_normal'); @@ -1538,6 +1677,7 @@ DROP PUBLICATION pub_all_no_viaroot; DROP PUBLICATION pub_all_except; DROP PUBLICATION pub_all_except_no_viaroot; DROP PUBLICATION pub_schema; +DROP PUBLICATION pub_schema_except; DROP PUBLICATION pub_normal; DROP PUBLICATION pub_part_leaf; DROP PUBLICATION pub_part_parent; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 8c58d282eee..e9bca3554b1 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -24,14 +24,17 @@ my $result; sub test_except_root_partition { - my ($pubviaroot) = @_; + my ($pubviaroot, $pubsql) = @_; + $pubsql //= + "CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1)"; + $pubsql .= " WITH (publish_via_partition_root = $pubviaroot)"; # If the root partitioned table is in the EXCEPT clause, all its # partitions are excluded from publication, regardless of the # publish_via_partition_root setting. $node_publisher->safe_psql( 'postgres', qq( - CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1) WITH (publish_via_partition_root = $pubviaroot); + $pubsql; INSERT INTO root1 VALUES (1), (101); )); $node_subscriber->safe_psql('postgres', @@ -223,6 +226,206 @@ $node_subscriber->safe_psql( test_except_root_partition('false'); test_except_root_partition('true'); +# Same validation using TABLES IN SCHEMA instead of FOR ALL TABLES. +my $schema_pub = + "CREATE PUBLICATION tap_pub_part FOR TABLES IN SCHEMA public EXCEPT (TABLE public.root1)"; +test_except_root_partition('false', $schema_pub); +test_except_root_partition('true', $schema_pub); + +# ============================================ +# EXCEPT test cases for TABLES IN SCHEMA +# ============================================ + +# Create a dedicated schema with two tables: one to be published and one to be +# excluded. Also create inherited tables to verify ONLY semantics. +$node_publisher->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_published AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.tab_excluded AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.parent (a int); + CREATE TABLE sch1.child (b int) INHERITS (sch1.parent); +)); + +$node_subscriber->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_published (a int); + CREATE TABLE sch1.tab_excluded (a int); + CREATE TABLE sch1.parent (a int); + CREATE TABLE sch1.child (b int) INHERITS (sch1.parent); +)); + +# Basic test: initial sync respects EXCEPT. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_excluded)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: initial sync copies included table'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: initial sync skips excluded table'); + +# DML: only the included table should be replicated. +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (6); + INSERT INTO sch1.tab_excluded VALUES (6); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(6), + 'TABLES IN SCHEMA EXCEPT: DML on included table is replicated'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: DML on excluded table is not replicated'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Inherited tables: excluding the parent (without ONLY) also excludes the child. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.parent)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.child VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.child"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: excluding parent (without ONLY) also excludes child' +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Test that EXCEPT (TABLE ONLY parent) excludes only the parent itself, not its +# child. Truncate child first so rows from the previous test are not copied by +# the initial table sync of the next subscription. +$node_publisher->safe_psql('postgres', 'TRUNCATE sch1.child'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE sch1.child'); +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE ONLY sch1.parent)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.child VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.child"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: ONLY parent in EXCEPT does not exclude child'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Cleanup schema tables before the multi-publication section. +$node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); +$node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); + +# ============================================ +# EXCEPT test cases for TABLES IN SCHEMA with a cross-schema partition +# ============================================ + +# A partition can live in a different schema than its partitioned root. If +# the root is excluded via EXCEPT under its own schema's clause, the +# exclusion must cascade to all its partitions, even when the partition's +# own schema is separately, fully included (no EXCEPT) in the same +# publication. +$node_publisher->safe_psql( + 'postgres', qq( + CREATE SCHEMA csch1; + CREATE SCHEMA csch2; + CREATE TABLE csch1.croot(a int) PARTITION BY RANGE(a); + CREATE TABLE csch2.cpart1 PARTITION OF csch1.croot FOR VALUES FROM (0) TO (100); + INSERT INTO csch1.croot VALUES (generate_series(1,5)); +)); + +$node_subscriber->safe_psql( + 'postgres', qq( + CREATE SCHEMA csch1; + CREATE SCHEMA csch2; + CREATE TABLE csch1.croot(a int); + CREATE TABLE csch2.cpart1(a int); +)); + +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION cross_sch_pub FOR TABLES IN SCHEMA csch1 EXCEPT (TABLE csch1.croot), TABLES IN SCHEMA csch2" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION cross_sch_sub CONNECTION '$publisher_connstr' PUBLICATION cross_sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'cross_sch_sub'); + +# Baseline: the root itself, pre-populated with rows before the subscription +# was created, is excluded by its own schema's EXCEPT clause -- initial sync +# must not have copied it. +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM csch1.croot"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: cross-schema partition root is excluded by initial sync' +); + +# Regression case: the partition's own schema (csch2) is separately, fully +# included with no EXCEPT, but the root's exclusion must still cascade to it +# -- initial sync must not have copied the pre-existing rows routed into this +# partition via the root. +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM csch2.cpart1"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: cross-schema partition is excluded by initial sync via cascading root exclusion' +); + +# Insert distinct, identifiable data directly into the partition and verify +# it is not replicated either. +$node_publisher->safe_psql('postgres', + "INSERT INTO csch2.cpart1 VALUES (generate_series(1,5))"); +$node_publisher->wait_for_catchup('cross_sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM csch1.croot"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: cross-schema partition root remains excluded after DML' +); +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM csch2.cpart1"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: cross-schema partition remains excluded after DML via cascading root exclusion' +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION cross_sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION cross_sch_pub'); +$node_publisher->safe_psql('postgres', 'DROP SCHEMA csch1, csch2 CASCADE'); +$node_subscriber->safe_psql('postgres', 'DROP SCHEMA csch1, csch2 CASCADE'); + # ============================================ # Test when a subscription is subscribing to multiple publications # ============================================ @@ -254,6 +457,7 @@ $node_publisher->safe_psql( DROP PUBLICATION tap_pub2; TRUNCATE tab1; )); +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_subscriber->safe_psql('postgres', qq(TRUNCATE tab1)); # OK when a table is excluded by pub1 EXCEPT clause, but it is included by pub2 -- 2.50.1 (Apple Git-155)
v20-0002-Restrict-conflicting-EXCEPT-lists-in-multi-schem.patch (application/octet-stream, 15.0K) download From 34112dd23e62fae82fad9e97ba677cc2c5ab6de7 Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Wed, 8 Jul 2026 15:07:22 +0530 Subject: [PATCH v20 2/5] Restrict conflicting EXCEPT lists in multi-schema publications Add ProcessSchemaExceptTables() to qualify each mention's EXCEPT entries, build a sorted signature per schema OID, and compare it against any prior mention of the same schema in the same statement, erroring on a mismatch. --- src/backend/commands/publicationcmds.c | 103 +++++++++++++++------- src/backend/parser/gram.y | 36 +------- src/test/regress/expected/publication.out | 38 ++++++++ src/test/regress/sql/publication.sql | 31 +++++++ 4 files changed, 145 insertions(+), 63 deletions(-) diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 9a922a6dcc3..0c3c905f7ea 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -73,6 +73,11 @@ static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); static char defGetGeneratedColsOption(DefElem *def); static void CheckExceptNotInTableList(List *except_rels, List *explicitrelids); +static void ProcessSchemaExceptTables(Oid schemaid, const char *schema_name, + List *except_tables, ParseState *pstate, + bool schema_repeated, + List **schemas_with_except, + List **except_pubtables); static void @@ -177,6 +182,57 @@ parse_publication_options(ParseState *pstate, } } +/* + * Qualify unqualified EXCEPT table names with schema_name, reject entries + * explicitly qualified with a different schema, and append the (now + * qualified) tables to *except_pubtables. + * + * Also rejects a repeated mention of the same schema in the same TABLES IN + * SCHEMA list if either mention specifies a non-empty EXCEPT list, without + * checking whether the two EXCEPT lists actually name the same tables. This + * mirrors OpenTableList()'s handling of repeated tables with column lists + * (e.g. "FOR TABLE t1(a), t1(a)" is rejected even though the lists match): + * two mentions of the same schema wouldn't have a well-defined single + * EXCEPT list to enforce, so it's rejected as conflicting or redundant + * rather than silently unioned or compared for equivalence. + * *schemas_with_except accumulates the OIDs of schemas already seen with a + * non-empty EXCEPT list in this statement. + */ +static void +ProcessSchemaExceptTables(Oid schemaid, const char *schema_name, + List *except_tables, ParseState *pstate, + bool schema_repeated, List **schemas_with_except, + List **except_pubtables) +{ + if (schema_repeated && + (except_tables != NIL || list_member_oid(*schemas_with_except, schemaid))) + ereport(ERROR, + errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("conflicting or redundant EXCEPT lists for schema \"%s\"", + schema_name)); + + if (except_tables != NIL) + *schemas_with_except = lappend_oid(*schemas_with_except, schemaid); + + foreach_ptr(PublicationObjSpec, eobj, except_tables) + { + const char *eobj_schemaname = eobj->pubtable->relation->schemaname; + const char *eobj_relname = eobj->pubtable->relation->relname; + + if (eobj_schemaname == NULL) + eobj->pubtable->relation->schemaname = pstrdup(schema_name); + else if (strcmp(eobj_schemaname, schema_name) != 0) + ereport(ERROR, + errcode(ERRCODE_INVALID_OBJECT_DEFINITION), + errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", + quote_qualified_identifier(eobj_schemaname, eobj_relname), + schema_name), + parser_errposition(pstate, eobj->location)); + + *except_pubtables = lappend(*except_pubtables, eobj->pubtable); + } +} + /* * Convert the PublicationObjSpecType list into schema oid list and * PublicationTable list. @@ -187,6 +243,7 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, { ListCell *cell; PublicationObjSpec *pubobj; + List *schemas_with_except = NIL; if (!pubobjspec_list) return; @@ -194,7 +251,9 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, foreach(cell, pubobjspec_list) { Oid schemaid; + char *schema_name; List *search_path; + bool schema_repeated; pubobj = (PublicationObjSpec *) lfirst(cell); @@ -210,9 +269,16 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, break; case PUBLICATIONOBJ_TABLES_IN_SCHEMA: schemaid = get_namespace_oid(pubobj->name, false); + schema_name = pubobj->name; + schema_repeated = list_member_oid(*schemas, schemaid); /* Filter out duplicates if user specifies "sch1, sch1" */ *schemas = list_append_unique_oid(*schemas, schemaid); + + ProcessSchemaExceptTables(schemaid, schema_name, + pubobj->except_tables, pstate, + schema_repeated, &schemas_with_except, + except_pubtables); break; case PUBLICATIONOBJ_TABLES_IN_CUR_SCHEMA: search_path = fetch_search_path(false); @@ -223,41 +289,16 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, schemaid = linitial_oid(search_path); list_free(search_path); + schema_name = get_namespace_name(schemaid); + schema_repeated = list_member_oid(*schemas, schemaid); /* Filter out duplicates if user specifies "sch1, sch1" */ *schemas = list_append_unique_oid(*schemas, schemaid); - /* - * Qualify unqualified EXCEPT table names with the resolved - * current schema and reject any explicitly cross-schema - * entries. This mirrors the parse-time handling done for - * TABLES_IN_SCHEMA in preprocess_pubobj_list(), deferred here - * because CURRENT_SCHEMA is not known until execution time. - */ - if (pubobj->except_tables != NIL) - { - char *cur_schema_name = get_namespace_name(schemaid); - - foreach_ptr(PublicationObjSpec, eobj, pubobj->except_tables) - { - const char *eobj_schemaname = - eobj->pubtable->relation->schemaname; - const char *eobj_relname = - eobj->pubtable->relation->relname; - - if (eobj_schemaname == NULL) - eobj->pubtable->relation->schemaname = cur_schema_name; - else if (strcmp(eobj_schemaname, cur_schema_name) != 0) - ereport(ERROR, - errcode(ERRCODE_INVALID_OBJECT_DEFINITION), - errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", - quote_qualified_identifier(eobj_schemaname, eobj_relname), - cur_schema_name)); - - *except_pubtables = lappend(*except_pubtables, - eobj->pubtable); - } - } + ProcessSchemaExceptTables(schemaid, schema_name, + pubobj->except_tables, pstate, + schema_repeated, &schemas_with_except, + except_pubtables); break; default: /* shouldn't happen */ diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y index 2a8f999d586..437416f7c96 100644 --- a/src/backend/parser/gram.y +++ b/src/backend/parser/gram.y @@ -20878,8 +20878,10 @@ preprocess_pub_all_objtype_list(List *all_objects_list, List **pubobjects, /* * Process pubobjspec_list to check for errors in any of the objects and * convert PUBLICATIONOBJ_CONTINUATION into appropriate PublicationObjSpecType. - * Also flattens except_tables from TABLES IN SCHEMA nodes into the list so - * that ObjectsInPublicationToOids() sees them as top-level EXCEPT_TABLE entries. + * The except_tables attached to TABLES IN SCHEMA nodes are left in place here; + * ObjectsInPublicationToOids() qualifies their names, validates schema + * membership, and merges the qualified tables into its except_pubtables + * output list once the schema OID is known. */ static void preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) @@ -20963,36 +20965,6 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) errcode(ERRCODE_SYNTAX_ERROR), errmsg("invalid schema name"), parser_errposition(pubobj->location)); - - /* - * For TABLES_IN_SCHEMA, qualify unqualified EXCEPT table names - * with the parent schema and reject cross-schema entries at parse - * time, then flatten into the top-level list. - * - * For TABLES_IN_CUR_SCHEMA the schema name is not yet known, so - * skip both steps here; ObjectsInPublicationToOids() will - * qualify names and validate schema membership at execution time. - */ - if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLES_IN_SCHEMA) - { - foreach_ptr(PublicationObjSpec, eobj, pubobj->except_tables) - { - const char *eobj_schemaname = eobj->pubtable->relation->schemaname; - const char *eobj_relname = eobj->pubtable->relation->relname; - - if (eobj_schemaname == NULL) - eobj->pubtable->relation->schemaname = pubobj->name; - else if (strcmp(eobj_schemaname, pubobj->name) != 0) - ereport(ERROR, - errcode(ERRCODE_INVALID_OBJECT_DEFINITION), - errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", - quote_qualified_identifier(eobj_schemaname, eobj_relname), - pubobj->name), - parser_errposition(eobj->location)); - } - pubobjspec_list = list_concat(pubobjspec_list, pubobj->except_tables); - pubobj->except_tables = NIL; - } } prevobjtype = pubobj->pubobjtype; diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 0729e546116..5fb7de2f07f 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -543,6 +543,17 @@ Except tables: "pub_test.testpub_tbl_s1" "public.testpub_tbl1" +-- fail: same schema repeated with same EXCEPT lists +CREATE PUBLICATION testpub_schema_except_conflict + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: conflicting or redundant EXCEPT lists for schema "pub_test" +-- fail: same schema repeated with conflicting or no EXCEPT lists +CREATE PUBLICATION testpub_schema_except_conflict2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2), + pub_test; +ERROR: conflicting or redundant EXCEPT lists for schema "pub_test" -- ALTER TABLE ... SET SCHEMA on a table excluded by a schema publication: -- the schema-scoped exclusion is no longer meaningful once the table moves -- out of its schema, so the exclusion is auto-removed. @@ -2111,6 +2122,8 @@ SET search_path = pub_test1; -- qualified name from wrong schema -> error CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.tbl1); ERROR: table "pub_test2.tbl1" in EXCEPT clause does not belong to schema "pub_test1" +LINE 1: ...FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.... + ^ -- unqualified name implicitly qualified with current schema (pub_test1.tbl) SET client_min_messages = 'ERROR'; CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl); @@ -2126,6 +2139,31 @@ Except tables: "pub_test1.tbl" DROP PUBLICATION testpub_cursch_except; +-- succeeds: CURRENT_SCHEMA and pub_test1 (same schema) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_named_same + FOR TABLES IN SCHEMA CURRENT_SCHEMA, pub_test1; +RESET client_min_messages; +\dRp+ testpub_cursch_named_same + Publication testpub_cursch_named_same + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test1" + +DROP PUBLICATION testpub_cursch_named_same; +-- fail: CURRENT_SCHEMA and pub_test1 (same schema) have +-- conflicting EXCEPT lists +CREATE PUBLICATION testpub_cursch_named_conflict + FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl), + pub_test1 EXCEPT (TABLE tbl1); +ERROR: conflicting or redundant EXCEPT lists for schema "pub_test1" +-- fail: two CURRENT_SCHEMA mentions with conflicting EXCEPT lists +CREATE PUBLICATION testpub_cursch_cursch_conflict + FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl), + CURRENT_SCHEMA EXCEPT (TABLE tbl1); +ERROR: conflicting or redundant EXCEPT lists for schema "pub_test1" RESET search_path; -- cleanup pub_test1 schema for invalidation tests ALTER PUBLICATION testpub2_forschema DROP TABLES IN SCHEMA pub_test1; diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 055b9e97dc1..3755032ad03 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -260,6 +260,17 @@ CREATE PUBLICATION testpub_schema_except_multi public EXCEPT (TABLE testpub_tbl1); \dRp+ testpub_schema_except_multi +-- fail: same schema repeated with same EXCEPT lists +CREATE PUBLICATION testpub_schema_except_conflict + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: same schema repeated with conflicting or no EXCEPT lists +CREATE PUBLICATION testpub_schema_except_conflict2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2), + pub_test; + -- ALTER TABLE ... SET SCHEMA on a table excluded by a schema publication: -- the schema-scoped exclusion is no longer meaningful once the table moves -- out of its schema, so the exclusion is auto-removed. @@ -1298,6 +1309,26 @@ CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXC RESET client_min_messages; \dRp+ testpub_cursch_except DROP PUBLICATION testpub_cursch_except; + +-- succeeds: CURRENT_SCHEMA and pub_test1 (same schema) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_named_same + FOR TABLES IN SCHEMA CURRENT_SCHEMA, pub_test1; +RESET client_min_messages; +\dRp+ testpub_cursch_named_same +DROP PUBLICATION testpub_cursch_named_same; + +-- fail: CURRENT_SCHEMA and pub_test1 (same schema) have +-- conflicting EXCEPT lists +CREATE PUBLICATION testpub_cursch_named_conflict + FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl), + pub_test1 EXCEPT (TABLE tbl1); + +-- fail: two CURRENT_SCHEMA mentions with conflicting EXCEPT lists +CREATE PUBLICATION testpub_cursch_cursch_conflict + FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl), + CURRENT_SCHEMA EXCEPT (TABLE tbl1); + RESET search_path; -- cleanup pub_test1 schema for invalidation tests -- 2.50.1 (Apple Git-155)
v20-0003-Add-EXCEPT-support-to-ALTER-PUBLICATION-ADD-TABL.patch (application/octet-stream, 22.5K) download From 8d564bf6b279b80b05309903b886dd31d499f5c2 Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Wed, 8 Jul 2026 17:09:06 +0530 Subject: [PATCH v20 3/5] Add EXCEPT support to ALTER PUBLICATION ADD TABLES IN SCHEMA Extend the EXCEPT clause support to allow tables to be excluded when adding a schema to a publication via ALTER PUBLICATION ... ADD. Syntax: ALTER PUBLICATION pub ADD TABLES IN SCHEMA s EXCEPT (TABLE s.t1); Since pg_dump uses ALTER PUBLICATION ... ADD, support for it is included in this patch. --- src/backend/catalog/pg_publication.c | 19 +++-- src/backend/commands/publicationcmds.c | 98 ++++++++++++++++++++++- src/bin/pg_dump/pg_dump.c | 30 ++++++- src/bin/pg_dump/t/002_pg_dump.pl | 24 ++++++ src/bin/psql/tab-complete.in.c | 17 ++++ src/test/regress/expected/publication.out | 66 ++++++++++++++- src/test/regress/sql/publication.sql | 50 +++++++++++- src/test/subscription/t/037_except.pl | 32 ++++++++ 8 files changed, 322 insertions(+), 14 deletions(-) diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index 0bdcc07c42d..21f679f8ac1 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -729,15 +729,18 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, * here, as CreatePublication() function invalidates all relations as part * of defining a FOR ALL TABLES publication. * - * For ALTER PUBLICATION, invalidation is needed only when adding an - * EXCEPT table to a publication already marked as ALL TABLES. For - * publications that were originally empty or defined as ALL SEQUENCES and - * are being converted to ALL TABLES, invalidation is skipped here, as - * AlterPublicationAllFlags() function invalidates all relations while - * marking the publication as ALL TABLES publication. + * For ALTER PUBLICATION, invalidation is needed when adding an EXCEPT + * table to either a FOR ALL TABLES publication (pub->alltables is true) + * or a FOR TABLES IN SCHEMA publication (is_schema_publication is true). + * The exception: when a publication is being converted to FOR ALL TABLES + * (pub->alltables is still false at this point), + * AlterPublicationAllFlags() will perform a full invalidation, so we skip + * it here. */ - inval_except_table = (alter_stmt != NULL) && pub->alltables && - (alter_stmt->for_all_tables && pri->except); + inval_except_table = (alter_stmt != NULL) && pri->except && + (pub->alltables + ? alter_stmt->for_all_tables + : is_schema_publication(pubid)); if (!pri->except || inval_except_table) { diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 0c3c905f7ea..e6485827b1c 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -71,6 +71,13 @@ static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok); static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); +static void AlterPublicationSchemas(AlterPublicationStmt *stmt, + HeapTuple tup, List *schemaidlist, + List *except_pubtables); +static void AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, + List *except_pubtables, + List *schemaidlist); static char defGetGeneratedColsOption(DefElem *def); static void CheckExceptNotInTableList(List *except_rels, List *explicitrelids); static void ProcessSchemaExceptTables(Oid schemaid, const char *schema_name, @@ -1577,7 +1584,8 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, */ static void AlterPublicationSchemas(AlterPublicationStmt *stmt, - HeapTuple tup, List *schemaidlist) + HeapTuple tup, List *schemaidlist, + List *except_pubtables) { Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); @@ -1654,6 +1662,88 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, */ PublicationAddSchemas(pubform->oid, schemaidlist, true, stmt); } + + /* + * Increment the command counter so that is_schema_publication() in + * GetExcludedPublicationTables() can see the just-inserted schema + * rows when AlterPublicationSchemaExceptTables runs next. + */ + if (stmt->action == AP_AddObjects || stmt->action == AP_SetObjects) + CommandCounterIncrement(); + + AlterPublicationSchemaExceptTables(stmt, tup, except_pubtables, schemaidlist); +} + +/* + * Alter the EXCEPT list of a schema-level publication. + * + * Adds, removes, or replaces except-table entries in pg_publication_rel + * (rows with prexcept = true). These entries suppress publication of the + * named tables that would otherwise be covered by a FOR TABLES IN SCHEMA + * clause. + */ +static void +AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, List *except_pubtables, + List *schemaidlist) +{ + Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); + Oid pubid = pubform->oid; + + /* + * Nothing to do if no EXCEPT entries. + */ + if (!except_pubtables) + return; + + /* + * This function handles EXCEPT entries for schema-level publications + * only. For FOR ALL TABLES publications, EXCEPT entries are already + * processed by AlterPublicationTables(). + */ + if (schemaidlist == NIL && !is_schema_publication(pubid)) + return; + + /* + * Dropping a schema from a publication removes all its EXCEPT entries via + * cascade. The concept of "drop all schema tables from the publication + * EXCEPT these ones" is not supported. + */ + if (stmt->action == AP_DropObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); + + /* + * XXX EXCEPT with SET is not currently implemented. Workaround: DROP and + * re-ADD the schema with the desired EXCEPT list. + */ + if (stmt->action == AP_SetObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"), + errhint("Drop and re-add the schema with the desired EXCEPT list."))); + + if (stmt->action == AP_AddObjects) + { + List *rels; + List *explicitrelids; + + rels = OpenTableList(except_pubtables); + + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + /* + * Validate that each excluded table is not also in the explicit table + * list (which would be contradictory). + */ + CheckExceptNotInTableList(rels, explicitrelids); + + PublicationAddTables(pubid, rels, false, stmt); + + CloseTableList(rels); + } } /* @@ -1863,10 +1953,12 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) errmsg("publication \"%s\" does not exist", stmt->pubname)); - relations = list_concat(relations, except_pubtables); + if (stmt->for_all_tables) + relations = list_concat(relations, except_pubtables); + AlterPublicationTables(stmt, tup, relations, pstate->p_sourcetext, schemaidlist != NIL); - AlterPublicationSchemas(stmt, tup, schemaidlist); + AlterPublicationSchemas(stmt, tup, schemaidlist, except_pubtables); AlterPublicationAllFlags(stmt, rel, tup); } diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c index 4d660d14b4c..4877fd4546c 100644 --- a/src/bin/pg_dump/pg_dump.c +++ b/src/bin/pg_dump/pg_dump.c @@ -4973,6 +4973,7 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) PublicationInfo *pubinfo = pubsinfo->publication; PQExpBuffer query; char *tag; + bool has_except = false; /* Do nothing if not dumping schema */ if (!dopt->dumpSchema) @@ -4983,7 +4984,34 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) query = createPQExpBuffer(); appendPQExpBuffer(query, "ALTER PUBLICATION %s ", fmtId(pubinfo->dobj.name)); - appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s;\n", fmtId(schemainfo->dobj.name)); + appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s", fmtId(schemainfo->dobj.name)); + + /* + * Append EXCEPT clause for any tables that belong to this schema + * and are excluded from the publication. + */ + for (SimplePtrListCell *cell = pubinfo->except_tables.head; cell; cell = cell->next) + { + TableInfo *tbinfo = (TableInfo *) cell->ptr; + + if (strcmp(tbinfo->dobj.namespace->dobj.name, schemainfo->dobj.name) == 0) + { + if (!has_except) + { + appendPQExpBufferStr(query, " EXCEPT ("); + has_except = true; + } + else + appendPQExpBufferStr(query, ", "); + + appendPQExpBuffer(query, "TABLE ONLY %s", fmtId(tbinfo->dobj.name)); + } + } + + if (has_except) + appendPQExpBufferStr(query, ")"); + + appendPQExpBufferStr(query, ";\n"); /* * There is no point in creating drop query as the drop is done by schema diff --git a/src/bin/pg_dump/t/002_pg_dump.pl b/src/bin/pg_dump/t/002_pg_dump.pl index 9258948b583..d18b3b0d7b9 100644 --- a/src/bin/pg_dump/t/002_pg_dump.pl +++ b/src/bin/pg_dump/t/002_pg_dump.pl @@ -3283,6 +3283,30 @@ my %tests = ( like => { %full_runs, section_post_data => 1, }, }, + 'CREATE PUBLICATION pub11' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub11 FOR TABLES IN SCHEMA dump_test EXCEPT (TABLE test_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub11 WITH (publish = 'insert, update, delete, truncate');\E + .*? + \QALTER PUBLICATION pub11 ADD TABLES IN SCHEMA dump_test EXCEPT (TABLE ONLY test_table);\E + /xms, + like => { %full_runs, section_post_data => 1, }, + }, + + 'CREATE PUBLICATION pub12' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub12 FOR TABLES IN SCHEMA dump_test EXCEPT (TABLE test_table, dump_test.test_second_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub12 WITH (publish = 'insert, update, delete, truncate');\E + .*? + \QALTER PUBLICATION pub12 ADD TABLES IN SCHEMA dump_test EXCEPT (TABLE ONLY test_table, TABLE ONLY test_second_table);\E + /xms, + like => { %full_runs, section_post_data => 1, }, + }, + 'CREATE SUBSCRIPTION sub1' => { create_order => 50, create_sql => 'CREATE SUBSCRIPTION sub1 diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index 067168699f6..23009ca2f40 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2359,6 +2359,23 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); + /* After a single schema name in ADD context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 5fb7de2f07f..13dd334d2ba 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -626,12 +626,76 @@ CREATE PUBLICATION testpub_except_ancestor_same_create TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); ERROR: partition "pub_test.testpub_part_s" cannot be both published and excluded DETAIL: Ancestor "pub_test.testpub_parted_s" is also being excluded by this same command. +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; +-- fail: non-existing table in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- fail: EXCEPT table belongs to a different schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 1: ...xcept ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.tes... + ^ +-- fail: TABLE keyword is required for the first entry in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +ERROR: syntax error at or near "testpub_nopk" +LINE 1: ...lter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_no... + ^ +-- fail: exact same table given as both explicitly published and excluded +-- in a single ALTER ... ADD +ALTER PUBLICATION testpub_alter_except + ADD TABLE pub_test.testpub_tbl_s1, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot be both published and excluded +-- fail: add explicit partition and EXCEPT ancestor, given in a +-- single ALTER ... ADD statement +ALTER PUBLICATION testpub_alter_except + ADD TABLE pub_test.testpub_part_s, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ERROR: partition "pub_test.testpub_part_s" cannot be both published and excluded +DETAIL: Ancestor "pub_test.testpub_parted_s" is also being excluded by this same command. +-- fail: partition still rejected from EXCEPT even when its own root is also +-- named in the same EXCEPT list, via ALTER ... ADD +ALTER PUBLICATION testpub_alter_except + ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s, TABLE pub_test.testpub_parted_s); +ERROR: cannot specify relation "pub_test.testpub_part_s" in the publication EXCEPT clause +DETAIL: This operation is not supported for individual partitions. +-- fail: partition already explicitly published, then its root is EXCEPT-ed +-- via a later, separate ALTER ... ADD +ALTER PUBLICATION testpub_alter_except ADD TABLE pub_test.testpub_part_s; +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ERROR: partition "pub_test.testpub_part_s" cannot be both published and excluded +DETAIL: Ancestor "pub_test.testpub_parted_s" is also being excluded by this same command. +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_part_s; +-- fail: root already explicitly published, then its partition is rejected +-- from EXCEPT via a later, separate ALTER ... ADD (partitions can never +-- appear in EXCEPT, independent of the root's state) +ALTER PUBLICATION testpub_alter_except ADD TABLE pub_test.testpub_parted_s; +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); +ERROR: cannot specify relation "pub_test.testpub_part_s" in the publication EXCEPT clause +DETAIL: This operation is not supported for individual partitions. +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_parted_s; +-- ADD: qualified and unqualified names; unqualified is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + "pub_test.testpub_tbl_s2" + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP TABLE pub_test.testpub_parted_s CASCADE; DROP TABLE testpub_nopk, testpub_tbl_s1; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi, testpub_alter_except; --------------------------------------------- -- Tests for publications with SEQUENCES --------------------------------------------- diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 3755032ad03..4801ccac112 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -321,12 +321,60 @@ CREATE PUBLICATION testpub_except_ancestor_same_create FOR TABLE pub_test.testpub_part_s, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; + +-- fail: non-existing table in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- fail: EXCEPT table belongs to a different schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- fail: TABLE keyword is required for the first entry in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + +-- fail: exact same table given as both explicitly published and excluded +-- in a single ALTER ... ADD +ALTER PUBLICATION testpub_alter_except + ADD TABLE pub_test.testpub_tbl_s1, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: add explicit partition and EXCEPT ancestor, given in a +-- single ALTER ... ADD statement +ALTER PUBLICATION testpub_alter_except + ADD TABLE pub_test.testpub_part_s, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); + +-- fail: partition still rejected from EXCEPT even when its own root is also +-- named in the same EXCEPT list, via ALTER ... ADD +ALTER PUBLICATION testpub_alter_except + ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s, TABLE pub_test.testpub_parted_s); + +-- fail: partition already explicitly published, then its root is EXCEPT-ed +-- via a later, separate ALTER ... ADD +ALTER PUBLICATION testpub_alter_except ADD TABLE pub_test.testpub_part_s; +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_part_s; + +-- fail: root already explicitly published, then its partition is rejected +-- from EXCEPT via a later, separate ALTER ... ADD (partitions can never +-- appear in EXCEPT, independent of the root's state) +ALTER PUBLICATION testpub_alter_except ADD TABLE pub_test.testpub_parted_s; +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_parted_s; + +-- ADD: qualified and unqualified names; unqualified is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); +\dRp+ testpub_alter_except + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP TABLE pub_test.testpub_parted_s CASCADE; DROP TABLE testpub_nopk, testpub_tbl_s1; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi, testpub_alter_except; --------------------------------------------- -- Tests for publications with SEQUENCES diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index e9bca3554b1..27e336267db 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -347,6 +347,38 @@ is($result, qq(5), $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); +# ============================================ +# ALTER PUBLICATION EXCEPT for TABLES IN SCHEMA +# ============================================ + +# Truncate subscriber tables to remove data accumulated from previous tests. +$node_subscriber->safe_psql('postgres', + 'TRUNCATE sch1.tab_published, sch1.tab_excluded, sch1.parent, sch1.child'); + +# ADD: add a schema with an excepted table; verify the except entry takes effect. +$node_publisher->safe_psql('postgres', "CREATE PUBLICATION sch_pub"); +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub ADD TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_excluded)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(6), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: included table synced'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + # Cleanup schema tables before the multi-publication section. $node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); $node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); -- 2.50.1 (Apple Git-155)
v20-0004-Add-EXCEPT-support-to-ALTER-PUBLICATION-SET-TABL.patch (application/octet-stream, 27.5K) download From 5695f655343b98fbe540cf9df6c85ce3e6047c24 Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Thu, 18 Jun 2026 11:32:32 +0530 Subject: [PATCH v20 4/5] Add EXCEPT support to ALTER PUBLICATION SET TABLES IN SCHEMA Extend AlterPublicationExceptTables() with the AP_SetObjects case, which redefines the publication and replaces the entire EXCEPT list. Syntax: ALTER PUBLICATION pub SET TABLES IN SCHEMA s EXCEPT (TABLE t1); This patch also cleans up EXCEPT entries when a schema is dropped from the publication. --- src/backend/commands/publicationcmds.c | 181 +++++++++++++++++++--- src/bin/psql/tab-complete.in.c | 17 ++ src/test/regress/expected/publication.out | 109 +++++++++++++ src/test/regress/sql/publication.sql | 47 ++++++ src/test/subscription/t/037_except.pl | 85 ++++++++++ 5 files changed, 414 insertions(+), 25 deletions(-) diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index e6485827b1c..b431ccf802a 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -67,7 +67,8 @@ static void CloseTableList(List *rels); static void LockSchemaList(List *schemalist); static void PublicationAddTables(Oid pubid, List *rels, bool if_not_exists, AlterPublicationStmt *stmt); -static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok); +static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok, + bool delete_excluded); static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); @@ -1428,7 +1429,7 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, PublicationAddTables(pubid, rels, false, stmt); } else if (stmt->action == AP_DropObjects) - PublicationDropTables(pubid, rels, false); + PublicationDropTables(pubid, rels, false, false); else /* AP_SetObjects */ { List *oldrelids = NIL; @@ -1563,7 +1564,7 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, } /* And drop them. */ - PublicationDropTables(pubid, delrels, true); + PublicationDropTables(pubid, delrels, true, true); /* * Don't bother calculating the difference for adding, we'll catch and @@ -1665,8 +1666,8 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, /* * Increment the command counter so that is_schema_publication() in - * GetExcludedPublicationTables() can see the just-inserted schema - * rows when AlterPublicationSchemaExceptTables runs next. + * GetExcludedPublicationTables() can see the just-inserted schema rows + * when AlterPublicationSchemaExceptTables runs next. */ if (stmt->action == AP_AddObjects || stmt->action == AP_SetObjects) CommandCounterIncrement(); @@ -1684,16 +1685,18 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, */ static void AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, - HeapTuple tup, List *except_pubtables, - List *schemaidlist) + HeapTuple tup, List *except_pubtables, + List *schemaidlist) { Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); Oid pubid = pubform->oid; /* - * Nothing to do if no EXCEPT entries. + * Nothing to do if there are no EXCEPT entries, unless handling the SET + * command, because if the user has removed all exceptions we need to drop + * any existing ones. */ - if (!except_pubtables) + if (!except_pubtables && stmt->action != AP_SetObjects) return; /* @@ -1714,16 +1717,6 @@ AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); - /* - * XXX EXCEPT with SET is not currently implemented. Workaround: DROP and - * re-ADD the schema with the desired EXCEPT list. - */ - if (stmt->action == AP_SetObjects) - ereport(ERROR, - (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"), - errhint("Drop and re-add the schema with the desired EXCEPT list."))); - if (stmt->action == AP_AddObjects) { List *rels; @@ -1742,6 +1735,76 @@ AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, PublicationAddTables(pubid, rels, false, stmt); + CloseTableList(rels); + } + else /* AP_SetObjects */ + { + List *oldexceptrelids = NIL; + List *newexceptrelids = NIL; + List *delrelids = NIL; + List *rels; + List *explicitrelids; + + rels = OpenTableList(except_pubtables); + + /* Collect OIDs of the desired new EXCEPT list. */ + foreach_ptr(PublicationRelInfo, pri, rels) + newexceptrelids = lappend_oid(newexceptrelids, + RelationGetRelid(pri->relation)); + + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + /* + * Validate that no excluded table is also already explicitly + * published (exact match), and that no already-published partition + * has its root among the tables being newly excluded here. + */ + CheckExceptNotInTableList(rels, explicitrelids); + + /* + * Get the current set of EXCEPT entries. Only FOR ALL TABLES and + * schema-level publications can have EXCEPT entries; for any other + * publication type oldexceptrelids stays NIL. + * + * Note: we check is_schema_publication() against the current catalog + * state (before AlterPublicationSchemas has run), so if the caller is + * doing SET TABLE t1 to convert a schema publication into a plain + * table publication, is_schema_publication() still returns true here. + * That is intentional: it lets us discover and clean up any stale + * EXCEPT entries that belong to the old schema definition. + */ + if (GetPublication(pubid)->alltables || is_schema_publication(pubid)) + oldexceptrelids = GetExcludedPublicationTables(pubid, + PUBLICATION_PART_ROOT); + + /* Build a list of old EXCEPT entries not present in the new list. */ + foreach_oid(oldrelid, oldexceptrelids) + { + if (!list_member_oid(newexceptrelids, oldrelid)) + delrelids = lappend_oid(delrelids, oldrelid); + } + + /* Drop old EXCEPT entries not present in the new list. */ + foreach_oid(relid, delrelids) + { + Oid proid; + ObjectAddress obj; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + /* Add new EXCEPT entries, skipping any already present. */ + PublicationAddTables(pubid, rels, true, stmt); + CloseTableList(rels); } } @@ -2365,33 +2428,68 @@ PublicationAddTables(Oid pubid, List *rels, bool if_not_exists, /* * Remove listed tables from the publication. + * + * delete_excluded controls how EXCEPT (prexcept=true) rows are handled: + * true - delete them silently. Used by the SET path to clear stale + * EXCEPT rows that are being replaced by a new EXCEPT list. + * false - treat them as "not a member". Used by ALTER ... DROP TABLE: an + * EXCEPT entry is not something DROP TABLE is expected to remove. */ static void -PublicationDropTables(Oid pubid, List *rels, bool missing_ok) +PublicationDropTables(Oid pubid, List *rels, bool missing_ok, + bool delete_excluded) { ObjectAddress obj; ListCell *lc; - Oid prid; foreach(lc, rels) { PublicationRelInfo *pubrel = (PublicationRelInfo *) lfirst(lc); Relation rel = pubrel->relation; Oid relid = RelationGetRelid(rel); + HeapTuple tup; + Form_pg_publication_rel pubrelform; + Oid prid = InvalidOid; + bool is_except = false; if (pubrel->columns) ereport(ERROR, errcode(ERRCODE_SYNTAX_ERROR), errmsg("column list must not be specified in ALTER PUBLICATION ... DROP")); - prid = GetSysCacheOid2(PUBLICATIONRELMAP, Anum_pg_publication_rel_oid, - ObjectIdGetDatum(relid), - ObjectIdGetDatum(pubid)); - if (!OidIsValid(prid)) + tup = SearchSysCache2(PUBLICATIONRELMAP, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (HeapTupleIsValid(tup)) + { + pubrelform = (Form_pg_publication_rel) GETSTRUCT(tup); + is_except = pubrelform->prexcept; + prid = pubrelform->oid; + ReleaseSysCache(tup); + } + + /* + * DROP TABLE operates only on regular member rows. A missing row + * and an EXCEPT row both mean the table isn't currently published, + * but we distinguish them so the EXCEPT case can carry a hint + * pointing the user at the EXCEPT list. The SET-cleanup caller + * (delete_excluded = true) intends to remove EXCEPT rows and so + * bypasses the EXCEPT half of this check. + */ + if (!OidIsValid(prid) || (is_except && !delete_excluded)) { if (missing_ok) continue; + if (is_except) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("cannot drop table \"%s\" from publication \"%s\"", + RelationGetQualifiedRelationName(rel), + get_publication_name(pubid, false)), + errdetail("The table is currently listed in the EXCEPT clause of the publication."), + errhint("Use ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT to drop the table from the EXCEPT list."))); + ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("relation \"%s\" is not part of the publication", @@ -2447,6 +2545,7 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) foreach(lc, schemas) { Oid schemaid = lfirst_oid(lc); + List *except_relids; psid = GetSysCacheOid2(PUBLICATIONNAMESPACEMAP, Anum_pg_publication_namespace_oid, @@ -2463,8 +2562,40 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) get_namespace_name(schemaid)))); } + /* + * Collect EXCEPT entries for tables belonging to this schema before + * removing the schema entry. + */ + except_relids = GetExcludedPublicationTables(pubid, PUBLICATION_PART_ROOT); + ObjectAddressSet(obj, PublicationNamespaceRelationId, psid); performDeletion(&obj, DROP_CASCADE, 0); + + /* + * Drop any prexcept rows for tables belonging to this schema. These + * rows have no pg_depend entry pointing at the + * pg_publication_namespace row, so they are not cascaded by the + * performDeletion() call above and must be cleaned up explicitly. + */ + foreach_oid(relid, except_relids) + { + Oid proid; + + if (get_rel_namespace(relid) != schemaid) + continue; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + list_free(except_relids); } } diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index 23009ca2f40..dcdc3893112 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2376,6 +2376,23 @@ match_previous_words(int pattern_id, } else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) COMPLETE_WITH(")"); + /* After a single schema name in SET context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 13dd334d2ba..d0037ed3da4 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -690,6 +690,115 @@ Except tables: "pub_test.testpub_tbl_s1" "pub_test.testpub_tbl_s2" +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s2" + +-- fail: table in EXCEPT clause also appears in the explicit table list +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot be both published and excluded +-- fail: explicit partition + EXCEPT-ed root, given in a single SET statement +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_part_s, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ERROR: partition "pub_test.testpub_part_s" cannot be both published and excluded +DETAIL: Ancestor "pub_test.testpub_parted_s" is also being excluded by this same command. +-- fail: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 1: ...xcept SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.tes... + ^ +-- SET: unqualified name in EXCEPT is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- SET without EXCEPT clears the existing except list +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + +-- SET to a different schema removes old schema's EXCEPT entries +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA public; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "public" + +-- fail: nonexistent table in EXCEPT clause (SET path) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- SET: multiple schemas each with their own EXCEPT clause +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- fail: ALTER PUBLICATION ... DROP TABLE on an excluded table is rejected +-- with an EXCEPT-specific error. +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_tbl_s1; +ERROR: cannot drop table "pub_test.testpub_tbl_s1" from publication "testpub_alter_except" +DETAIL: The table is currently listed in the EXCEPT clause of the publication. +HINT: Use ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT to drop the table from the EXCEPT list. +-- the EXCEPT entry is still present after the rejected DROP TABLE +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- fail: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +ERROR: EXCEPT clause is not supported with DROP in ALTER PUBLICATION +-- DROP TABLES IN SCHEMA removes associated EXCEPT entries +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "public" +Except tables: + "public.testpub_tbl1" + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 4801ccac112..93d827f2b2c 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -369,6 +369,53 @@ ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_parted_s; ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); \dRp+ testpub_alter_except +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + +-- fail: table in EXCEPT clause also appears in the explicit table list +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: explicit partition + EXCEPT-ed root, given in a single SET statement +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_part_s, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); + +-- fail: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- SET: unqualified name in EXCEPT is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +\dRp+ testpub_alter_except + +-- SET without EXCEPT clears the existing except list +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + +-- SET to a different schema removes old schema's EXCEPT entries +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA public; +\dRp+ testpub_alter_except + +-- fail: nonexistent table in EXCEPT clause (SET path) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- SET: multiple schemas each with their own EXCEPT clause +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_alter_except + +-- fail: ALTER PUBLICATION ... DROP TABLE on an excluded table is rejected +-- with an EXCEPT-specific error. +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_tbl_s1; +-- the EXCEPT entry is still present after the rejected DROP TABLE +\dRp+ testpub_alter_except + +-- fail: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); + +-- DROP TABLES IN SCHEMA removes associated EXCEPT entries +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 27e336267db..251a87981b4 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -376,6 +376,61 @@ $result = is($result, qq(0), 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); +# SET: replace the except list; tab_excluded is now included and tab_published is excluded. +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_published)" +); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (7); + INSERT INTO sch1.tab_excluded VALUES (7); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded WHERE a = 7"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: newly included table is replicated' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published WHERE a = 7"); +is($result, qq(0), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: now-excluded table is not replicated' +); + +# SET without EXCEPT: clears the except list; both tables are now published. +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1"); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (8); + INSERT INTO sch1.tab_excluded VALUES (8); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published WHERE a = 8"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_published replicated after except list cleared' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded WHERE a = 8"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_excluded replicated after except list cleared' +); + $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); @@ -518,6 +573,36 @@ $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); +# OK when a table is excluded by a TABLES IN SCHEMA EXCEPT publication, +# but is included by another publication. +$node_publisher->safe_psql('postgres', 'TRUNCATE tab1'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE tab1'); + +$node_publisher->safe_psql( + 'postgres', qq( + CREATE PUBLICATION tap_pub1 FOR TABLES IN SCHEMA public EXCEPT (TABLE public.tab1); + CREATE PUBLICATION tap_pub2 FOR TABLE tab1; + INSERT INTO tab1 VALUES(1); +)); +$node_subscriber->psql('postgres', + "CREATE SUBSCRIPTION tap_sub CONNECTION '$publisher_connstr' PUBLICATION tap_pub1, tap_pub2" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'tap_sub'); + +$node_publisher->safe_psql('postgres', qq(INSERT INTO tab1 VALUES(2))); +$node_publisher->wait_for_catchup('tap_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT * FROM tab1 ORDER BY a"); +is( $result, qq(1 +2), + "TABLES IN SCHEMA EXCEPT: table excluded in schema pub but included by another pub is replicated" +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); + $node_publisher->stop('fast'); done_testing(); -- 2.50.1 (Apple Git-155)
v20-0005-Documentation-Patch.patch (application/octet-stream, 11.6K) download From a3ae2eb3ab64efa3ff2fca5e1b00fe4178a4205e Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Thu, 18 Jun 2026 09:03:08 +0530 Subject: [PATCH v20 5/5] Documentation Patch --- doc/src/sgml/logical-replication.sgml | 3 +- doc/src/sgml/ref/alter_publication.sgml | 58 +++++++++++++++++++++++- doc/src/sgml/ref/create_publication.sgml | 42 +++++++++++++---- 3 files changed, 91 insertions(+), 12 deletions(-) diff --git a/doc/src/sgml/logical-replication.sgml b/doc/src/sgml/logical-replication.sgml index 690598bff98..46c944beae8 100644 --- a/doc/src/sgml/logical-replication.sgml +++ b/doc/src/sgml/logical-replication.sgml @@ -117,7 +117,8 @@ or <literal>FOR ALL SEQUENCES</literal>. Unlike tables, sequences can be synchronized at any time. For more information, see <xref linkend="logical-replication-sequences"/>. When a publication is - created with <literal>FOR ALL TABLES</literal>, a table or set of tables can + created with <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal>, a table or set of tables can be explicitly excluded from publication using the <link linkend="sql-createpublication-params-for-except-table"><literal>EXCEPT</literal></link> clause. diff --git a/doc/src/sgml/ref/alter_publication.sgml b/doc/src/sgml/ref/alter_publication.sgml index 52114a16a39..037ddfa9404 100644 --- a/doc/src/sgml/ref/alter_publication.sgml +++ b/doc/src/sgml/ref/alter_publication.sgml @@ -31,7 +31,7 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA <replaceable class="parameter">tables_in_schema</replaceable> [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -47,6 +47,10 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <replaceable class="parameter">table_object</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] [ WHERE ( <replaceable class="parameter">expression</replaceable> ) ] +<phrase>and <replaceable class="parameter">tables_in_schema</replaceable> is:</phrase> + + { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] + <phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> TABLE <replaceable class="parameter">table_object</replaceable> [, ... ] @@ -69,6 +73,9 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r The first two variants modify which tables/schemas are part of the publication. The <literal>ADD</literal> and <literal>DROP</literal> clauses will add and remove one or more tables/schemas from the publication. + The <literal>EXCEPT</literal> clause can be used with + <literal>ADD TABLES IN SCHEMA</literal> to exclude specific tables from a + schema-level publication. </para> <para> @@ -93,7 +100,11 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r used with a publication defined with <literal>FOR TABLE</literal> or <literal>FOR TABLES IN SCHEMA</literal>, replaces the list of tables/schemas in the publication with the specified list; the existing tables or schemas - that were present in the publication will be removed. + that were present in the publication will be removed. When + <literal>SET TABLES IN SCHEMA</literal> is used with an + <literal>EXCEPT</literal> clause, the excluded tables for each schema are + replaced with the specified list; if <literal>EXCEPT</literal> is omitted + for a schema, any existing exclusions for that schema are cleared. </para> <para> @@ -198,6 +209,27 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r </listitem> </varlistentry> + <varlistentry> + <term><literal>EXCEPT</literal></term> + <listitem> + <para> + When used with <literal>ADD TABLES IN SCHEMA</literal> + or <literal>SET TABLES IN SCHEMA</literal>, specifies + tables to be excluded from the publication. Each named + table must belong to the schema specified in the same + <literal>TABLES IN SCHEMA</literal> clause. Table names may be + schema-qualified or unqualified; unqualified names are implicitly + qualified with the schema named in the same clause. See + <xref linkend="sql-createpublication"/> for further details on the + semantics of <literal>EXCEPT</literal>. + </para> + <para> + Dropping a table always removes it from the <literal>EXCEPT</literal> + clause. + </para> + </listitem> + </varlistentry> + <varlistentry> <term><literal>SET ( <replaceable class="parameter">publication_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] )</literal></term> <listitem> @@ -288,6 +320,28 @@ ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA marketing, sales; </programlisting> </para> + <para> + Add schema <structname>sales</structname> to the publication + <structname>sales_publication</structname>, excluding the + <structname>sales.internal</structname> and + <structname>sales.drafts</structname> tables: +<programlisting> +ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA sales EXCEPT (TABLE internal, drafts); +</programlisting> + </para> + + <para> + Replace the schema list of <structname>sales_publication</structname> with + <structname>sales</structname>, excluding only + <structname>sales.drafts</structname>. Other than + <structname>sales.drafts</structname>, any previously excluded tables for schema + <structname>sales</structname> are no longer excluded. Any schemas previously in + <structname>sales_publication</structname> are removed: +<programlisting> +ALTER PUBLICATION sales_publication SET TABLES IN SCHEMA sales EXCEPT (TABLE drafts); +</programlisting> + </para> + <para> Add tables <structname>users</structname>, <structname>departments</structname> and schema diff --git a/doc/src/sgml/ref/create_publication.sgml b/doc/src/sgml/ref/create_publication.sgml index 85cfcaddafa..26cb536e90b 100644 --- a/doc/src/sgml/ref/create_publication.sgml +++ b/doc/src/sgml/ref/create_publication.sgml @@ -28,7 +28,7 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA <replaceable class="parameter">tables_in_schema</replaceable> [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -39,6 +39,10 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <replaceable class="parameter">table_object</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] [ WHERE ( <replaceable class="parameter">expression</replaceable> ) ] +<phrase>and <replaceable class="parameter">tables_in_schema</replaceable> is:</phrase> + + { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] + <phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> TABLE <replaceable class="parameter">table_object</replaceable> [, ... ] @@ -142,6 +146,8 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <para> Marks the publication as one that replicates changes for all tables in the specified list of schemas, including tables created in the future. + Tables listed in the <literal>EXCEPT</literal> clause for a given schema + are excluded from the publication. </para> <para> @@ -173,7 +179,7 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <para> Marks the publication as one that replicates changes for all tables in the database, including tables created in the future. Tables listed in - <literal>EXCEPT</literal> clause are excluded from the publication. + the <literal>EXCEPT</literal> clause are excluded from the publication. </para> </listitem> </varlistentry> @@ -198,13 +204,21 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <listitem> <para> This clause specifies a list of tables to be excluded from the - publication. + publication. It can be used with <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal>. For <literal>FOR TABLES IN + SCHEMA</literal>, the exclusion applies only to tables in the schema + associated with the <literal>EXCEPT</literal>. </para> <para> - Once a table is excluded, the exclusion applies to that table - regardless of its name or schema. Renaming the table or moving it to - another schema using <command>ALTER TABLE ... SET SCHEMA</command> does - not remove the exclusion. + Once a table is excluded under <literal>FOR ALL TABLES</literal>, the + exclusion applies to that table regardless of its name or schema. + Renaming the table or moving it to another schema using + <command>ALTER TABLE ... SET SCHEMA</command> does not remove the + exclusion. However, for <literal>FOR TABLES IN SCHEMA</literal>, because + the <literal>EXCEPT</literal> is schema-scoped, moving a schema-excluded + table to another schema does remove the exclusion; if the table is later + moved back, the exclusion is not restored and must be re-established + with <command>ALTER PUBLICATION</command>. </para> <para> For inherited tables, if <literal>ONLY</literal> is specified before the @@ -216,8 +230,9 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> </para> <para> For partitioned tables, only the root partitioned table may be specified - in <literal>EXCEPT</literal>. Doing so excludes the root table and - all of its partitions from replication. The optional + in <literal>EXCEPT</literal>. Excluding the root table automatically + excludes all of its partitions from replication, including those in + schemas that are otherwise included in the publication. The optional <literal>ONLY</literal> and <literal>*</literal> has no effect for partitioned tables. </para> @@ -521,6 +536,15 @@ CREATE PUBLICATION production_publication FOR TABLE users, departments, TABLES I CREATE PUBLICATION sales_publication FOR TABLES IN SCHEMA marketing, sales; </programlisting></para> + <para> + Create a publication that publishes all changes for all the tables present in + the schema <structname>sales</structname>, except + <structname>internal</structname> and <structname>drafts</structname>: +<programlisting> +CREATE PUBLICATION sales_filtered FOR TABLES IN SCHEMA sales EXCEPT (TABLE internal, drafts); +</programlisting> + </para> + <para> Create a publication that publishes all changes for table <structname>users</structname>, but replicates only columns <structname>user_id</structname> and -- 2.50.1 (Apple Git-155)
^ permalink raw reply [nested|flat] 196+ messages in thread

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-10 11:37  Nisha Moond <nisha.moond412@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: Nisha Moond @ 2026-07-10 11:37 UTC (permalink / raw)
  To: shveta malik <shveta.malik@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Thu, Jul 9, 2026 at 2:53 PM shveta malik <shveta.malik@gmail.com> wrote:
>
> >
> > To reduce duplicate code, I moved the schema
> > qualification and eligibility checks for both cases to execution time
>>  and removed the corresponding processing from gram.y.
> >
> > Since this changes a fair amount of code, I've kept it as a separate
> > patch (v19-0002) to make review easier. Depending on the feedback, we
> > can optimize the implementation or move parts of it back into gram.y
> > before merging it into patch 0001.
> > ~~~
> >
>
> Nisha,
>
> - * Also flattens except_tables from TABLES IN SCHEMA nodes into the list so
> - * that ObjectsInPublicationToOids() sees them as top-level
> EXCEPT_TABLE entries.
> + * The except_tables attached to TABLES IN SCHEMA nodes are left in place;
> + * ObjectsInPublicationToOids() qualifies names, validates schema membership,
> + * and flattens them once the schema OID is known.
>
> Can you please explain what does 'flatten' mean here.
>

Each TABLES IN SCHEMA ... EXCEPT (...) entry stores its own nested
list of EXCEPT tables. Flatten means collecting the PublicationTable
from each nested list into a single top-level except_pubtables list,
giving it the same structure as a FOR TABLE list that can be passed
directly to OpenTableList().

I've reworded the comment. We can also remove it if it seems unnecessary here.

> The flatten logic here is added by your patch001 only, it is not an
> existing logic. To me (in my initial round of review), it seems okay
> if we moved it to ObjectsInPublicationToOids(). The only thing is that
> the one error (table in EXCEPT clause does not belong to schema) which
> is possible to get at the parsing stage will now be emitted during
> pub-creation stage.

Yes, the logic was introduced in patch 0001 itself. I just highlighted
it for the case you mentioned, where the error is deferred instead of
being raised at parse time.

> But since it will keep the entire logic of
> except-list verification at one place and considering that
> creat/alter-pub is not so frequent operation, I am fine with it. But
> lets see if others have any comment here.
>

My thought was the same: to keep the logic in one place for now. Let's
see if others have any opinions on it as well.

> ~~
>
> I had a quick look at the changes:
>
> + * Include the ONLY-ness of this entry in its signature. EXCEPT
> + * (TABLE parent) excludes parent and its inheritance children,
> + * while EXCEPT (TABLE ONLY parent) excludes only parent itself.
>
> I think this will unconditionally apply to paritioned tables as well
> but for paritioned table, EXCEPT doc says that ONLY and * has no
> effect, but here it shows the effect:
>
> Thsi gives error:
> postgres=# CREATE PUBLICATION pub1 FOR TABLES IN SCHEMA public EXCEPT
> (TABLE ONLY tab_root), TABLES IN SCHEMA public EXCEPT (TABLE
> tab_root);
> ERROR:  42P17: schema "public" specified with conflicting EXCEPT lists
> LOCATION:  ProcessSchemaExceptTables, publicationcmds.c:299
>
> While this does not:
> postgres=#  CREATE PUBLICATION pub1 FOR TABLES IN SCHEMA public EXCEPT
> (TABLE tab_root), TABLES IN SCHEMA public EXCEPT (TABLE tab_root);
> CREATE PUBLICATION
>
> But I also checked column-list errors and found that even if columns
> are exact sames, we get error:
>
> postgres=# CREATE PUBLICATION PUB4 FOR TABLE T1(i), T1(i);
> ERROR:  42710: conflicting or redundant column lists for table "t1"
> LOCATION:  OpenTableList, publicationcmds.c:2312
>
> While this works:
> postgres=# CREATE PUBLICATION PUB4 FOR TABLE T1, T1;
> CREATE PUBLICATION
>
> This makes me think that even introducing the smartness of identifying
> ONLY in case of inherited tables and distinguishing it from
> parititoned tables is not required. We can just change your error
> message to 'conflicting or redundant EXCEPT lists for schmea "s1"' and
> throw error in all cases where schmea with except list repeats without
> actually comparing them. Does this sound reasonable?
>

Yes, that works for me as we have FOR TABLES example to follow. I've
made the changes in v20.

--
Thanks,
Nisha





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-13 10:01  shveta malik <shveta.malik@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  0 siblings, 2 replies; 196+ messages in thread

From: shveta malik @ 2026-07-13 10:01 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; shveta malik <shveta.malik@gmail.com>

On Fri, Jul 10, 2026 at 5:07 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
>
>
> Yes, that works for me as we have FOR TABLES example to follow. I've
> made the changes in v20.
>

Thanks! I had a quick look, few initial comments:


1)
GetTopMostAncestorInPublication():

+ if (ancestors == NIL)
+ return InvalidOid;

Should this be Assert or can there be a case where ancestors list can
come as NIL?

2)
GetAllSchemaPublicationRelations

+ if (!excluded && get_rel_relispartition(relid))
+ {
+ List    *ancestors = get_partition_ancestors(relid);
+ ListCell   *alc;
+
+ foreach(alc, ancestors)
+ {
+ if (list_member_oid(except_relids, lfirst_oid(alc)))
+ {
+ excluded = true;
+ break;
+ }
+ }
+ list_free(ancestors);
+ }

Should we check root only in except_relids instead of complete ancestor chain?

3)
postgres=# ALTER TABLE s2.tab_root_new ATTACH PARTITION s2.tab_root
FOR VALUES FROM (1) TO (2000);
ERROR:  55000: cannot attach table "tab_root" as partition because it
is referenced in publication "pub1" EXCEPT clause
DETAIL:  The publication EXCEPT clause cannot contain tables that are
partitions.
HINT:  Change the publication's EXCEPT clause using ALTER PUBLICATION
... SET ALL TABLES.
LOCATION:  ATExecAttachPartition, tablecmds.c:21107

pub1 is a schmea publication table here, I think HINT needs some adjustment.

4)
+ root_tup = SearchSysCache2(PUBLICATIONRELMAP,
+    ObjectIdGetDatum(llast_oid(ancestors)),
+    ObjectIdGetDatum(pub->oid));
+ if (HeapTupleIsValid(root_tup))
+ {
+ bool root_except = ((Form_pg_publication_rel) GETSTRUCT(root_tup))->prexcept;
+
+ ReleaseSysCache(root_tup);
+ if (root_except)
+ return false;
+ }

Above code snipet appears a lot many times either for relid or
llast_oid(ancestors), can we replace this with a common function like:

bool lookup_pub_relmap(Oid pubid, Oid relid, bool *is_except);  (or
get_publication_rel_entry or anything which you find better)

The return value will indicate when the relid is present. 'is_except'
will indicate whetehr it is marked with except flag or not. Then above
can be replaced with:

if (lookup_pub_relmap(pub->oid, llast_oid(ancestors), &root_except)
&& root_except)
return false;

Do this only if you feel it will simplify the code and apply it where it helps.

thanks
Shveta






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-14 09:34  shveta malik <shveta.malik@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  1 sibling, 0 replies; 196+ messages in thread

From: shveta malik @ 2026-07-14 09:34 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; shveta malik <shveta.malik@gmail.com>

Few comments for 002:

1)
@@ -210,9 +269,16 @@ ObjectsInPublicationToOids(List *pubobjspec_list,
ParseState *pstate,
  break;
  case PUBLICATIONOBJ_TABLES_IN_SCHEMA:
  schemaid = get_namespace_oid(pubobj->name, false);
+ schema_name = pubobj->name;
+ schema_repeated = list_member_oid(*schemas, schemaid);

  /* Filter out duplicates if user specifies "sch1, sch1" */
  *schemas = list_append_unique_oid(*schemas, schemaid);
+
+ ProcessSchemaExceptTables(schemaid, schema_name,
+   pubobj->except_tables, pstate,
+   schema_repeated, &schemas_with_except,
+

Should we extract schema_name inside ProcessSchemaExceptTables, as we
are passing schemaid to it. Generally one such arguement should
suffice.

2)
We can also avoid passing 'schema_repeated' to function
ProcessSchemaExceptTables(). Instead we can pass input/output arg
'schemas' similar to 'schemas_with_except'. Let it extract 'repeated'
from schemas internally and also populate it internally with unique
schema-oid.

3)
ProcessSchemaExceptTables:

can we avoid repeated dereferences of eobj->pubtable->relation. We can
work with:
RangeVar   *relation = eobj->pubtable->relation;

4)

+
+ if (except_tables != NIL)
+ *schemas_with_except = lappend_oid(*schemas_with_except, schemaid);

We can return early here:
if (except_tables == NIL)
return;

*schemas_with_except = lappend_oid(*schemas_with_except, schemaid);

thanks
Shveta






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-15 04:48  Peter Smith <smithpb2250@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  1 sibling, 1 reply; 196+ messages in thread

From: Peter Smith @ 2026-07-15 04:48 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; Amit Kapila <amit.kapila16@gmail.com>

Some review comments for v20-0001.

======
src/backend/catalog/pg_publication.c

check_publication_add_relation:

1.
+ else
+ {
+ /*
+ * If not in EXCEPT clause, a partition cannot be independently
+ * included when its partition root is in this publication's
+ * EXCEPT list.  Doing so would leave the catalog inconsistent
+ * (root excluded, partition explicitly included) and the
+ * ancestor-cascade rule would silently override the include at
+ * replication time.
+ *
+ * Only the root of a partition hierarchy can ever appear in an
+ * EXCEPT clause (a partition itself is rejected just above), so
+ * checking any intermediate ancestor cannot find a match; the
+ * root is the only one worth a catalog lookup.
+ */
+ Oid root = llast_oid(get_partition_ancestors(relid));
+ HeapTuple atup;
+
+ atup = SearchSysCache2(PUBLICATIONRELMAP,
+    ObjectIdGetDatum(root),
+    ObjectIdGetDatum(pubid));
+ if (HeapTupleIsValid(atup))
+ {
+ bool root_except = ((Form_pg_publication_rel) GETSTRUCT(atup))->prexcept;
+
+ ReleaseSysCache(atup);
+
+ if (root_except)
+ ereport(ERROR,
+ (errcode(ERRCODE_DUPLICATE_OBJECT),
+ errmsg("cannot add partition \"%s\" to publication \"%s\"",
+ RelationGetQualifiedRelationName(targetrel),
+ get_publication_name(pubid, false)),
+ errdetail("Ancestor \"%s\" of partition \"%s\" is currently listed
in the EXCEPT clause of the publication.",
+    quote_qualified_identifier(get_namespace_name(get_rel_namespace(root)),
+   get_rel_name(root)),
+    RelationGetQualifiedRelationName(targetrel)),
+ errhint("Change EXCEPT list using ALTER PUBLICATION ... SET TABLES
IN SCHEMA ... EXCEPT.")));
+ }
+ }

This whole part does not really need to be in `else` because previous
block throws ERROR. So it might be simpler code to remove the `else`
keyword and save some indentation.

~~~

2.
+ /*
+ * If not in EXCEPT clause, a partition cannot be independently
+ * included when its partition root is in this publication's
+ * EXCEPT list.  Doing so would leave the catalog inconsistent
+ * (root excluded, partition explicitly included) and the
+ * ancestor-cascade rule would silently override the include at
+ * replication time.

This could be worded simpler

SUGGESTION:
A partition cannot be included when its partition root is in the same
publication's EXCEPT list.  Doing so would leave the catalog
inconsistent (root excluded, partition included) and the ...

~~~

3.
+ * Only the root of a partition hierarchy can ever appear in an
+ * EXCEPT clause (a partition itself is rejected just above), so
+ * checking any intermediate ancestor cannot find a match; the
+ * root is the only one worth a catalog lookup.

This could be worded simpler

SUGGESTION
For partition hierachies, only the partition root can be in an EXCEPT
clause (a partition itself is rejected just above), so we only need to
look up the catalog for the root.

~~~

is_table_publication:

4.
"Returns true if the publication has explicitly included relation"


Typos in function comment.

/has explicitly included relation/has an explicitly-included relation/

~~~

5.
+ /*
+ * A publication can hold both explicit-include (prexcept=false) and
+ * EXCEPT (prexcept=true) rows for the same pubid.  Scan until we find an
+ * explicit-include row, rather than relying on the first row's prexcept
+ * value.
+ */

2x typos /explicit-include/explicitly-included/

~~~

6.
+ /*
+ * GetTopMostAncestorInPublication() returns InvalidOid both when no
+ * ancestor matched at all, and when the root is excluded via EXCEPT.
+ * Disambiguate here: if the root is excluded, the partition is never
+ * published through this publication, regardless of whether the
+ * partition's own schema is separately included.
+ */

When you say "the partition's own schema", it seems to be viewed
through the lens of FOR TABLES IN SCHEMA, but the partition could also
be explicitly included (e.g. FOR TABLE xxx).

IOW, does "own schema" need to be mentioned, or can that last sentence
say "regardless of whether the partition is separately included".

~~~

7.
+ *
+ * A pg_publication_rel row with prexcept=true means the table is
+ * explicitly excluded via EXCEPT and must not be reported as published,
+ * even if its schema is otherwise included.  A row with prexcept=false
+ * means it is explicitly included.  If no pg_publication_rel row exists,
+ * the table is published iff its schema appears in
+ * pg_publication_namespace.

Again, this comment seems viewed the the lens of FOR TABLES IN SCHEMA.

That last part, ("If no pg_publication_rel row exists, the table is
published iff its schema appears in pg_publication_namespace."), seems
not quite correct. For example, a table can be published by a FOR ALL
TABLES publication, which has nothing in pg_publication_namespace at
all.

======
src/backend/commands/publicationcmds.c

CheckExceptNotInTableList:

8.
/*
 * Check that no relation in except_rels is also present in explicitrelids,
 * the list of OIDs added to the publication by the explicit TABLE list.  A
 * table cannot be both explicitly published and excluded in the same DDL.
 *
 * Also check that no relation in explicitrelids is a partition whose
 * partition root is in except_rels; that would leave the catalog
 * inconsistent (root excluded, partition explicitly included) with the
 * ancestor-cascade rule silently overriding the include at replication
 * time.

The wording like "Check that no relation..." is a bit hard to read.

SUGGESTION
Check that a table is not both excluded and published in the same DDL.

An excluded relation (except_rels) cannot also be present in
explicitrelids, the list of OIDs added to the publication by the
explicit TABLE list.

Also reject any relation in explicitrelids whose partition root is in
except_rels. Otherwise the catalog would be inconsistent (root
excluded, partition explicitly included), and the ancestor-cascade
rule would silently override the include at replication time.

~~~

9.
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("partition \"%s\" cannot be both published and excluded",
+ quote_qualified_identifier(get_namespace_name(get_rel_namespace(explicitrelid)),
+    get_rel_name(explicitrelid))),
+ errdetail("Ancestor \"%s\" is also being excluded by this same command.",
+    RelationGetQualifiedRelationName(pri->relation))));

Hmm. Elsewhere there was an errdetail worded like:
errdetail("Ancestor \"%s\" of partition \"%s\" is currently listed in
the EXCEPT clause of the publication.",

Maybe they should both use that wording.

======
src/backend/replication/pgoutput/pgoutput.c

get_rel_sync_entry:

10.
+ /*
+ * GetTopMostAncestorInPublication() itself skips
+ * schema-based ancestor matches when the partition root
+ * is excluded via this publication's EXCEPT clause.
+ */
  ancestor = GetTopMostAncestorInPublication(pub->oid,
     ancestors,
     &level);

I'm not sure if that comment is helpful here or not. Why is the caller
describing the inner logic of the function it is calling?

~~~

11.
+ Oid root_relid;
+ HeapTuple tup;
+ bool is_except = false;

Given how this is used, maybe `root_is_except` is a better var name.

~~~

12.
+ /*
+ * schemaPubids is relid's own schema, independent of the
+ * ancestor walk above -- a partition can live in a
+ * different schema than its root.  Still need to check
+ * for exclusion here, using the top-most ancestor since
+ * only a root (non-partition) table can appear in an
+ * EXCEPT clause.
+ */

I don't know what "schemaPubids is relid's own schema" means. AFAIK
the `schemaPubids` was a list of publications this schemas is a member
of (??).

======
src/test/regress/sql/publication.sql

13.
+-- fail: partition still rejected from EXCEPT even when its own root is also
+-- named in the same EXCEPT list
+CREATE PUBLICATION testpub_except_partition_with_root
+    FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE
pub_test.testpub_part_s, TABLE pub_test.testpub_parted_s);
+

Is this test needed? Isn't the previous test ("only root tables are
allowed") covering this?

Alternatively, consider to put the partition in a different schema
(e.g. see the review comment #15 just below)

~~~

14.
+-- fail: same contradiction (explicit partition + EXCEPT-ed ancestor), but
+-- given in a single statement instead of two separate ones; the ancestor's
+-- EXCEPT row doesn't exist in the catalog yet when the explicit partition is
+-- validated, so this must be caught by comparing the in-memory lists

All that "; the ancestor's EXCEPT ..." is more like some explanation
about internals, and nothing really to do with the test case, so I was
not sure it needs to be in this comment.

~~~

15.
+-- test for EXCEPT clause with schema publication, where the excluded root's
+-- partition lives in a different schema that is separately, fully included
+-- (no EXCEPT) in the same publication.  The root's exclusion must cascade to
+-- the partition regardless of the partition's own schema membership.
+CREATE SCHEMA gpt_cross_sch1;
+CREATE SCHEMA gpt_cross_sch2;
+CREATE TABLE gpt_cross_sch1.croot (id int) PARTITION BY RANGE (id);
+CREATE TABLE gpt_cross_sch2.cpart1 PARTITION OF gpt_cross_sch1.croot
FOR VALUES FROM (1) TO (10);
+
+SET client_min_messages = 'ERROR';
+CREATE PUBLICATION pub_cross_schema_except FOR TABLES IN SCHEMA
gpt_cross_sch1 EXCEPT (TABLE gpt_cross_sch1.croot), TABLES IN SCHEMA
gpt_cross_sch2;

IIUC, a different way to do this test would be to name the partition explicitly:
CREATE PUBLICATION pub_cross_schema_except FOR TABLES IN SCHEMA
gpt_cross_sch1 EXCEPT (TABLE gpt_cross_sch1.croot), TABLE
gpt_cross_sch2.cpart1;

Is it worth adding this way as well?

======
src/test/subscription/t/037_except.pl

16.
+$node_publisher->safe_psql('postgres',
+ "CREATE PUBLICATION cross_sch_pub FOR TABLES IN SCHEMA csch1 EXCEPT
(TABLE csch1.croot), TABLES IN SCHEMA csch2"

Wondering if you should also say "WITH (publish_via_partition_root =
false)"... Even though it is the default maybe it helps to be more
explicitLy, since later you do try to insert directly into partitions
to see the effect.

======
Kind Regards,
Peter Smith.
Fujitsu Australia






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-15 08:42  Peter Smith <smithpb2250@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  1 sibling, 1 reply; 196+ messages in thread

From: Peter Smith @ 2026-07-15 08:42 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; Amit Kapila <amit.kapila16@gmail.com>

Hi Nisha.

Here are my review comments for all the rest of the v20* patches

//////////
Patch v20-0002.
//////////

======
Commit message.

1.
entries, build a sorted signature per schema OID, and compare it
against any prior mention of the same schema in the same statement,
erroring on a mismatch.

~

It does more than that though -- it also checks there are no clashes
of the same schema with/without EXCEPT.

======
src/backend/commands/publicationcmds.c

ProcessSchemaExceptTables:

2.
+ * Also rejects a repeated mention of the same schema in the same TABLES IN
+ * SCHEMA list if either mention specifies a non-empty EXCEPT list, without
+ * checking whether the two EXCEPT lists actually name the same tables. This
+ * mirrors OpenTableList()'s handling of repeated tables with column lists
+ * (e.g. "FOR TABLE t1(a), t1(a)" is rejected even though the lists match):
+ * two mentions of the same schema wouldn't have a well-defined single
+ * EXCEPT list to enforce, so it's rejected as conflicting or redundant
+ * rather than silently unioned or compared for equivalence.
+ * *schemas_with_except accumulates the OIDs of schemas already seen with a
+ * non-empty EXCEPT list in this statement.

Some rewording might be needed. The "if either" and "the two" make it
sound like there are only 2 members in the schema list, but there
might be many schemas:

e.g. FOR TABLES IN SCHEMA S1,S1,S1,S1,S1,S1,S1,S1,S1,S1;

~~~

3.
Something about this logic seems over-complicated to me.

e.g. All this stuff about `schema_repeated`?

AFAICT, you only need to be accumulating 2 lists
- list1 = schemas without EXCEPT
- list2 = schemas with EXCEPT

To check conflicting the logic is simple:
- before adding to list1 ensure same schema is not already in list2, else error
- before adding to list2 ensure same schema is not already in list1, else error

Those checks can be done before you verify the qualified schema names
match their schema...

======
src/backend/parser/gram.y

4.
 /*
  * Process pubobjspec_list to check for errors in any of the objects and
  * convert PUBLICATIONOBJ_CONTINUATION into appropriate PublicationObjSpecType.
- * Also flattens except_tables from TABLES IN SCHEMA nodes into the list so
- * that ObjectsInPublicationToOids() sees them as top-level
EXCEPT_TABLE entries.
+ * The except_tables attached to TABLES IN SCHEMA nodes are left in place here;
+ * ObjectsInPublicationToOids() qualifies their names, validates schema
+ * membership, and merges the qualified tables into its except_pubtables
+ * output list once the schema OID is known.
  */

Maybe add a blank line before the new text here.

//////////
Patch v20-0003.
//////////

======
src/test/regress/sql/publication.sql

1.
+-- fail: partition still rejected from EXCEPT even when its own root is also
+-- named in the same EXCEPT list, via ALTER ... ADD
+ALTER PUBLICATION testpub_alter_except
+    ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE
pub_test.testpub_part_s, TABLE pub_test.testpub_parted_s);
+

Not sure how this test case differs from a plain-ol'
cannot-specify-a-partition-in-EXCEPT test case.

//////////
Patch v20-0004
//////////

======
src/backend/commands/publicationcmds.c

AlterPublicationSchemaExceptTables:

1.
+ /*
+ * Validate that no excluded table is also already explicitly
+ * published (exact match), and that no already-published partition
+ * has its root among the tables being newly excluded here.
+ */

The comment seems to be over-explaining the logic of the function it is calling.

How about something simpler.

SUGGESTION
Check that there is no clash between what tables are included and excluded.

~~~

PublicationDropTables:

2.
+ if (is_except)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("cannot drop table \"%s\" from publication \"%s\"",
+ RelationGetQualifiedRelationName(rel),
+ get_publication_name(pubid, false)),
+ errdetail("The table is currently listed in the EXCEPT clause of the
publication."),
+ errhint("Use ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT
to drop the table from the EXCEPT list.")));
+

This new errhint makes more sense, but I felt it's more natural to say
you are "removing" something from a list, not "dropping" something
from a list.

So:

SUGGESTION #1
Use ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT to remove a
table from the EXCEPT list.

or, more generically:

SUGGESTION #2
Use ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT to modify
the EXCEPT list.

//////////
Patch v20-0005 (docs)
//////////

======
doc/src/sgml/ref/create_publication.sgml

      <para>
       For partitioned tables, only the root partitioned table may be specified
-      in <literal>EXCEPT</literal>. Doing so excludes the root table and
-      all of its partitions from replication. The optional
+      in <literal>EXCEPT</literal>. Excluding the root table automatically
+      excludes all of its partitions from replication, including those in
+      schemas that are otherwise included in the publication. The optional
       <literal>ONLY</literal> and <literal>*</literal> has no effect for
       partitioned tables.
      </para>

In hindsight, I thought it would seem weird to have the word
"including" in the sentence where you are trying to describe excluded
tables.

/including those/even those/

======
Kind Regards,
Peter Smith.
Fujitsu Australia






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-15 16:46  Nisha Moond <nisha.moond412@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  1 sibling, 4 replies; 196+ messages in thread

From: Nisha Moond @ 2026-07-15 16:46 UTC (permalink / raw)
  To: shveta malik <shveta.malik@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Mon, Jul 13, 2026 at 3:31 PM shveta malik <shveta.malik@gmail.com> wrote:
>
> On Fri, Jul 10, 2026 at 5:07 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
> >
> >
> > Yes, that works for me as we have FOR TABLES example to follow. I've
> > made the changes in v20.
> >
>
> Thanks! I had a quick look, few initial comments:
>
>
> 1)
> GetTopMostAncestorInPublication():
>
> + if (ancestors == NIL)
> + return InvalidOid;
>
> Should this be Assert or can there be a case where ancestors list can
> come as NIL?
>

I found one case where ancestors can be NIL.
Test case:
  CREATE TABLE t1 (a int) PARTITION BY RANGE (a);
  CREATE TABLE t1_part PARTITION OF t1 FOR VALUES FROM (1) TO (100);
  CREATE PUBLICATION mypub FOR TABLE t1;

-- Get the partition into the pending-detach state:
 -- Session A:
  BEGIN;
  SELECT * FROM t1;
  -- leave open

-- Session B (blocks, waiting on Session A's lock on t1):
  ALTER TABLE t1 DETACH PARTITION t1_part CONCURRENTLY;

-- Session C, while B is blocked:
  SELECT * FROM pg_get_publication_tables('{mypub}'::text[],
't1_part'::regclass);

In this scenario, Session C reaches GetTopMostAncestorInPublication()
with ancestors == NIL. So I think we should keep return InvalidOid;
rather than replacing it with an Assert.

While investigating this race, I also hit assertions at places that
call "llast_oid(ancestors)" without checking for NIL, for example in
check_publication_add_relation() and RelationBuildPublicationDesc(). I
fixed those by guarding with if (ancestors != NIL).

But due to this same race, other existing callers of llast_oid() on
HEAD that assume ancestors is never NIL can also hit the following
assertion:
  "TRAP: failed Assert("list != NIL"), File:
"../../../../src/include/nodes/pg_list.h" ..."

One such case is pgoutput.c:get_rel_sync_entry(). To reproduce on HEAD:
-- create a slot
SELECT pg_create_logical_replication_slot('myslot', 'pgoutput');

-- get the partition into the pending-detach state (using same A & B
sessions), and in session C run -
INSERT INTO t1_part VALUES (5);
SELECT * FROM pg_logical_slot_get_binary_changes('myslot', NULL, NULL,
'proto_version', '1', 'publication_names', 'mypub');

I think this should be handled separately after analyzing whether
there's a better fix than simply adding if (ancestors != NIL) guards
at each call site.
Note: Other callers of llast_oid(ancestors) may need similar review.

Thoughts?

> 2)
> GetAllSchemaPublicationRelations
>
> + if (!excluded && get_rel_relispartition(relid))
> + {
> + List    *ancestors = get_partition_ancestors(relid);
> + ListCell   *alc;
> +
> + foreach(alc, ancestors)
> + {
> + if (list_member_oid(except_relids, lfirst_oid(alc)))
> + {
> + excluded = true;
> + break;
> + }
> + }
> + list_free(ancestors);
> + }
>
> Should we check root only in except_relids instead of complete ancestor chain?
>

yes, corrected.

> 3)
> postgres=# ALTER TABLE s2.tab_root_new ATTACH PARTITION s2.tab_root
> FOR VALUES FROM (1) TO (2000);
> ERROR:  55000: cannot attach table "tab_root" as partition because it
> is referenced in publication "pub1" EXCEPT clause
> DETAIL:  The publication EXCEPT clause cannot contain tables that are
> partitions.
> HINT:  Change the publication's EXCEPT clause using ALTER PUBLICATION
> ... SET ALL TABLES.
> LOCATION:  ATExecAttachPartition, tablecmds.c:21107
>
> pub1 is a schmea publication table here, I think HINT needs some adjustment.
>

Fixed.

> 4)
> + root_tup = SearchSysCache2(PUBLICATIONRELMAP,
> +    ObjectIdGetDatum(llast_oid(ancestors)),
> +    ObjectIdGetDatum(pub->oid));
> + if (HeapTupleIsValid(root_tup))
> + {
> + bool root_except = ((Form_pg_publication_rel) GETSTRUCT(root_tup))->prexcept;
> +
> + ReleaseSysCache(root_tup);
> + if (root_except)
> + return false;
> + }
>
> Above code snipet appears a lot many times either for relid or
> llast_oid(ancestors), can we replace this with a common function like:
>
> bool lookup_pub_relmap(Oid pubid, Oid relid, bool *is_except);  (or
> get_publication_rel_entry or anything which you find better)
>
> The return value will indicate when the relid is present. 'is_except'
> will indicate whetehr it is marked with except flag or not. Then above
> can be replaced with:
>
> if (lookup_pub_relmap(pub->oid, llast_oid(ancestors), &root_except)
> && root_except)
> return false;
>
> Do this only if you feel it will simplify the code and apply it where it helps.
>

You're right. The same check appears in five places. I replaced it
with a helper function, get_publication_rel_entry(), which
significantly reduces code duplication.
~~~

Attached is the v21 patch set addressing the above changes, along with
all other comments for v20 at [1], [2], and [3].

[1] https://www.postgresql.org/message-id/CAJpy0uCFCdL97L3Pt8f586br5irqkzCa_i3tXMjH6JFCPxxr4Q%40mail.gma...
[2] https://www.postgresql.org/message-id/CAHut%2BPuJE947Y3WPo%2BcaEpEojQdRXryS2KjBLBr12rb9RQ95Zw%40mail...
[3] https://www.postgresql.org/message-id/CAHut%2BPsGg7Pi2CM5eBjb8s6FCPb5XmyWaBUxPrDSzt_2wK4Gfg%40mail.g...

--
Thanks,
Nisha

Attachments: download all (5 files, .tar.gz)

v21-0001-Support-EXCEPT-clause-for-schema-level-publicati.patch (application/x-patch, 78.7K) download From 3dbef0f2aca0c206ee34e089358b8052fd3bb700 Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Tue, 16 Jun 2026 10:58:49 +0530 Subject: [PATCH v21 1/5] Support EXCEPT clause for schema-level publications Extend table exclusion support in publications to allow specific tables to be excluded from schema-level publications using an EXCEPT clause in CREATE PUBLICATION. Supported syntax: CREATE PUBLICATION <pub> FOR TABLES IN SCHEMA s EXCEPT (TABLE t1,...); --- src/backend/catalog/pg_publication.c | 258 ++++++++++++++++---- src/backend/commands/publicationcmds.c | 198 ++++++++++++++- src/backend/commands/tablecmds.c | 20 +- src/backend/parser/gram.y | 54 +++- src/backend/replication/pgoutput/pgoutput.c | 32 ++- src/backend/utils/cache/relcache.c | 44 ++-- src/bin/psql/describe.c | 18 ++ src/bin/psql/tab-complete.in.c | 35 ++- src/include/catalog/pg_publication.h | 1 + src/include/commands/publicationcmds.h | 2 + src/include/nodes/parsenodes.h | 2 + src/test/regress/expected/publication.out | 224 ++++++++++++++++- src/test/regress/sql/publication.sql | 143 ++++++++++- src/test/subscription/t/037_except.pl | 208 +++++++++++++++- 14 files changed, 1141 insertions(+), 98 deletions(-) diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index 1ec94c851b2..785c9effdd9 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -48,14 +48,38 @@ typedef struct * table. */ } published_rel; +/* + * Check whether a pg_publication_rel row exists for (pubid, relid); if so, + * set *is_except to its prexcept flag. + */ +bool +get_publication_rel_entry(Oid pubid, Oid relid, bool *is_except) +{ + HeapTuple tup; + + tup = SearchSysCache2(PUBLICATIONRELMAP, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (!HeapTupleIsValid(tup)) + return false; + + *is_except = ((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept; + ReleaseSysCache(tup); + + return true; +} + /* * Check if relation can be in given publication and throws appropriate * error if not. */ static void -check_publication_add_relation(PublicationRelInfo *pri) +check_publication_add_relation(PublicationRelInfo *pri, Oid pubid) { Relation targetrel = pri->relation; + Oid relid = RelationGetRelid(targetrel); + Oid root; + bool root_except; const char *relname; const char *errormsg; @@ -70,12 +94,42 @@ check_publication_add_relation(PublicationRelInfo *pri) errormsg = gettext_noop("cannot add relation \"%s\" to publication"); } - /* If in EXCEPT clause, must be root partitioned table */ - if (pri->except && targetrel->rd_rel->relispartition) - ereport(ERROR, - (errcode(ERRCODE_INVALID_PARAMETER_VALUE), - errmsg(errormsg, relname), - errdetail("This operation is not supported for individual partitions."))); + if (targetrel->rd_rel->relispartition) + { + if (pri->except) + { + /* If in EXCEPT clause, must be root partitioned table */ + ereport(ERROR, + (errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg(errormsg, relname), + errdetail("This operation is not supported for individual partitions."))); + } + + /* + * A partition cannot be included when its partition root is in the + * same publication's EXCEPT list. Doing so would leave the catalog + * inconsistent (root excluded, partition included) and the + * ancestor-cascade rule would silently override the include at + * replication time. + * + * For partition hierarchies, only the partition root can be in an + * EXCEPT clause (a partition itself is rejected just above), so we + * only need to look up the catalog for the root. + */ + root = llast_oid(get_partition_ancestors(relid)); + + if (get_publication_rel_entry(pubid, root, &root_except) && root_except) + ereport(ERROR, + errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("cannot add partition \"%s\" to publication \"%s\"", + RelationGetQualifiedRelationName(targetrel), + get_publication_name(pubid, false)), + errdetail("Ancestor \"%s\" of partition \"%s\" is currently listed in the EXCEPT clause of the publication.", + quote_qualified_identifier(get_namespace_name(get_rel_namespace(root)), + get_rel_name(root)), + RelationGetQualifiedRelationName(targetrel)), + errhint("Change EXCEPT list using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT.")); + } /* Must be a regular or partitioned table */ if (RelationGetForm(targetrel)->relkind != RELKIND_RELATION && @@ -319,7 +373,7 @@ is_schema_publication(Oid pubid) } /* - * Returns true if the publication has explicitly included relation (i.e., + * Returns true if the publication has an explicitly-included relation (i.e., * not marked as EXCEPT). */ bool @@ -340,19 +394,20 @@ is_table_publication(Oid pubid) scan = systable_beginscan(pubrelsrel, PublicationRelPrpubidIndexId, true, NULL, 1, &scankey); - tup = systable_getnext(scan); - if (HeapTupleIsValid(tup)) - { - Form_pg_publication_rel pubrel; - pubrel = (Form_pg_publication_rel) GETSTRUCT(tup); - - /* - * For any publication, pg_publication_rel contains either only EXCEPT - * entries or only explicitly included tables. Therefore, examining - * the first tuple is sufficient to determine table inclusion. - */ - result = !pubrel->prexcept; + /* + * A publication can hold both explicitly-included (prexcept=false) and + * EXCEPT (prexcept=true) rows for the same pubid. Scan until we find an + * explicitly-included row, rather than relying on the first row's + * prexcept value. + */ + while (HeapTupleIsValid(tup = systable_getnext(scan))) + { + if (!((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept) + { + result = true; + break; + } } systable_endscan(scan); @@ -456,11 +511,29 @@ GetPubPartitionOptionRelations(List *result, PublicationPartOpt pub_partopt, * ancestor is at the end of the list. */ Oid -GetTopMostAncestorInPublication(Oid puboid, List *ancestors, int *ancestor_level) +GetTopMostAncestorInPublication(Oid puboid, List *ancestors, + int *ancestor_level) { ListCell *lc; Oid topmost_relid = InvalidOid; int level = 0; + bool root_except; + + if (ancestors == NIL) + return InvalidOid; + + /* + * If the partition root (the last element of ancestors) is excluded from + * this publication via its EXCEPT clause, the partition is not published + * through this publication at all, so we short-circuit and return + * InvalidOid without walking the ancestor list. Only the root of a + * partition hierarchy can ever appear in a publication's EXCEPT clause (a + * partition itself is rejected from EXCEPT elsewhere), so it's the only + * one worth a catalog lookup. + */ + if (get_publication_rel_entry(puboid, llast_oid(ancestors), &root_except) && + root_except) + return InvalidOid; /* * Find the "topmost" ancestor that is in this publication. @@ -555,21 +628,33 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, * duplicates, it's here just to provide nicer error message in common * case. The real protection is the unique key on the catalog. */ - if (SearchSysCacheExists2(PUBLICATIONRELMAP, ObjectIdGetDatum(relid), - ObjectIdGetDatum(pubid))) { - table_close(rel, RowExclusiveLock); + bool is_except; - if (if_not_exists) - return InvalidObjectAddress; - - ereport(ERROR, - (errcode(ERRCODE_DUPLICATE_OBJECT), - errmsg("relation \"%s\" is already member of publication \"%s\"", - RelationGetRelationName(targetrel), pub->name))); + if (get_publication_rel_entry(pubid, relid, &is_except)) + { + table_close(rel, RowExclusiveLock); + + if (if_not_exists) + return InvalidObjectAddress; + + if (is_except) + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("cannot add table \"%s\" to publication \"%s\"", + RelationGetQualifiedRelationName(targetrel), + pub->name), + errdetail("The table is currently listed in the EXCEPT clause of the publication."), + errhint("Change EXCEPT list using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT."))); + else + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("relation \"%s\" is already member of publication \"%s\"", + RelationGetRelationName(targetrel), pub->name))); + } } - check_publication_add_relation(pri); + check_publication_add_relation(pri, pubid); /* Validate and translate column names into a Bitmapset of attnums. */ attnums = pub_collist_validate(pri->relation, pri->columns); @@ -992,12 +1077,13 @@ GetIncludedPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) * Gets list of table oids that were specified in the EXCEPT clause for a * publication. * - * This should only be used FOR ALL TABLES publications. + * This is used for FOR ALL TABLES and FOR TABLES IN SCHEMA publications, + * both of which support EXCEPT TABLE. */ List * GetExcludedPublicationTables(Oid pubid, PublicationPartOpt pub_partopt) { - Assert(GetPublication(pubid)->alltables); + Assert(GetPublication(pubid)->alltables || is_schema_publication(pubid)); return get_publication_relations(pubid, pub_partopt, true); } @@ -1059,15 +1145,15 @@ GetAllPublicationRelations(Oid pubid, char relkind, bool pubviaroot) TableScanDesc scan; HeapTuple tuple; List *result = NIL; - List *exceptlist = NIL; + List *except_relids = NIL; Assert(!(relkind == RELKIND_SEQUENCE && pubviaroot)); /* EXCEPT filtering applies only to relations, not sequences */ if (relkind == RELKIND_RELATION) - exceptlist = GetExcludedPublicationTables(pubid, pubviaroot ? - PUBLICATION_PART_ROOT : - PUBLICATION_PART_LEAF); + except_relids = GetExcludedPublicationTables(pubid, pubviaroot ? + PUBLICATION_PART_ROOT : + PUBLICATION_PART_LEAF); classRel = table_open(RelationRelationId, AccessShareLock); @@ -1085,7 +1171,7 @@ GetAllPublicationRelations(Oid pubid, char relkind, bool pubviaroot) if (is_publishable_class(relid, relForm) && !(relForm->relispartition && pubviaroot) && - !list_member_oid(exceptlist, relid)) + !list_member_oid(except_relids, relid)) result = lappend_oid(result, relid); } @@ -1107,7 +1193,7 @@ GetAllPublicationRelations(Oid pubid, char relkind, bool pubviaroot) if (is_publishable_class(relid, relForm) && !relForm->relispartition && - !list_member_oid(exceptlist, relid)) + !list_member_oid(except_relids, relid)) result = lappend_oid(result, relid); } @@ -1242,22 +1328,63 @@ GetSchemaPublicationRelations(Oid schemaid, PublicationPartOpt pub_partopt) /* * Gets the list of all relations published by FOR TABLES IN SCHEMA - * publication. + * publication, excluding any tables listed in the EXCEPT clause. */ List * GetAllSchemaPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) { List *result = NIL; List *pubschemalist = GetPublicationSchemas(pubid); + List *except_relids = NIL; ListCell *cell; + /* get the list of tables excluded via EXCEPT TABLE for this publication */ + if (pubschemalist != NIL) + except_relids = GetExcludedPublicationTables(pubid, pub_partopt); + foreach(cell, pubschemalist) { Oid schemaid = lfirst_oid(cell); List *schemaRels = NIL; schemaRels = GetSchemaPublicationRelations(schemaid, pub_partopt); - result = list_concat(result, schemaRels); + + if (except_relids != NIL) + { + /* filter out any tables that appear in the EXCEPT list */ + ListCell *rlc; + + foreach(rlc, schemaRels) + { + Oid relid = lfirst_oid(rlc); + bool excluded = list_member_oid(except_relids, relid); + + /* + * A partition whose root is in the publication's EXCEPT list + * is also excluded, even if the partition itself lives in a + * different (included) schema. Only the topmost root of a + * partition hierarchy can ever appear in EXCEPT (see + * check_publication_add_relation()), so it's enough to check + * the last element of the ancestors list, rather than walking + * the whole chain. + */ + if (!excluded && get_rel_relispartition(relid)) + { + List *ancestors = get_partition_ancestors(relid); + + if (ancestors != NIL) + excluded = list_member_oid(except_relids, + llast_oid(ancestors)); + list_free(ancestors); + } + + if (!excluded) + result = lappend_oid(result, relid); + } + list_free(schemaRels); + } + else + result = list_concat(result, schemaRels); } return result; @@ -1390,20 +1517,49 @@ is_table_publishable_in_publication(Oid relid, Publication *pub) * If it's false, the partition is covered by its ancestor's presence in * the publication, it should be included (return true). */ - if (relispartition && - OidIsValid(GetTopMostAncestorInPublication(pub->oid, ancestors, NULL))) - return !pub->pubviaroot; + if (relispartition) + { + bool root_except; + + if (OidIsValid(GetTopMostAncestorInPublication(pub->oid, ancestors, NULL))) + return !pub->pubviaroot; + + /* + * GetTopMostAncestorInPublication() returns InvalidOid both when no + * ancestor matched at all, and when the root is excluded via EXCEPT. + * Disambiguate here: if the root is excluded, the partition is never + * published through this publication, regardless of whether the + * partition's schema is separately included. ancestors can be NIL + * for a partition whose DETACH ... CONCURRENTLY is pending, in which + * case there is no ancestor to check. + */ + if (ancestors != NIL && + get_publication_rel_entry(pub->oid, llast_oid(ancestors), &root_except) && + root_except) + return false; + } /* * Check whether the table is explicitly published via pg_publication_rel * or pg_publication_namespace. + * + * A pg_publication_rel row with prexcept=true means the table is + * explicitly excluded via EXCEPT and must not be reported as published, + * even if its schema is otherwise included. A row with prexcept=false + * means it is explicitly included. If no pg_publication_rel row exists, + * the table is published iff its schema appears in + * pg_publication_namespace. */ - return (SearchSysCacheExists2(PUBLICATIONRELMAP, - ObjectIdGetDatum(relid), - ObjectIdGetDatum(pub->oid)) || - SearchSysCacheExists2(PUBLICATIONNAMESPACEMAP, - ObjectIdGetDatum(get_rel_namespace(relid)), - ObjectIdGetDatum(pub->oid))); + { + bool is_except; + + if (get_publication_rel_entry(pub->oid, relid, &is_except)) + return !is_except; + } + + return SearchSysCacheExists2(PUBLICATIONNAMESPACEMAP, + ObjectIdGetDatum(get_rel_namespace(relid)), + ObjectIdGetDatum(pub->oid)); } /* diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 440adb356ad..edc8a20ae81 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -22,6 +22,7 @@ #include "catalog/namespace.h" #include "catalog/objectaccess.h" #include "catalog/objectaddress.h" +#include "catalog/partition.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" #include "catalog/pg_namespace.h" @@ -71,6 +72,7 @@ static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); static char defGetGeneratedColsOption(DefElem *def); +static void CheckExceptNotInTableList(List *except_rels, List *explicitrelids); static void @@ -181,7 +183,7 @@ parse_publication_options(ParseState *pstate, */ static void ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, - List **rels, List **exceptrels, List **schemas) + List **rels, List **except_pubtables, List **schemas) { ListCell *cell; PublicationObjSpec *pubobj; @@ -200,7 +202,7 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, { case PUBLICATIONOBJ_EXCEPT_TABLE: pubobj->pubtable->except = true; - *exceptrels = lappend(*exceptrels, pubobj->pubtable); + *except_pubtables = lappend(*except_pubtables, pubobj->pubtable); break; case PUBLICATIONOBJ_TABLE: pubobj->pubtable->except = false; @@ -224,6 +226,38 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, /* Filter out duplicates if user specifies "sch1, sch1" */ *schemas = list_append_unique_oid(*schemas, schemaid); + + /* + * Qualify unqualified EXCEPT table names with the resolved + * current schema and reject any explicitly cross-schema + * entries. This mirrors the parse-time handling done for + * TABLES_IN_SCHEMA in preprocess_pubobj_list(), deferred here + * because CURRENT_SCHEMA is not known until execution time. + */ + if (pubobj->except_tables != NIL) + { + char *cur_schema_name = get_namespace_name(schemaid); + + foreach_ptr(PublicationObjSpec, eobj, pubobj->except_tables) + { + const char *eobj_schemaname = + eobj->pubtable->relation->schemaname; + const char *eobj_relname = + eobj->pubtable->relation->relname; + + if (eobj_schemaname == NULL) + eobj->pubtable->relation->schemaname = cur_schema_name; + else if (strcmp(eobj_schemaname, cur_schema_name) != 0) + ereport(ERROR, + errcode(ERRCODE_INVALID_OBJECT_DEFINITION), + errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", + quote_qualified_identifier(eobj_schemaname, eobj_relname), + cur_schema_name)); + + *except_pubtables = lappend(*except_pubtables, + eobj->pubtable); + } + } break; default: /* shouldn't happen */ @@ -770,6 +804,61 @@ TransformPubWhereClauses(List *tables, const char *queryString, } } +/* + * Check that a table is not both excluded and published in the same DDL. + * + * An excluded relation (except_rels) cannot also be present in + * explicitrelids, the list of OIDs added to the publication by the explicit + * TABLE list. + * + * Also reject any relation in explicitrelids whose partition root is in + * except_rels. Otherwise the catalog would be inconsistent (root excluded, + * partition explicitly included), and the ancestor-cascade rule would + * silently override the include at replication time. + */ +static void +CheckExceptNotInTableList(List *except_rels, List *explicitrelids) +{ + foreach_oid(explicitrelid, explicitrelids) + { + Oid root = InvalidOid; + + if (get_rel_relispartition(explicitrelid)) + { + List *ancestors = get_partition_ancestors(explicitrelid); + + /* + * ancestors is NIL for a partition with a pending DETACH + * CONCURRENTLY. + */ + if (ancestors != NIL) + root = llast_oid(ancestors); + list_free(ancestors); + } + + foreach_ptr(PublicationRelInfo, pri, except_rels) + { + Oid exceptrelid = RelationGetRelid(pri->relation); + + if (exceptrelid == explicitrelid) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" cannot be both published and excluded", + RelationGetQualifiedRelationName(pri->relation))); + + if (OidIsValid(root) && exceptrelid == root) + ereport(ERROR, + (errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("partition \"%s\" cannot be both published and excluded", + quote_qualified_identifier(get_namespace_name(get_rel_namespace(explicitrelid)), + get_rel_name(explicitrelid))), + errdetail("Ancestor \"%s\" of partition \"%s\" is currently listed in the EXCEPT clause of this command.", + RelationGetQualifiedRelationName(pri->relation), + quote_qualified_identifier(get_namespace_name(get_rel_namespace(explicitrelid)), + get_rel_name(explicitrelid))))); + } + } +} /* * Given a list of tables that are going to be added to a publication, @@ -849,7 +938,7 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) char publish_generated_columns; AclResult aclresult; List *relations = NIL; - List *exceptrelations = NIL; + List *except_pubtables = NIL; List *schemaidlist = NIL; /* must have CREATE privilege on database */ @@ -936,16 +1025,16 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) /* Associate objects with the publication. */ ObjectsInPublicationToOids(stmt->pubobjects, pstate, &relations, - &exceptrelations, &schemaidlist); + &except_pubtables, &schemaidlist); if (stmt->for_all_tables) { /* Process EXCEPT table list */ - if (exceptrelations != NIL) + if (except_pubtables != NIL) { List *rels; - rels = OpenTableList(exceptrelations); + rels = OpenTableList(except_pubtables); PublicationAddTables(puboid, rels, true, NULL); CloseTableList(rels); } @@ -959,6 +1048,8 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) } else if (!stmt->for_all_sequences) { + List *explicitrelids = NIL; + /* FOR TABLES IN SCHEMA requires superuser */ if (schemaidlist != NIL && !superuser()) ereport(ERROR, @@ -977,6 +1068,19 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) schemaidlist != NIL, publish_via_partition_root); + /* + * Collect explicit table OIDs now, before we close the relation + * list, so that except-table validation below can check for + * contradictions without relying on a catalog scan that might not + * yet see the just-inserted rows. + */ + if (except_pubtables != NIL) + { + foreach_ptr(PublicationRelInfo, pri, rels) + explicitrelids = lappend_oid(explicitrelids, + RelationGetRelid(pri->relation)); + } + PublicationAddTables(puboid, rels, true, NULL); CloseTableList(rels); } @@ -989,6 +1093,26 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) */ LockSchemaList(schemaidlist); PublicationAddSchemas(puboid, schemaidlist, true, NULL); + + if (except_pubtables != NIL) + { + List *except_rels; + + except_rels = OpenTableList(except_pubtables); + + /* + * Validate that each excluded table is not also in the + * explicit table list (which would be contradictory), and + * that no explicit partition's root is in the except list. + * Use the in-memory explicitrelids collected above rather + * than re-reading the catalog, which may not yet see the + * just-inserted rows. + */ + CheckExceptNotInTableList(except_rels, explicitrelids); + + PublicationAddTables(puboid, except_rels, true, NULL); + CloseTableList(except_rels); + } } } @@ -1683,12 +1807,12 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) else { List *relations = NIL; - List *exceptrelations = NIL; + List *except_pubtables = NIL; List *schemaidlist = NIL; Oid pubid = pubform->oid; ObjectsInPublicationToOids(stmt->pubobjects, pstate, &relations, - &exceptrelations, &schemaidlist); + &except_pubtables, &schemaidlist); CheckAlterPublication(stmt, tup, relations, schemaidlist); @@ -1711,7 +1835,7 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) errmsg("publication \"%s\" does not exist", stmt->pubname)); - relations = list_concat(relations, exceptrelations); + relations = list_concat(relations, except_pubtables); AlterPublicationTables(stmt, tup, relations, pstate->p_sourcetext, schemaidlist != NIL); AlterPublicationSchemas(stmt, tup, schemaidlist); @@ -1829,6 +1953,62 @@ RemovePublicationSchemaById(Oid psoid) table_close(rel, RowExclusiveLock); } +/* + * Remove any EXCEPT clause entries for a relation from schema publications. + * Called when a table changes schema (ALTER TABLE ... SET SCHEMA), so that + * a schema-scoped exclusion does not silently follow the table to its new + * schema. + */ +void +RemoveSchemaPubExceptForRel(Oid relid, Oid oldNspOid, Oid newNspOid) +{ + List *pubids; + + /* + * If the table is not actually moving to a different schema (no-op ALTER + * TABLE ... SET SCHEMA <current_schema>), there is nothing to do. + */ + if (oldNspOid == newNspOid) + return; + + pubids = GetRelationExcludedPublications(relid); + + foreach_oid(pubid, pubids) + { + Oid proid; + + /* + * This problem does not apply to FOR ALL TABLES publications, because + * their EXCEPT clause is publication-scoped, not schema-scoped: the + * exclusion should persist regardless of what schema the table is in. + */ + if (!is_schema_publication(pubid)) + continue; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddress obj; + + ObjectAddressSet(obj, PublicationRelRelationId, proid); + + ereport(DEBUG2, + errmsg_internal("auto-remove exclusion of table \"%s.%s\" from publication \"%s\": table moved to schema \"%s\"", + get_namespace_name(oldNspOid), + get_rel_name(relid), + get_publication_name(pubid, false), + get_namespace_name(newNspOid))); + + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + list_free(pubids); +} + /* * Open relations specified by a PublicationTable list. * The returned tables are locked in ShareUpdateExclusiveLock mode in order to diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..4e0897e9691 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -49,6 +49,7 @@ #include "catalog/pg_opclass.h" #include "catalog/pg_policy.h" #include "catalog/pg_proc.h" +#include "catalog/pg_publication.h" #include "catalog/pg_publication_rel.h" #include "catalog/pg_rewrite.h" #include "catalog/pg_statistic_ext.h" @@ -63,6 +64,7 @@ #include "commands/event_trigger.h" #include "commands/extension.h" #include "commands/repack.h" +#include "commands/publicationcmds.h" #include "commands/sequence.h" #include "commands/tablecmds.h" #include "commands/tablespace.h" @@ -19745,6 +19747,16 @@ AlterTableNamespaceInternal(Relation rel, Oid oldNspOid, Oid nspOid, AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid, false, objsMoved); + /* + * Remove any EXCEPT clause entries for this relation from schema + * publications. A schema-scoped exclusion is no longer meaningful once + * the table moves to a different schema. + */ + if (rel->rd_rel->relkind == RELKIND_RELATION || + rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE) + RemoveSchemaPubExceptForRel(RelationGetRelid(rel), oldNspOid, + nspOid); + table_close(classRel, RowExclusiveLock); } @@ -21078,6 +21090,7 @@ ATExecAttachPartition(List **wqueue, Relation rel, PartitionCmd *cmd, if (exceptpuboids != NIL) { bool first = true; + bool has_alltables_pub = false; StringInfoData pubnames; initStringInfo(&pubnames); @@ -21091,6 +21104,9 @@ ATExecAttachPartition(List **wqueue, Relation rel, PartitionCmd *cmd, else appendStringInfo(&pubnames, _(", \"%s\""), pubname); first = false; + + if (GetPublication(pubid)->alltables) + has_alltables_pub = true; } ereport(ERROR, @@ -21101,7 +21117,9 @@ ATExecAttachPartition(List **wqueue, Relation rel, PartitionCmd *cmd, RelationGetRelationName(attachrel), pubnames.data), errdetail("The publication EXCEPT clause cannot contain tables that are partitions."), - errhint("Change the publication's EXCEPT clause using ALTER PUBLICATION ... SET ALL TABLES.")); + errhint("%s", has_alltables_pub ? + _("Change the publication's EXCEPT clause using ALTER PUBLICATION ... SET ALL TABLES ... EXCEPT.") : + _("Change the publication's EXCEPT clause using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT."))); } list_free(exceptpuboids); diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y index 9e05a314707..2a8f999d586 100644 --- a/src/backend/parser/gram.y +++ b/src/backend/parser/gram.y @@ -58,6 +58,7 @@ #include "nodes/makefuncs.h" #include "nodes/nodeFuncs.h" #include "parser/parser.h" +#include "utils/builtins.h" #include "utils/datetime.h" #include "utils/xml.h" @@ -11283,7 +11284,7 @@ AlterOwnerStmt: ALTER AGGREGATE aggregate_with_argtypes OWNER TO RoleSpec * pub_obj is one of: * * TABLE table [, ...] - * TABLES IN SCHEMA schema [, ...] + * TABLES IN SCHEMA schema [EXCEPT (TABLE table [, ...] )] [, ...] * *****************************************************************************/ @@ -11343,23 +11344,26 @@ PublicationObjSpec: $$->pubtable->columns = $3; $$->pubtable->whereClause = $4; } - | TABLES IN_P SCHEMA ColId + | TABLES IN_P SCHEMA ColId opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_SCHEMA; $$->name = $4; + $$->except_tables = $5; $$->location = @4; } - | TABLES IN_P SCHEMA CURRENT_SCHEMA + | TABLES IN_P SCHEMA CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_CUR_SCHEMA; + $$->except_tables = $5; $$->location = @4; } - | ColId opt_column_list OptWhereClause + | ColId opt_column_list OptWhereClause opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $4; /* * If either a row filter or column list is specified, create * a PublicationTable object. @@ -11403,10 +11407,11 @@ PublicationObjSpec: $$->pubtable->columns = $2; $$->pubtable->whereClause = $3; } - | CURRENT_SCHEMA + | CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $2; $$->location = @1; } ; @@ -20873,6 +20878,8 @@ preprocess_pub_all_objtype_list(List *all_objects_list, List **pubobjects, /* * Process pubobjspec_list to check for errors in any of the objects and * convert PUBLICATIONOBJ_CONTINUATION into appropriate PublicationObjSpecType. + * Also flattens except_tables from TABLES IN SCHEMA nodes into the list so + * that ObjectsInPublicationToOids() sees them as top-level EXCEPT_TABLE entries. */ static void preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) @@ -20901,6 +20908,13 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLE) { + /* EXCEPT is not valid for table objects */ + if (pubobj->except_tables != NIL) + ereport(ERROR, + errcode(ERRCODE_SYNTAX_ERROR), + errmsg("EXCEPT is not allowed for TABLE publication objects"), + parser_errposition(pubobj->location)); + /* relation name or pubtable must be set for this type of object */ if (!pubobj->name && !pubobj->pubtable) ereport(ERROR, @@ -20949,6 +20963,36 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) errcode(ERRCODE_SYNTAX_ERROR), errmsg("invalid schema name"), parser_errposition(pubobj->location)); + + /* + * For TABLES_IN_SCHEMA, qualify unqualified EXCEPT table names + * with the parent schema and reject cross-schema entries at parse + * time, then flatten into the top-level list. + * + * For TABLES_IN_CUR_SCHEMA the schema name is not yet known, so + * skip both steps here; ObjectsInPublicationToOids() will + * qualify names and validate schema membership at execution time. + */ + if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLES_IN_SCHEMA) + { + foreach_ptr(PublicationObjSpec, eobj, pubobj->except_tables) + { + const char *eobj_schemaname = eobj->pubtable->relation->schemaname; + const char *eobj_relname = eobj->pubtable->relation->relname; + + if (eobj_schemaname == NULL) + eobj->pubtable->relation->schemaname = pubobj->name; + else if (strcmp(eobj_schemaname, pubobj->name) != 0) + ereport(ERROR, + errcode(ERRCODE_INVALID_OBJECT_DEFINITION), + errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", + quote_qualified_identifier(eobj_schemaname, eobj_relname), + pubobj->name), + parser_errposition(eobj->location)); + } + pubobjspec_list = list_concat(pubobjspec_list, pubobj->except_tables); + pubobj->except_tables = NIL; + } } prevobjtype = pubobj->pubobjtype; diff --git a/src/backend/replication/pgoutput/pgoutput.c b/src/backend/replication/pgoutput/pgoutput.c index 4ecfcbff7ab..b92df78266f 100644 --- a/src/backend/replication/pgoutput/pgoutput.c +++ b/src/backend/replication/pgoutput/pgoutput.c @@ -2280,10 +2280,36 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) } } - if (list_member_oid(pubids, pub->oid) || - list_member_oid(schemaPubids, pub->oid) || - ancestor_published) + if (list_member_oid(pubids, pub->oid) || ancestor_published) publish = true; + else if (list_member_oid(schemaPubids, pub->oid)) + { + Oid root_relid; + bool root_is_except = false; + + /* + * schemaPubids is the list of publications that include + * relid's own schema, independent of the ancestor walk + * above -- a partition can live in a different schema + * than its root. Still need to check for exclusion here, + * using the top-most ancestor since only a root + * (non-partition) table can appear in an EXCEPT clause. + */ + if (am_partition) + { + List *ancestors = get_partition_ancestors(relid); + + root_relid = llast_oid(ancestors); + list_free(ancestors); + } + else + root_relid = relid; + + get_publication_rel_entry(pub->oid, root_relid, &root_is_except); + + if (!root_is_except) + publish = true; + } } /* diff --git a/src/backend/utils/cache/relcache.c b/src/backend/utils/cache/relcache.c index 19c4ff6e75e..b14de79d918 100644 --- a/src/backend/utils/cache/relcache.c +++ b/src/backend/utils/cache/relcache.c @@ -5847,16 +5847,32 @@ RelationBuildPublicationDesc(Relation relation, PublicationDesc *pubdesc) /* Fetch the publication membership info. */ puboids = GetRelationIncludedPublications(relid); schemaid = RelationGetNamespace(relation); - puboids = list_concat_unique_oid(puboids, GetSchemaPublications(schemaid)); if (relation->rd_rel->relispartition) { - Oid last_ancestor_relid; - - /* Add publications that the ancestors are in too. */ ancestors = get_partition_ancestors(relid); - last_ancestor_relid = llast_oid(ancestors); + /* ancestors is NIL for a partition with a pending DETACH CONCURRENTLY. */ + if (ancestors != NIL) + exceptpuboids = GetRelationExcludedPublications(llast_oid(ancestors)); + } + else + exceptpuboids = GetRelationExcludedPublications(relid); + + /* + * Subtract exceptpuboids from the schema-publication contribution so that + * a relation EXCEPT'd from a schema publication does not inherit that + * publication's pubactions. Without this filter, + * CheckCmdReplicaIdentity() would demand REPLICA IDENTITY for + * UPDATE/DELETE even on a explicitly excluded table. + */ + puboids = list_concat_unique_oid(puboids, + list_difference_oid(GetSchemaPublications(schemaid), + exceptpuboids)); + + if (relation->rd_rel->relispartition) + { + /* Add publications that the ancestors are in too. */ foreach(lc, ancestors) { Oid ancestor = lfirst_oid(lc); @@ -5865,23 +5881,9 @@ RelationBuildPublicationDesc(Relation relation, PublicationDesc *pubdesc) GetRelationIncludedPublications(ancestor)); schemaid = get_rel_namespace(ancestor); puboids = list_concat_unique_oid(puboids, - GetSchemaPublications(schemaid)); + list_difference_oid(GetSchemaPublications(schemaid), + exceptpuboids)); } - - /* - * Only the top-most ancestor can appear in the EXCEPT clause. - * Therefore, for a partition, exclusion must be evaluated at the - * top-most ancestor. - */ - exceptpuboids = GetRelationExcludedPublications(last_ancestor_relid); - } - else - { - /* - * For a regular table or a root partitioned table, check exclusion on - * table itself. - */ - exceptpuboids = GetRelationExcludedPublications(relid); } alltablespuboids = GetAllTablesPublications(); diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c index a2f09c26369..bdc9bffc697 100644 --- a/src/bin/psql/describe.c +++ b/src/bin/psql/describe.c @@ -6838,6 +6838,24 @@ describePublications(const char *pattern) if (!addFooterToPublicationDesc(&buf, _("Tables from schemas:"), true, &cont)) goto error_return; + + if (pset.sversion >= 190000) + { + /* + * Get tables in the EXCEPT clause for this schema + * publication. + */ + printfPQExpBuffer(&buf, + "SELECT concat(c.relnamespace::regnamespace, '.', c.relname)\n" + "FROM pg_catalog.pg_class c\n" + " JOIN pg_catalog.pg_publication_rel pr ON c.oid = pr.prrelid\n" + "WHERE pr.prpubid = '%s'\n" + " AND pr.prexcept\n" + "ORDER BY 1", pubid); + if (!addFooterToPublicationDesc(&buf, _("Except tables:"), + true, &cont)) + goto error_return; + } } } else diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index 1cacc8c3ea2..7d8b4504194 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -1065,6 +1065,24 @@ static const SchemaQuery Query_for_trigger_of_table = { "SELECT nspname FROM pg_catalog.pg_namespace "\ " WHERE nspname LIKE '%s'" +#define Query_for_list_of_tables_in_schema \ +"SELECT n.nspname || '.' || c.relname "\ +" FROM pg_catalog.pg_class c "\ +" JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "\ +" WHERE c.relkind IN (" CppAsString2(RELKIND_RELATION) ", " \ + CppAsString2(RELKIND_PARTITIONED_TABLE) ") "\ +" AND (n.nspname || '.' || c.relname) LIKE '%s' "\ +" AND n.nspname = '%s'" + +#define Query_for_list_of_tables_in_current_schema \ +"SELECT c.relname "\ +" FROM pg_catalog.pg_class c "\ +" JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "\ +" WHERE c.relkind IN (" CppAsString2(RELKIND_RELATION) ", " \ + CppAsString2(RELKIND_PARTITIONED_TABLE) ") "\ +" AND c.relname LIKE '%s' "\ +" AND n.nspname = pg_catalog.current_schema()" + /* Use COMPLETE_WITH_QUERY_VERBATIM with these queries for GUC names: */ #define Query_for_list_of_alter_system_set_vars \ "SELECT pg_catalog.lower(name) FROM pg_catalog.pg_settings "\ @@ -3774,8 +3792,21 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); - else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && (!ends_with(prev_wd, ','))) - COMPLETE_WITH("WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE", "WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* Complete "CREATE PUBLICATION <name> [...] WITH" */ else if (Matches("CREATE", "PUBLICATION", MatchAnyN, "WITH", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/include/catalog/pg_publication.h b/src/include/catalog/pg_publication.h index 89b4bb14f62..e437e949051 100644 --- a/src/include/catalog/pg_publication.h +++ b/src/include/catalog/pg_publication.h @@ -192,6 +192,7 @@ extern List *GetPubPartitionOptionRelations(List *result, Oid relid); extern Oid GetTopMostAncestorInPublication(Oid puboid, List *ancestors, int *ancestor_level); +extern bool get_publication_rel_entry(Oid pubid, Oid relid, bool *is_except); extern bool is_publishable_relation(Relation rel); extern bool is_schema_publication(Oid pubid); diff --git a/src/include/commands/publicationcmds.h b/src/include/commands/publicationcmds.h index 4cf45c17cc5..fb1703aa675 100644 --- a/src/include/commands/publicationcmds.h +++ b/src/include/commands/publicationcmds.h @@ -27,6 +27,8 @@ extern void AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt); extern void RemovePublicationById(Oid pubid); extern void RemovePublicationRelById(Oid proid); extern void RemovePublicationSchemaById(Oid psoid); +extern void RemoveSchemaPubExceptForRel(Oid relid, Oid oldNspOid, + Oid newNspOid); extern ObjectAddress AlterPublicationOwner(const char *name, Oid newOwnerId); extern void AlterPublicationOwner_oid(Oid pubid, Oid newOwnerId); diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h index 77f69f94607..63abc0b6960 100644 --- a/src/include/nodes/parsenodes.h +++ b/src/include/nodes/parsenodes.h @@ -4532,6 +4532,8 @@ typedef struct PublicationObjSpec PublicationObjSpecType pubobjtype; /* type of this publication object */ char *name; PublicationTable *pubtable; + List *except_tables; /* tables specified in the EXCEPT clause (for + * TABLES IN SCHEMA) */ ParseLoc location; /* token location, or -1 if unknown */ } PublicationObjSpec; diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 9c6386d518a..d4c213d4c84 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -279,6 +279,12 @@ CREATE PUBLICATION testpub_foralltables_excepttable2 FOR ALL TABLES EXCEPT (test ERROR: syntax error at or near "testpub_tbl1" LINE 1: ..._foralltables_excepttable2 FOR ALL TABLES EXCEPT (testpub_tb... ^ +-- fail - EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testpub_tbl3); +ERROR: EXCEPT is not allowed for TABLE publication objects +LINE 2: FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testp... + ^ --------------------------------------------- -- SET ALL TABLES/SEQUENCES --------------------------------------------- @@ -475,11 +481,159 @@ CREATE TABLE tab_main (a int) PARTITION BY RANGE(a); ALTER TABLE tab_main ATTACH PARTITION testpub_root FOR VALUES FROM (0) TO (200); ERROR: cannot attach table "testpub_root" as partition because it is referenced in publication "testpub8" EXCEPT clause DETAIL: The publication EXCEPT clause cannot contain tables that are partitions. -HINT: Change the publication's EXCEPT clause using ALTER PUBLICATION ... SET ALL TABLES. +HINT: Change the publication's EXCEPT clause using ALTER PUBLICATION ... SET ALL TABLES ... EXCEPT. RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Create same-named tables in public to verify unqualified EXCEPT entries +-- are qualified with the named schema, not public +CREATE TABLE testpub_nopk (foo int, bar int); +CREATE TABLE testpub_tbl_s1 (a int primary key, b text); +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + Publication testpub_schema_except1 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- Exclude multiple tables using unqualified names; same-named tables exist in +-- public to confirm unqualified names resolve to pub_test, not public +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + Publication testpub_schema_except2 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_nopk" + "pub_test.testpub_tbl_s1" + +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testp... + ^ +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); +ERROR: table "pub_test.testpub_tbl_s1" in EXCEPT clause does not belong to schema "public" +LINE 2: ...R TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.t... + ^ +-- Multiple schemas each with their own EXCEPT clause +CREATE PUBLICATION testpub_schema_except_multi + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_schema_except_multi + Publication testpub_schema_except_multi + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- ALTER TABLE ... SET SCHEMA on a table excluded by a schema publication: +-- the schema-scoped exclusion is no longer meaningful once the table moves +-- out of its schema, so the exclusion is auto-removed. +CREATE PUBLICATION testpub_schema_except_setsch + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_schema_except_setsch + Publication testpub_schema_except_setsch + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s2" + +ALTER TABLE pub_test.testpub_tbl_s2 SET SCHEMA public; +\dRp+ testpub_schema_except_setsch + Publication testpub_schema_except_setsch + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + +DROP PUBLICATION testpub_schema_except_setsch; +-- Restore for further tests +ALTER TABLE public.testpub_tbl_s2 SET SCHEMA pub_test; +-- fail: table appears in both the explicit table list and the EXCEPT clause +CREATE PUBLICATION testpub_except_conflict + FOR TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot be both published and excluded +-- fail: nonexistent table in EXCEPT clause +CREATE PUBLICATION testpub_except_norel + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- fail: partition cannot appear in EXCEPT clause; only root tables are allowed +CREATE TABLE pub_test.testpub_parted_s (a int) PARTITION BY LIST (a); +CREATE TABLE pub_test.testpub_part_s PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (1); +CREATE PUBLICATION testpub_except_partition + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); +ERROR: cannot specify relation "pub_test.testpub_part_s" in the publication EXCEPT clause +DETAIL: This operation is not supported for individual partitions. +-- fail: TABLE keyword is required for the first entry in the EXCEPT clause +CREATE PUBLICATION testpub_except_nokw + FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +ERROR: syntax error at or near "testpub_nopk" +LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + ^ +-- fail: ADD TABLE for a partition is rejected when a partition ancestor +-- is currently in the publication's EXCEPT list. +CREATE PUBLICATION testpub_except_ancestor + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ALTER PUBLICATION testpub_except_ancestor ADD TABLE pub_test.testpub_part_s; +ERROR: cannot add partition "pub_test.testpub_part_s" to publication "testpub_except_ancestor" +DETAIL: Ancestor "pub_test.testpub_parted_s" of partition "pub_test.testpub_part_s" is currently listed in the EXCEPT clause of the publication. +HINT: Change EXCEPT list using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT. +DROP PUBLICATION testpub_except_ancestor; +-- fail: same contradiction (explicit partition + EXCEPT-ed ancestor), but +-- given in a single statement instead of two separate ones +CREATE PUBLICATION testpub_except_ancestor_same_create + FOR TABLE pub_test.testpub_part_s, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ERROR: partition "pub_test.testpub_part_s" cannot be both published and excluded +DETAIL: Ancestor "pub_test.testpub_parted_s" of partition "pub_test.testpub_part_s" is currently listed in the EXCEPT clause of this command. +-- fail: same contradiction as above, but the partition lives in a different +-- schema (public) than its EXCEPT-ed root (pub_test) +CREATE TABLE public.testpub_part_s2 PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (2); +CREATE PUBLICATION testpub_except_ancestor_cross_schema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s), + TABLE public.testpub_part_s2; +ERROR: partition "public.testpub_part_s2" cannot be both published and excluded +DETAIL: Ancestor "pub_test.testpub_parted_s" of partition "public.testpub_part_s2" is currently listed in the EXCEPT clause of this command. +DROP TABLE public.testpub_part_s2; +-- Cleanup +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP TABLE pub_test.testpub_parted_s CASCADE; +DROP TABLE testpub_nopk, testpub_tbl_s1; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +--------------------------------------------- +-- Tests for publications with SEQUENCES +--------------------------------------------- CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; -- FOR ALL SEQUENCES @@ -1970,6 +2124,27 @@ ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b); ERROR: column specification not allowed for schema LINE 1: ...TION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b)... ^ +-- EXCEPT clause with CURRENT_SCHEMA: cross-schema entry must be rejected +SET search_path = pub_test1; +-- qualified name from wrong schema -> error +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.tbl1); +ERROR: table "pub_test2.tbl1" in EXCEPT clause does not belong to schema "pub_test1" +-- unqualified name implicitly qualified with current schema (pub_test1.tbl) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl); +RESET client_min_messages; +\dRp+ testpub_cursch_except + Publication testpub_cursch_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test1" +Except tables: + "pub_test1.tbl" + +DROP PUBLICATION testpub_cursch_except; +RESET search_path; -- cleanup pub_test1 schema for invalidation tests ALTER PUBLICATION testpub2_forschema DROP TABLES IN SCHEMA pub_test1; DROP PUBLICATION testpub3_forschema, testpub4_forschema, testpub5_forschema, testpub6_forschema, testpub_fortable; @@ -2321,6 +2496,7 @@ DROP ROLE regress_publication_user_dummy; -- Test pg_get_publication_tables(text[], oid) function CREATE SCHEMA gpt_test_sch; CREATE TABLE gpt_test_sch.tbl_sch (id int); +CREATE TABLE gpt_test_sch.tbl_sch2 (id int); CREATE TABLE tbl_normal (id int); CREATE TABLE tbl_parent (id1 int, id2 int, id3 int) PARTITION BY RANGE (id1); CREATE TABLE tbl_part1 PARTITION OF tbl_parent FOR VALUES FROM (1) TO (10); @@ -2331,6 +2507,7 @@ CREATE PUBLICATION pub_all_no_viaroot FOR ALL TABLES WITH (publish_via_partition CREATE PUBLICATION pub_all_except FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = true); CREATE PUBLICATION pub_all_except_no_viaroot FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_schema FOR TABLES IN SCHEMA gpt_test_sch; +CREATE PUBLICATION pub_schema_except FOR TABLES IN SCHEMA gpt_test_sch EXCEPT (TABLE gpt_test_sch.tbl_sch); CREATE PUBLICATION pub_normal FOR TABLE tbl_normal WHERE (id < 10); CREATE PUBLICATION pub_part_leaf FOR TABLE tbl_part1 WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_part_parent FOR TABLE tbl_parent (id1, id2) WHERE (id1 = 10) WITH (publish_via_partition_root = true); @@ -2482,6 +2659,44 @@ SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_part1'); -- no r ---------+---------+-------+------ (0 rows) +-- test for EXCEPT clause with schema publication +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch'); -- no result (excluded) + pubname | relname | attrs | qual +---------+---------+-------+------ +(0 rows) + +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch2'); -- one row (included via schema) + pubname | relname | attrs | qual +-------------------+----------+-------+------ + pub_schema_except | tbl_sch2 | 1 | +(1 row) + +-- test for EXCEPT clause with schema publication, where the excluded root's +-- partition lives in a different schema that is separately, fully included +-- (no EXCEPT) in the same publication. The root's exclusion must cascade to +-- the partition regardless of the partition's own schema membership. +CREATE SCHEMA gpt_cross_sch1; +CREATE SCHEMA gpt_cross_sch2; +CREATE TABLE gpt_cross_sch1.croot (id int) PARTITION BY RANGE (id); +CREATE TABLE gpt_cross_sch2.cpart1 PARTITION OF gpt_cross_sch1.croot FOR VALUES FROM (1) TO (10); +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION pub_cross_schema_except FOR TABLES IN SCHEMA gpt_cross_sch1 EXCEPT (TABLE gpt_cross_sch1.croot), TABLES IN SCHEMA gpt_cross_sch2; +RESET client_min_messages; +SELECT * FROM test_gpt(ARRAY['pub_cross_schema_except'], 'gpt_cross_sch1.croot'); -- no result (excluded) + pubname | relname | attrs | qual +---------+---------+-------+------ +(0 rows) + +-- no result (excluded via cascading root exclusion, even though cpart1's own +-- schema gpt_cross_sch2 is separately, fully included with no EXCEPT) +SELECT * FROM test_gpt(ARRAY['pub_cross_schema_except'], 'gpt_cross_sch2.cpart1'); + pubname | relname | attrs | qual +---------+---------+-------+------ +(0 rows) + +DROP PUBLICATION pub_cross_schema_except; +DROP TABLE gpt_cross_sch2.cpart1, gpt_cross_sch1.croot; +DROP SCHEMA gpt_cross_sch1, gpt_cross_sch2; -- two rows with different row filter SELECT * FROM test_gpt(ARRAY['pub_all', 'pub_normal'], 'tbl_normal'); pubname | relname | attrs | qual @@ -2534,6 +2749,7 @@ DROP PUBLICATION pub_all_no_viaroot; DROP PUBLICATION pub_all_except; DROP PUBLICATION pub_all_except_no_viaroot; DROP PUBLICATION pub_schema; +DROP PUBLICATION pub_schema_except; DROP PUBLICATION pub_normal; DROP PUBLICATION pub_part_leaf; DROP PUBLICATION pub_part_parent; @@ -2542,7 +2758,9 @@ DROP PUBLICATION pub_part_parent_child; DROP VIEW gpt_test_view; DROP TABLE tbl_normal, tbl_parent, tbl_part1; DROP SCHEMA gpt_test_sch CASCADE; -NOTICE: drop cascades to table gpt_test_sch.tbl_sch +NOTICE: drop cascades to 2 other objects +DETAIL: drop cascades to table gpt_test_sch.tbl_sch +drop cascades to table gpt_test_sch.tbl_sch2 -- stage objects for pg_dump tests CREATE SCHEMA pubme CREATE TABLE t0 (c int, d int) CREATE TABLE t1 (c int); CREATE SCHEMA pubme2 CREATE TABLE t0 (c int, d int); diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index fac54b02e27..4a86d699e84 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -125,6 +125,9 @@ CREATE PUBLICATION testpub_foralltables_excepttable1 FOR ALL TABLES EXCEPT (TABL \d testpub_tbl1 -- fail - first table in the EXCEPT list should use TABLE keyword CREATE PUBLICATION testpub_foralltables_excepttable2 FOR ALL TABLES EXCEPT (testpub_tbl1, testpub_tbl2); +-- fail - EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testpub_tbl3); --------------------------------------------- -- SET ALL TABLES/SEQUENCES @@ -222,7 +225,104 @@ RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Create same-named tables in public to verify unqualified EXCEPT entries +-- are qualified with the named schema, not public +CREATE TABLE testpub_nopk (foo int, bar int); +CREATE TABLE testpub_tbl_s1 (a int primary key, b text); + +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + +-- Exclude multiple tables using unqualified names; same-named tables exist in +-- public to confirm unqualified names resolve to pub_test, not public +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); + +-- Multiple schemas each with their own EXCEPT clause +CREATE PUBLICATION testpub_schema_except_multi + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_schema_except_multi + +-- ALTER TABLE ... SET SCHEMA on a table excluded by a schema publication: +-- the schema-scoped exclusion is no longer meaningful once the table moves +-- out of its schema, so the exclusion is auto-removed. +CREATE PUBLICATION testpub_schema_except_setsch + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_schema_except_setsch +ALTER TABLE pub_test.testpub_tbl_s2 SET SCHEMA public; +\dRp+ testpub_schema_except_setsch +DROP PUBLICATION testpub_schema_except_setsch; +-- Restore for further tests +ALTER TABLE public.testpub_tbl_s2 SET SCHEMA pub_test; + +-- fail: table appears in both the explicit table list and the EXCEPT clause +CREATE PUBLICATION testpub_except_conflict + FOR TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: nonexistent table in EXCEPT clause +CREATE PUBLICATION testpub_except_norel + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- fail: partition cannot appear in EXCEPT clause; only root tables are allowed +CREATE TABLE pub_test.testpub_parted_s (a int) PARTITION BY LIST (a); +CREATE TABLE pub_test.testpub_part_s PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (1); +CREATE PUBLICATION testpub_except_partition + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); + +-- fail: TABLE keyword is required for the first entry in the EXCEPT clause +CREATE PUBLICATION testpub_except_nokw + FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + +-- fail: ADD TABLE for a partition is rejected when a partition ancestor +-- is currently in the publication's EXCEPT list. +CREATE PUBLICATION testpub_except_ancestor + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ALTER PUBLICATION testpub_except_ancestor ADD TABLE pub_test.testpub_part_s; +DROP PUBLICATION testpub_except_ancestor; + +-- fail: same contradiction (explicit partition + EXCEPT-ed ancestor), but +-- given in a single statement instead of two separate ones +CREATE PUBLICATION testpub_except_ancestor_same_create + FOR TABLE pub_test.testpub_part_s, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); + +-- fail: same contradiction as above, but the partition lives in a different +-- schema (public) than its EXCEPT-ed root (pub_test) +CREATE TABLE public.testpub_part_s2 PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (2); +CREATE PUBLICATION testpub_except_ancestor_cross_schema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s), + TABLE public.testpub_part_s2; +DROP TABLE public.testpub_part_s2; + +-- Cleanup +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP TABLE pub_test.testpub_parted_s CASCADE; +DROP TABLE testpub_nopk, testpub_tbl_s1; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; + +--------------------------------------------- +-- Tests for publications with SEQUENCES +--------------------------------------------- CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; @@ -1194,6 +1294,18 @@ ALTER PUBLICATION testpub1_forschema SET TABLES IN SCHEMA pub_test1, pub_test1; ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo (a, b); ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b); +-- EXCEPT clause with CURRENT_SCHEMA: cross-schema entry must be rejected +SET search_path = pub_test1; +-- qualified name from wrong schema -> error +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.tbl1); +-- unqualified name implicitly qualified with current schema (pub_test1.tbl) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl); +RESET client_min_messages; +\dRp+ testpub_cursch_except +DROP PUBLICATION testpub_cursch_except; +RESET search_path; + -- cleanup pub_test1 schema for invalidation tests ALTER PUBLICATION testpub2_forschema DROP TABLES IN SCHEMA pub_test1; DROP PUBLICATION testpub3_forschema, testpub4_forschema, testpub5_forschema, testpub6_forschema, testpub_fortable; @@ -1448,6 +1560,7 @@ DROP ROLE regress_publication_user_dummy; -- Test pg_get_publication_tables(text[], oid) function CREATE SCHEMA gpt_test_sch; CREATE TABLE gpt_test_sch.tbl_sch (id int); +CREATE TABLE gpt_test_sch.tbl_sch2 (id int); CREATE TABLE tbl_normal (id int); CREATE TABLE tbl_parent (id1 int, id2 int, id3 int) PARTITION BY RANGE (id1); CREATE TABLE tbl_part1 PARTITION OF tbl_parent FOR VALUES FROM (1) TO (10); @@ -1459,6 +1572,7 @@ CREATE PUBLICATION pub_all_no_viaroot FOR ALL TABLES WITH (publish_via_partition CREATE PUBLICATION pub_all_except FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = true); CREATE PUBLICATION pub_all_except_no_viaroot FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_schema FOR TABLES IN SCHEMA gpt_test_sch; +CREATE PUBLICATION pub_schema_except FOR TABLES IN SCHEMA gpt_test_sch EXCEPT (TABLE gpt_test_sch.tbl_sch); CREATE PUBLICATION pub_normal FOR TABLE tbl_normal WHERE (id < 10); CREATE PUBLICATION pub_part_leaf FOR TABLE tbl_part1 WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_part_parent FOR TABLE tbl_parent (id1, id2) WHERE (id1 = 10) WITH (publish_via_partition_root = true); @@ -1515,6 +1629,32 @@ SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'gpt_test_sch.tbl_sch SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_parent'); -- no result (excluded) SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_part1'); -- no result +-- test for EXCEPT clause with schema publication +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch'); -- no result (excluded) +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch2'); -- one row (included via schema) + +-- test for EXCEPT clause with schema publication, where the excluded root's +-- partition lives in a different schema that is separately, fully included +-- (no EXCEPT) in the same publication. The root's exclusion must cascade to +-- the partition regardless of the partition's own schema membership. +CREATE SCHEMA gpt_cross_sch1; +CREATE SCHEMA gpt_cross_sch2; +CREATE TABLE gpt_cross_sch1.croot (id int) PARTITION BY RANGE (id); +CREATE TABLE gpt_cross_sch2.cpart1 PARTITION OF gpt_cross_sch1.croot FOR VALUES FROM (1) TO (10); + +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION pub_cross_schema_except FOR TABLES IN SCHEMA gpt_cross_sch1 EXCEPT (TABLE gpt_cross_sch1.croot), TABLES IN SCHEMA gpt_cross_sch2; +RESET client_min_messages; + +SELECT * FROM test_gpt(ARRAY['pub_cross_schema_except'], 'gpt_cross_sch1.croot'); -- no result (excluded) +-- no result (excluded via cascading root exclusion, even though cpart1's own +-- schema gpt_cross_sch2 is separately, fully included with no EXCEPT) +SELECT * FROM test_gpt(ARRAY['pub_cross_schema_except'], 'gpt_cross_sch2.cpart1'); + +DROP PUBLICATION pub_cross_schema_except; +DROP TABLE gpt_cross_sch2.cpart1, gpt_cross_sch1.croot; +DROP SCHEMA gpt_cross_sch1, gpt_cross_sch2; + -- two rows with different row filter SELECT * FROM test_gpt(ARRAY['pub_all', 'pub_normal'], 'tbl_normal'); @@ -1543,6 +1683,7 @@ DROP PUBLICATION pub_all_no_viaroot; DROP PUBLICATION pub_all_except; DROP PUBLICATION pub_all_except_no_viaroot; DROP PUBLICATION pub_schema; +DROP PUBLICATION pub_schema_except; DROP PUBLICATION pub_normal; DROP PUBLICATION pub_part_leaf; DROP PUBLICATION pub_part_parent; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 8c58d282eee..c4e4efafec8 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -24,14 +24,17 @@ my $result; sub test_except_root_partition { - my ($pubviaroot) = @_; + my ($pubviaroot, $pubsql) = @_; + $pubsql //= + "CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1)"; + $pubsql .= " WITH (publish_via_partition_root = $pubviaroot)"; # If the root partitioned table is in the EXCEPT clause, all its # partitions are excluded from publication, regardless of the # publish_via_partition_root setting. $node_publisher->safe_psql( 'postgres', qq( - CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1) WITH (publish_via_partition_root = $pubviaroot); + $pubsql; INSERT INTO root1 VALUES (1), (101); )); $node_subscriber->safe_psql('postgres', @@ -223,6 +226,206 @@ $node_subscriber->safe_psql( test_except_root_partition('false'); test_except_root_partition('true'); +# Same validation using TABLES IN SCHEMA instead of FOR ALL TABLES. +my $schema_pub = + "CREATE PUBLICATION tap_pub_part FOR TABLES IN SCHEMA public EXCEPT (TABLE public.root1)"; +test_except_root_partition('false', $schema_pub); +test_except_root_partition('true', $schema_pub); + +# ============================================ +# EXCEPT test cases for TABLES IN SCHEMA +# ============================================ + +# Create a dedicated schema with two tables: one to be published and one to be +# excluded. Also create inherited tables to verify ONLY semantics. +$node_publisher->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_published AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.tab_excluded AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.parent (a int); + CREATE TABLE sch1.child (b int) INHERITS (sch1.parent); +)); + +$node_subscriber->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_published (a int); + CREATE TABLE sch1.tab_excluded (a int); + CREATE TABLE sch1.parent (a int); + CREATE TABLE sch1.child (b int) INHERITS (sch1.parent); +)); + +# Basic test: initial sync respects EXCEPT. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_excluded)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: initial sync copies included table'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: initial sync skips excluded table'); + +# DML: only the included table should be replicated. +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (6); + INSERT INTO sch1.tab_excluded VALUES (6); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(6), + 'TABLES IN SCHEMA EXCEPT: DML on included table is replicated'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: DML on excluded table is not replicated'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Inherited tables: excluding the parent (without ONLY) also excludes the child. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.parent)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.child VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.child"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: excluding parent (without ONLY) also excludes child' +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Test that EXCEPT (TABLE ONLY parent) excludes only the parent itself, not its +# child. Truncate child first so rows from the previous test are not copied by +# the initial table sync of the next subscription. +$node_publisher->safe_psql('postgres', 'TRUNCATE sch1.child'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE sch1.child'); +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE ONLY sch1.parent)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.child VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.child"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: ONLY parent in EXCEPT does not exclude child'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Cleanup schema tables before the multi-publication section. +$node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); +$node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); + +# ============================================ +# EXCEPT test cases for TABLES IN SCHEMA with a cross-schema partition +# ============================================ + +# A partition can live in a different schema than its partitioned root. If +# the root is excluded via EXCEPT under its own schema's clause, the +# exclusion must cascade to all its partitions, even when the partition's +# own schema is separately, fully included (no EXCEPT) in the same +# publication. +$node_publisher->safe_psql( + 'postgres', qq( + CREATE SCHEMA csch1; + CREATE SCHEMA csch2; + CREATE TABLE csch1.croot(a int) PARTITION BY RANGE(a); + CREATE TABLE csch2.cpart1 PARTITION OF csch1.croot FOR VALUES FROM (0) TO (100); + INSERT INTO csch1.croot VALUES (generate_series(1,5)); +)); + +$node_subscriber->safe_psql( + 'postgres', qq( + CREATE SCHEMA csch1; + CREATE SCHEMA csch2; + CREATE TABLE csch1.croot(a int); + CREATE TABLE csch2.cpart1(a int); +)); + +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION cross_sch_pub FOR TABLES IN SCHEMA csch1 EXCEPT (TABLE csch1.croot), TABLES IN SCHEMA csch2 WITH (publish_via_partition_root = false)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION cross_sch_sub CONNECTION '$publisher_connstr' PUBLICATION cross_sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'cross_sch_sub'); + +# Baseline: the root itself, pre-populated with rows before the subscription +# was created, is excluded by its own schema's EXCEPT clause -- initial sync +# must not have copied it. +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM csch1.croot"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: cross-schema partition root is excluded by initial sync' +); + +# Regression case: the partition's own schema (csch2) is separately, fully +# included with no EXCEPT, but the root's exclusion must still cascade to it +# -- initial sync must not have copied the pre-existing rows routed into this +# partition via the root. +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM csch2.cpart1"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: cross-schema partition is excluded by initial sync via cascading root exclusion' +); + +# Insert distinct, identifiable data directly into the partition and verify +# it is not replicated either. +$node_publisher->safe_psql('postgres', + "INSERT INTO csch2.cpart1 VALUES (generate_series(1,5))"); +$node_publisher->wait_for_catchup('cross_sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM csch1.croot"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: cross-schema partition root remains excluded after DML' +); +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM csch2.cpart1"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: cross-schema partition remains excluded after DML via cascading root exclusion' +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION cross_sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION cross_sch_pub'); +$node_publisher->safe_psql('postgres', 'DROP SCHEMA csch1, csch2 CASCADE'); +$node_subscriber->safe_psql('postgres', 'DROP SCHEMA csch1, csch2 CASCADE'); + # ============================================ # Test when a subscription is subscribing to multiple publications # ============================================ @@ -254,6 +457,7 @@ $node_publisher->safe_psql( DROP PUBLICATION tap_pub2; TRUNCATE tab1; )); +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_subscriber->safe_psql('postgres', qq(TRUNCATE tab1)); # OK when a table is excluded by pub1 EXCEPT clause, but it is included by pub2 -- 2.50.1 (Apple Git-155)
v21-0002-Restrict-conflicting-EXCEPT-lists-in-multi-schem.patch (application/x-patch, 14.9K) download From b42b4a34e9070b37a02e2c35fd754893af04e14d Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Wed, 15 Jul 2026 21:18:51 +0530 Subject: [PATCH v21 2/5] Restrict conflicting EXCEPT lists in multi-schema publications Add ProcessSchemaExceptTables() to qualify each mention's EXCEPT entries, build a sorted signature per schema OID, and compare it against any prior mention of the same schema in the same statement, erroring on a mismatch. It also checks there are no clashes of the same schema with or without EXCEPT. --- src/backend/commands/publicationcmds.c | 116 +++++++++++++++------- src/backend/parser/gram.y | 37 +------ src/test/regress/expected/publication.out | 38 +++++++ src/test/regress/sql/publication.sql | 31 ++++++ 4 files changed, 154 insertions(+), 68 deletions(-) diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index edc8a20ae81..ba5f6bf57b9 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -73,6 +73,10 @@ static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); static char defGetGeneratedColsOption(DefElem *def); static void CheckExceptNotInTableList(List *except_rels, List *explicitrelids); +static void ProcessSchemaExceptTables(Oid schemaid, List *except_tables, + ParseState *pstate, List **schemas, + List **schemas_with_except, + List **except_pubtables); static void @@ -177,6 +181,73 @@ parse_publication_options(ParseState *pstate, } } +/* + * Qualify unqualified EXCEPT table names with the given schema, reject + * entries explicitly qualified with a different schema, and append the (now + * qualified) tables to *except_pubtables. + * + * Also rejects a repeated mention of the same schema in the same TABLES IN + * SCHEMA list if it, or an earlier mention of the same schema, specified a + * non-empty EXCEPT list, without checking whether the EXCEPT lists across + * all the mentions actually name the same tables. This mirrors + * OpenTableList()'s handling of repeated tables with column lists (e.g. + * "FOR TABLE t1(a), t1(a)" is rejected even though the lists match): + * repeated mentions of the same schema wouldn't have a well-defined single + * EXCEPT list to enforce, so they're rejected as conflicting or redundant + * rather than silently unioned or compared for equivalence. A schema may + * still be mentioned multiple times as long as none of the mentions + * specify EXCEPT. + * *schemas_with_except accumulates the OIDs of schemas already seen with a + * non-empty EXCEPT list in this statement. + */ +static void +ProcessSchemaExceptTables(Oid schemaid, List *except_tables, + ParseState *pstate, List **schemas, + List **schemas_with_except, List **except_pubtables) +{ + char *schema_name = get_namespace_name(schemaid); + + /* + * A repeat is only a problem if this mention has EXCEPT, or an earlier + * mention of the same schema did. + */ + if (list_member_oid(*schemas, schemaid)) + { + if (except_tables != NIL || + list_member_oid(*schemas_with_except, schemaid)) + ereport(ERROR, + errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("conflicting or redundant EXCEPT lists for schema \"%s\"", + schema_name)); + } + + if (except_tables != NIL) + *schemas_with_except = lappend_oid(*schemas_with_except, schemaid); + + /* Filter out duplicates if the user specifies "sch1, sch1" */ + *schemas = list_append_unique_oid(*schemas, schemaid); + + if (except_tables == NIL) + return; + + foreach_ptr(PublicationObjSpec, eobj, except_tables) + { + RangeVar *relation = eobj->pubtable->relation; + + if (relation->schemaname == NULL) + relation->schemaname = schema_name; + else if (strcmp(relation->schemaname, schema_name) != 0) + ereport(ERROR, + errcode(ERRCODE_INVALID_OBJECT_DEFINITION), + errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", + quote_qualified_identifier(relation->schemaname, relation->relname), + schema_name), + parser_errposition(pstate, eobj->location)); + + *except_pubtables = lappend(*except_pubtables, eobj->pubtable); + } +} + /* * Convert the PublicationObjSpecType list into schema oid list and * PublicationTable list. @@ -187,6 +258,7 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, { ListCell *cell; PublicationObjSpec *pubobj; + List *schemas_with_except = NIL; if (!pubobjspec_list) return; @@ -211,8 +283,10 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, case PUBLICATIONOBJ_TABLES_IN_SCHEMA: schemaid = get_namespace_oid(pubobj->name, false); - /* Filter out duplicates if user specifies "sch1, sch1" */ - *schemas = list_append_unique_oid(*schemas, schemaid); + ProcessSchemaExceptTables(schemaid, pubobj->except_tables, + pstate, schemas, + &schemas_with_except, + except_pubtables); break; case PUBLICATIONOBJ_TABLES_IN_CUR_SCHEMA: search_path = fetch_search_path(false); @@ -224,40 +298,10 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, schemaid = linitial_oid(search_path); list_free(search_path); - /* Filter out duplicates if user specifies "sch1, sch1" */ - *schemas = list_append_unique_oid(*schemas, schemaid); - - /* - * Qualify unqualified EXCEPT table names with the resolved - * current schema and reject any explicitly cross-schema - * entries. This mirrors the parse-time handling done for - * TABLES_IN_SCHEMA in preprocess_pubobj_list(), deferred here - * because CURRENT_SCHEMA is not known until execution time. - */ - if (pubobj->except_tables != NIL) - { - char *cur_schema_name = get_namespace_name(schemaid); - - foreach_ptr(PublicationObjSpec, eobj, pubobj->except_tables) - { - const char *eobj_schemaname = - eobj->pubtable->relation->schemaname; - const char *eobj_relname = - eobj->pubtable->relation->relname; - - if (eobj_schemaname == NULL) - eobj->pubtable->relation->schemaname = cur_schema_name; - else if (strcmp(eobj_schemaname, cur_schema_name) != 0) - ereport(ERROR, - errcode(ERRCODE_INVALID_OBJECT_DEFINITION), - errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", - quote_qualified_identifier(eobj_schemaname, eobj_relname), - cur_schema_name)); - - *except_pubtables = lappend(*except_pubtables, - eobj->pubtable); - } - } + ProcessSchemaExceptTables(schemaid, pubobj->except_tables, + pstate, schemas, + &schemas_with_except, + except_pubtables); break; default: /* shouldn't happen */ diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y index 2a8f999d586..f38c9f332ba 100644 --- a/src/backend/parser/gram.y +++ b/src/backend/parser/gram.y @@ -20878,8 +20878,11 @@ preprocess_pub_all_objtype_list(List *all_objects_list, List **pubobjects, /* * Process pubobjspec_list to check for errors in any of the objects and * convert PUBLICATIONOBJ_CONTINUATION into appropriate PublicationObjSpecType. - * Also flattens except_tables from TABLES IN SCHEMA nodes into the list so - * that ObjectsInPublicationToOids() sees them as top-level EXCEPT_TABLE entries. + * + * The except_tables attached to TABLES IN SCHEMA nodes are left in place here; + * ObjectsInPublicationToOids() qualifies their names, validates schema + * membership, and merges the qualified tables into its except_pubtables + * output list once the schema OID is known. */ static void preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) @@ -20963,36 +20966,6 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) errcode(ERRCODE_SYNTAX_ERROR), errmsg("invalid schema name"), parser_errposition(pubobj->location)); - - /* - * For TABLES_IN_SCHEMA, qualify unqualified EXCEPT table names - * with the parent schema and reject cross-schema entries at parse - * time, then flatten into the top-level list. - * - * For TABLES_IN_CUR_SCHEMA the schema name is not yet known, so - * skip both steps here; ObjectsInPublicationToOids() will - * qualify names and validate schema membership at execution time. - */ - if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLES_IN_SCHEMA) - { - foreach_ptr(PublicationObjSpec, eobj, pubobj->except_tables) - { - const char *eobj_schemaname = eobj->pubtable->relation->schemaname; - const char *eobj_relname = eobj->pubtable->relation->relname; - - if (eobj_schemaname == NULL) - eobj->pubtable->relation->schemaname = pubobj->name; - else if (strcmp(eobj_schemaname, pubobj->name) != 0) - ereport(ERROR, - errcode(ERRCODE_INVALID_OBJECT_DEFINITION), - errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", - quote_qualified_identifier(eobj_schemaname, eobj_relname), - pubobj->name), - parser_errposition(eobj->location)); - } - pubobjspec_list = list_concat(pubobjspec_list, pubobj->except_tables); - pubobj->except_tables = NIL; - } } prevobjtype = pubobj->pubobjtype; diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index d4c213d4c84..eb115d4e433 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -552,6 +552,17 @@ Except tables: "pub_test.testpub_tbl_s1" "public.testpub_tbl1" +-- fail: same schema repeated with same EXCEPT lists +CREATE PUBLICATION testpub_schema_except_conflict + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: conflicting or redundant EXCEPT lists for schema "pub_test" +-- fail: same schema repeated with conflicting or no EXCEPT lists +CREATE PUBLICATION testpub_schema_except_conflict2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2), + pub_test; +ERROR: conflicting or redundant EXCEPT lists for schema "pub_test" -- ALTER TABLE ... SET SCHEMA on a table excluded by a schema publication: -- the schema-scoped exclusion is no longer meaningful once the table moves -- out of its schema, so the exclusion is auto-removed. @@ -2129,6 +2140,8 @@ SET search_path = pub_test1; -- qualified name from wrong schema -> error CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.tbl1); ERROR: table "pub_test2.tbl1" in EXCEPT clause does not belong to schema "pub_test1" +LINE 1: ...FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.... + ^ -- unqualified name implicitly qualified with current schema (pub_test1.tbl) SET client_min_messages = 'ERROR'; CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl); @@ -2144,6 +2157,31 @@ Except tables: "pub_test1.tbl" DROP PUBLICATION testpub_cursch_except; +-- succeeds: CURRENT_SCHEMA and pub_test1 (same schema) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_named_same + FOR TABLES IN SCHEMA CURRENT_SCHEMA, pub_test1; +RESET client_min_messages; +\dRp+ testpub_cursch_named_same + Publication testpub_cursch_named_same + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test1" + +DROP PUBLICATION testpub_cursch_named_same; +-- fail: CURRENT_SCHEMA and pub_test1 (same schema) have +-- conflicting EXCEPT lists +CREATE PUBLICATION testpub_cursch_named_conflict + FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl), + pub_test1 EXCEPT (TABLE tbl1); +ERROR: conflicting or redundant EXCEPT lists for schema "pub_test1" +-- fail: two CURRENT_SCHEMA mentions with conflicting EXCEPT lists +CREATE PUBLICATION testpub_cursch_cursch_conflict + FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl), + CURRENT_SCHEMA EXCEPT (TABLE tbl1); +ERROR: conflicting or redundant EXCEPT lists for schema "pub_test1" RESET search_path; -- cleanup pub_test1 schema for invalidation tests ALTER PUBLICATION testpub2_forschema DROP TABLES IN SCHEMA pub_test1; diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 4a86d699e84..4a79055c4f3 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -262,6 +262,17 @@ CREATE PUBLICATION testpub_schema_except_multi public EXCEPT (TABLE testpub_tbl1); \dRp+ testpub_schema_except_multi +-- fail: same schema repeated with same EXCEPT lists +CREATE PUBLICATION testpub_schema_except_conflict + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: same schema repeated with conflicting or no EXCEPT lists +CREATE PUBLICATION testpub_schema_except_conflict2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2), + pub_test; + -- ALTER TABLE ... SET SCHEMA on a table excluded by a schema publication: -- the schema-scoped exclusion is no longer meaningful once the table moves -- out of its schema, so the exclusion is auto-removed. @@ -1304,6 +1315,26 @@ CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXC RESET client_min_messages; \dRp+ testpub_cursch_except DROP PUBLICATION testpub_cursch_except; + +-- succeeds: CURRENT_SCHEMA and pub_test1 (same schema) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_named_same + FOR TABLES IN SCHEMA CURRENT_SCHEMA, pub_test1; +RESET client_min_messages; +\dRp+ testpub_cursch_named_same +DROP PUBLICATION testpub_cursch_named_same; + +-- fail: CURRENT_SCHEMA and pub_test1 (same schema) have +-- conflicting EXCEPT lists +CREATE PUBLICATION testpub_cursch_named_conflict + FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl), + pub_test1 EXCEPT (TABLE tbl1); + +-- fail: two CURRENT_SCHEMA mentions with conflicting EXCEPT lists +CREATE PUBLICATION testpub_cursch_cursch_conflict + FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl), + CURRENT_SCHEMA EXCEPT (TABLE tbl1); + RESET search_path; -- cleanup pub_test1 schema for invalidation tests -- 2.50.1 (Apple Git-155)
v21-0003-Add-EXCEPT-support-to-ALTER-PUBLICATION-ADD-TABL.patch (application/x-patch, 21.9K) download From fcde32f78d77e88e1a3a1a9e4c883f9e63b6db28 Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Wed, 15 Jul 2026 18:21:08 +0530 Subject: [PATCH v21 3/5] Add EXCEPT support to ALTER PUBLICATION ADD TABLES IN SCHEMA Extend the EXCEPT clause support to allow tables to be excluded when adding a schema to a publication via ALTER PUBLICATION ... ADD. Syntax: ALTER PUBLICATION pub ADD TABLES IN SCHEMA s EXCEPT (TABLE s.t1); Since pg_dump uses ALTER PUBLICATION ... ADD, support for it is included in this patch. --- src/backend/catalog/pg_publication.c | 19 +++-- src/backend/commands/publicationcmds.c | 98 ++++++++++++++++++++++- src/bin/pg_dump/pg_dump.c | 30 ++++++- src/bin/pg_dump/t/002_pg_dump.pl | 24 ++++++ src/bin/psql/tab-complete.in.c | 17 ++++ src/test/regress/expected/publication.out | 60 +++++++++++++- src/test/regress/sql/publication.sql | 45 ++++++++++- src/test/subscription/t/037_except.pl | 32 ++++++++ 8 files changed, 311 insertions(+), 14 deletions(-) diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index 785c9effdd9..ea222c6faa9 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -726,15 +726,18 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, * here, as CreatePublication() function invalidates all relations as part * of defining a FOR ALL TABLES publication. * - * For ALTER PUBLICATION, invalidation is needed only when adding an - * EXCEPT table to a publication already marked as ALL TABLES. For - * publications that were originally empty or defined as ALL SEQUENCES and - * are being converted to ALL TABLES, invalidation is skipped here, as - * AlterPublicationAllFlags() function invalidates all relations while - * marking the publication as ALL TABLES publication. + * For ALTER PUBLICATION, invalidation is needed when adding an EXCEPT + * table to either a FOR ALL TABLES publication (pub->alltables is true) + * or a FOR TABLES IN SCHEMA publication (is_schema_publication is true). + * The exception: when a publication is being converted to FOR ALL TABLES + * (pub->alltables is still false at this point), + * AlterPublicationAllFlags() will perform a full invalidation, so we skip + * it here. */ - inval_except_table = (alter_stmt != NULL) && pub->alltables && - (alter_stmt->for_all_tables && pri->except); + inval_except_table = (alter_stmt != NULL) && pri->except && + (pub->alltables + ? alter_stmt->for_all_tables + : is_schema_publication(pubid)); if (!pri->except || inval_except_table) { diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index ba5f6bf57b9..3367bb0c889 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -71,6 +71,13 @@ static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok); static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); +static void AlterPublicationSchemas(AlterPublicationStmt *stmt, + HeapTuple tup, List *schemaidlist, + List *except_pubtables); +static void AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, + List *except_pubtables, + List *schemaidlist); static char defGetGeneratedColsOption(DefElem *def); static void CheckExceptNotInTableList(List *except_rels, List *explicitrelids); static void ProcessSchemaExceptTables(Oid schemaid, List *except_tables, @@ -1593,7 +1600,8 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, */ static void AlterPublicationSchemas(AlterPublicationStmt *stmt, - HeapTuple tup, List *schemaidlist) + HeapTuple tup, List *schemaidlist, + List *except_pubtables) { Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); @@ -1670,6 +1678,88 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, */ PublicationAddSchemas(pubform->oid, schemaidlist, true, stmt); } + + /* + * Increment the command counter so that is_schema_publication() in + * GetExcludedPublicationTables() can see the just-inserted schema + * rows when AlterPublicationSchemaExceptTables runs next. + */ + if (stmt->action == AP_AddObjects || stmt->action == AP_SetObjects) + CommandCounterIncrement(); + + AlterPublicationSchemaExceptTables(stmt, tup, except_pubtables, schemaidlist); +} + +/* + * Alter the EXCEPT list of a schema-level publication. + * + * Adds, removes, or replaces except-table entries in pg_publication_rel + * (rows with prexcept = true). These entries suppress publication of the + * named tables that would otherwise be covered by a FOR TABLES IN SCHEMA + * clause. + */ +static void +AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, List *except_pubtables, + List *schemaidlist) +{ + Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); + Oid pubid = pubform->oid; + + /* + * Nothing to do if no EXCEPT entries. + */ + if (!except_pubtables) + return; + + /* + * This function handles EXCEPT entries for schema-level publications + * only. For FOR ALL TABLES publications, EXCEPT entries are already + * processed by AlterPublicationTables(). + */ + if (schemaidlist == NIL && !is_schema_publication(pubid)) + return; + + /* + * Dropping a schema from a publication removes all its EXCEPT entries via + * cascade. The concept of "drop all schema tables from the publication + * EXCEPT these ones" is not supported. + */ + if (stmt->action == AP_DropObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); + + /* + * XXX EXCEPT with SET is not currently implemented. Workaround: DROP and + * re-ADD the schema with the desired EXCEPT list. + */ + if (stmt->action == AP_SetObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"), + errhint("Drop and re-add the schema with the desired EXCEPT list."))); + + if (stmt->action == AP_AddObjects) + { + List *rels; + List *explicitrelids; + + rels = OpenTableList(except_pubtables); + + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + /* + * Validate that each excluded table is not also in the explicit table + * list (which would be contradictory). + */ + CheckExceptNotInTableList(rels, explicitrelids); + + PublicationAddTables(pubid, rels, false, stmt); + + CloseTableList(rels); + } } /* @@ -1879,10 +1969,12 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) errmsg("publication \"%s\" does not exist", stmt->pubname)); - relations = list_concat(relations, except_pubtables); + if (stmt->for_all_tables) + relations = list_concat(relations, except_pubtables); + AlterPublicationTables(stmt, tup, relations, pstate->p_sourcetext, schemaidlist != NIL); - AlterPublicationSchemas(stmt, tup, schemaidlist); + AlterPublicationSchemas(stmt, tup, schemaidlist, except_pubtables); AlterPublicationAllFlags(stmt, rel, tup); } diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c index 4948e6d80c7..ecd518af02c 100644 --- a/src/bin/pg_dump/pg_dump.c +++ b/src/bin/pg_dump/pg_dump.c @@ -4973,6 +4973,7 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) PublicationInfo *pubinfo = pubsinfo->publication; PQExpBuffer query; char *tag; + bool has_except = false; /* Do nothing if not dumping schema */ if (!dopt->dumpSchema) @@ -4983,7 +4984,34 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) query = createPQExpBuffer(); appendPQExpBuffer(query, "ALTER PUBLICATION %s ", fmtId(pubinfo->dobj.name)); - appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s;\n", fmtId(schemainfo->dobj.name)); + appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s", fmtId(schemainfo->dobj.name)); + + /* + * Append EXCEPT clause for any tables that belong to this schema + * and are excluded from the publication. + */ + for (SimplePtrListCell *cell = pubinfo->except_tables.head; cell; cell = cell->next) + { + TableInfo *tbinfo = (TableInfo *) cell->ptr; + + if (strcmp(tbinfo->dobj.namespace->dobj.name, schemainfo->dobj.name) == 0) + { + if (!has_except) + { + appendPQExpBufferStr(query, " EXCEPT ("); + has_except = true; + } + else + appendPQExpBufferStr(query, ", "); + + appendPQExpBuffer(query, "TABLE ONLY %s", fmtId(tbinfo->dobj.name)); + } + } + + if (has_except) + appendPQExpBufferStr(query, ")"); + + appendPQExpBufferStr(query, ";\n"); /* * There is no point in creating drop query as the drop is done by schema diff --git a/src/bin/pg_dump/t/002_pg_dump.pl b/src/bin/pg_dump/t/002_pg_dump.pl index 9258948b583..d18b3b0d7b9 100644 --- a/src/bin/pg_dump/t/002_pg_dump.pl +++ b/src/bin/pg_dump/t/002_pg_dump.pl @@ -3283,6 +3283,30 @@ my %tests = ( like => { %full_runs, section_post_data => 1, }, }, + 'CREATE PUBLICATION pub11' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub11 FOR TABLES IN SCHEMA dump_test EXCEPT (TABLE test_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub11 WITH (publish = 'insert, update, delete, truncate');\E + .*? + \QALTER PUBLICATION pub11 ADD TABLES IN SCHEMA dump_test EXCEPT (TABLE ONLY test_table);\E + /xms, + like => { %full_runs, section_post_data => 1, }, + }, + + 'CREATE PUBLICATION pub12' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub12 FOR TABLES IN SCHEMA dump_test EXCEPT (TABLE test_table, dump_test.test_second_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub12 WITH (publish = 'insert, update, delete, truncate');\E + .*? + \QALTER PUBLICATION pub12 ADD TABLES IN SCHEMA dump_test EXCEPT (TABLE ONLY test_table, TABLE ONLY test_second_table);\E + /xms, + like => { %full_runs, section_post_data => 1, }, + }, + 'CREATE SUBSCRIPTION sub1' => { create_order => 50, create_sql => 'CREATE SUBSCRIPTION sub1 diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index 7d8b4504194..bf206aa6210 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2359,6 +2359,23 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); + /* After a single schema name in ADD context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index eb115d4e433..77570833087 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -636,12 +636,70 @@ CREATE PUBLICATION testpub_except_ancestor_cross_schema ERROR: partition "public.testpub_part_s2" cannot be both published and excluded DETAIL: Ancestor "pub_test.testpub_parted_s" of partition "public.testpub_part_s2" is currently listed in the EXCEPT clause of this command. DROP TABLE public.testpub_part_s2; +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; +-- fail: non-existing table in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- fail: EXCEPT table belongs to a different schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 1: ...xcept ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.tes... + ^ +-- fail: TABLE keyword is required for the first entry in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +ERROR: syntax error at or near "testpub_nopk" +LINE 1: ...lter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_no... + ^ +-- fail: exact same table given as both explicitly published and excluded +-- in a single ALTER ... ADD +ALTER PUBLICATION testpub_alter_except + ADD TABLE pub_test.testpub_tbl_s1, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot be both published and excluded +-- fail: add explicit partition and EXCEPT ancestor, given in a +-- single ALTER ... ADD statement +ALTER PUBLICATION testpub_alter_except + ADD TABLE pub_test.testpub_part_s, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ERROR: partition "pub_test.testpub_part_s" cannot be both published and excluded +DETAIL: Ancestor "pub_test.testpub_parted_s" of partition "pub_test.testpub_part_s" is currently listed in the EXCEPT clause of this command. +-- fail: partition already explicitly published, then its root is EXCEPT-ed +-- via a later, separate ALTER ... ADD +ALTER PUBLICATION testpub_alter_except ADD TABLE pub_test.testpub_part_s; +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ERROR: partition "pub_test.testpub_part_s" cannot be both published and excluded +DETAIL: Ancestor "pub_test.testpub_parted_s" of partition "pub_test.testpub_part_s" is currently listed in the EXCEPT clause of this command. +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_part_s; +-- fail: root already explicitly published, then its partition is rejected +-- from EXCEPT via a later, separate ALTER ... ADD (partitions can never +-- appear in EXCEPT, independent of the root's state) +ALTER PUBLICATION testpub_alter_except ADD TABLE pub_test.testpub_parted_s; +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); +ERROR: cannot specify relation "pub_test.testpub_part_s" in the publication EXCEPT clause +DETAIL: This operation is not supported for individual partitions. +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_parted_s; +-- ADD: qualified and unqualified names; unqualified is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + "pub_test.testpub_tbl_s2" + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP TABLE pub_test.testpub_parted_s CASCADE; DROP TABLE testpub_nopk, testpub_tbl_s1; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi, testpub_alter_except; --------------------------------------------- -- Tests for publications with SEQUENCES --------------------------------------------- diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 4a79055c4f3..a7edd8493e5 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -324,12 +324,55 @@ CREATE PUBLICATION testpub_except_ancestor_cross_schema TABLE public.testpub_part_s2; DROP TABLE public.testpub_part_s2; +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; + +-- fail: non-existing table in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- fail: EXCEPT table belongs to a different schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- fail: TABLE keyword is required for the first entry in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + +-- fail: exact same table given as both explicitly published and excluded +-- in a single ALTER ... ADD +ALTER PUBLICATION testpub_alter_except + ADD TABLE pub_test.testpub_tbl_s1, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: add explicit partition and EXCEPT ancestor, given in a +-- single ALTER ... ADD statement +ALTER PUBLICATION testpub_alter_except + ADD TABLE pub_test.testpub_part_s, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); + +-- fail: partition already explicitly published, then its root is EXCEPT-ed +-- via a later, separate ALTER ... ADD +ALTER PUBLICATION testpub_alter_except ADD TABLE pub_test.testpub_part_s; +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_part_s; + +-- fail: root already explicitly published, then its partition is rejected +-- from EXCEPT via a later, separate ALTER ... ADD (partitions can never +-- appear in EXCEPT, independent of the root's state) +ALTER PUBLICATION testpub_alter_except ADD TABLE pub_test.testpub_parted_s; +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_parted_s; + +-- ADD: qualified and unqualified names; unqualified is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); +\dRp+ testpub_alter_except + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP TABLE pub_test.testpub_parted_s CASCADE; DROP TABLE testpub_nopk, testpub_tbl_s1; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi, testpub_alter_except; --------------------------------------------- -- Tests for publications with SEQUENCES diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index c4e4efafec8..d69b43c14b5 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -347,6 +347,38 @@ is($result, qq(5), $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); +# ============================================ +# ALTER PUBLICATION EXCEPT for TABLES IN SCHEMA +# ============================================ + +# Truncate subscriber tables to remove data accumulated from previous tests. +$node_subscriber->safe_psql('postgres', + 'TRUNCATE sch1.tab_published, sch1.tab_excluded, sch1.parent, sch1.child'); + +# ADD: add a schema with an excepted table; verify the except entry takes effect. +$node_publisher->safe_psql('postgres', "CREATE PUBLICATION sch_pub"); +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub ADD TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_excluded)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(6), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: included table synced'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + # Cleanup schema tables before the multi-publication section. $node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); $node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); -- 2.50.1 (Apple Git-155)
v21-0004-Add-EXCEPT-support-to-ALTER-PUBLICATION-SET-TABL.patch (application/x-patch, 27.4K) download From f8f3bd789c0b767cb2bf0c0da096acac0453d9a2 Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Thu, 18 Jun 2026 11:32:32 +0530 Subject: [PATCH v21 4/5] Add EXCEPT support to ALTER PUBLICATION SET TABLES IN SCHEMA Extend AlterPublicationExceptTables() with the AP_SetObjects case, which redefines the publication and replaces the entire EXCEPT list. Syntax: ALTER PUBLICATION pub SET TABLES IN SCHEMA s EXCEPT (TABLE t1); This patch also cleans up EXCEPT entries when a schema is dropped from the publication. --- src/backend/commands/publicationcmds.c | 177 +++++++++++++++++++--- src/bin/psql/tab-complete.in.c | 17 +++ src/test/regress/expected/publication.out | 109 +++++++++++++ src/test/regress/sql/publication.sql | 47 ++++++ src/test/subscription/t/037_except.pl | 85 +++++++++++ 5 files changed, 410 insertions(+), 25 deletions(-) diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 3367bb0c889..16ee980cc9e 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -67,7 +67,8 @@ static void CloseTableList(List *rels); static void LockSchemaList(List *schemalist); static void PublicationAddTables(Oid pubid, List *rels, bool if_not_exists, AlterPublicationStmt *stmt); -static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok); +static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok, + bool delete_excluded); static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); @@ -1444,7 +1445,7 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, PublicationAddTables(pubid, rels, false, stmt); } else if (stmt->action == AP_DropObjects) - PublicationDropTables(pubid, rels, false); + PublicationDropTables(pubid, rels, false, false); else /* AP_SetObjects */ { List *oldrelids = NIL; @@ -1579,7 +1580,7 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, } /* And drop them. */ - PublicationDropTables(pubid, delrels, true); + PublicationDropTables(pubid, delrels, true, true); /* * Don't bother calculating the difference for adding, we'll catch and @@ -1681,8 +1682,8 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, /* * Increment the command counter so that is_schema_publication() in - * GetExcludedPublicationTables() can see the just-inserted schema - * rows when AlterPublicationSchemaExceptTables runs next. + * GetExcludedPublicationTables() can see the just-inserted schema rows + * when AlterPublicationSchemaExceptTables runs next. */ if (stmt->action == AP_AddObjects || stmt->action == AP_SetObjects) CommandCounterIncrement(); @@ -1700,16 +1701,18 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, */ static void AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, - HeapTuple tup, List *except_pubtables, - List *schemaidlist) + HeapTuple tup, List *except_pubtables, + List *schemaidlist) { Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); Oid pubid = pubform->oid; /* - * Nothing to do if no EXCEPT entries. + * Nothing to do if there are no EXCEPT entries, unless handling the SET + * command, because if the user has removed all exceptions we need to drop + * any existing ones. */ - if (!except_pubtables) + if (!except_pubtables && stmt->action != AP_SetObjects) return; /* @@ -1730,16 +1733,6 @@ AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); - /* - * XXX EXCEPT with SET is not currently implemented. Workaround: DROP and - * re-ADD the schema with the desired EXCEPT list. - */ - if (stmt->action == AP_SetObjects) - ereport(ERROR, - (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"), - errhint("Drop and re-add the schema with the desired EXCEPT list."))); - if (stmt->action == AP_AddObjects) { List *rels; @@ -1758,6 +1751,72 @@ AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, PublicationAddTables(pubid, rels, false, stmt); + CloseTableList(rels); + } + else /* AP_SetObjects */ + { + List *oldexceptrelids = NIL; + List *newexceptrelids = NIL; + List *delrelids = NIL; + List *rels; + List *explicitrelids; + + rels = OpenTableList(except_pubtables); + + /* Collect OIDs of the desired new EXCEPT list. */ + foreach_ptr(PublicationRelInfo, pri, rels) + newexceptrelids = lappend_oid(newexceptrelids, + RelationGetRelid(pri->relation)); + + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + /* Check that there is no clash between included and excluded tables. */ + CheckExceptNotInTableList(rels, explicitrelids); + + /* + * Get the current set of EXCEPT entries. Only FOR ALL TABLES and + * schema-level publications can have EXCEPT entries; for any other + * publication type oldexceptrelids stays NIL. + * + * Note: we check is_schema_publication() against the current catalog + * state (before AlterPublicationSchemas has run), so if the caller is + * doing SET TABLE t1 to convert a schema publication into a plain + * table publication, is_schema_publication() still returns true here. + * That is intentional: it lets us discover and clean up any stale + * EXCEPT entries that belong to the old schema definition. + */ + if (GetPublication(pubid)->alltables || is_schema_publication(pubid)) + oldexceptrelids = GetExcludedPublicationTables(pubid, + PUBLICATION_PART_ROOT); + + /* Build a list of old EXCEPT entries not present in the new list. */ + foreach_oid(oldrelid, oldexceptrelids) + { + if (!list_member_oid(newexceptrelids, oldrelid)) + delrelids = lappend_oid(delrelids, oldrelid); + } + + /* Drop old EXCEPT entries not present in the new list. */ + foreach_oid(relid, delrelids) + { + Oid proid; + ObjectAddress obj; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + /* Add new EXCEPT entries, skipping any already present. */ + PublicationAddTables(pubid, rels, true, stmt); + CloseTableList(rels); } } @@ -2381,33 +2440,68 @@ PublicationAddTables(Oid pubid, List *rels, bool if_not_exists, /* * Remove listed tables from the publication. + * + * delete_excluded controls how EXCEPT (prexcept=true) rows are handled: + * true - delete them silently. Used by the SET path to clear stale + * EXCEPT rows that are being replaced by a new EXCEPT list. + * false - treat them as "not a member". Used by ALTER ... DROP TABLE: an + * EXCEPT entry is not something DROP TABLE is expected to remove. */ static void -PublicationDropTables(Oid pubid, List *rels, bool missing_ok) +PublicationDropTables(Oid pubid, List *rels, bool missing_ok, + bool delete_excluded) { ObjectAddress obj; ListCell *lc; - Oid prid; foreach(lc, rels) { PublicationRelInfo *pubrel = (PublicationRelInfo *) lfirst(lc); Relation rel = pubrel->relation; Oid relid = RelationGetRelid(rel); + HeapTuple tup; + Form_pg_publication_rel pubrelform; + Oid prid = InvalidOid; + bool is_except = false; if (pubrel->columns) ereport(ERROR, errcode(ERRCODE_SYNTAX_ERROR), errmsg("column list must not be specified in ALTER PUBLICATION ... DROP")); - prid = GetSysCacheOid2(PUBLICATIONRELMAP, Anum_pg_publication_rel_oid, - ObjectIdGetDatum(relid), - ObjectIdGetDatum(pubid)); - if (!OidIsValid(prid)) + tup = SearchSysCache2(PUBLICATIONRELMAP, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (HeapTupleIsValid(tup)) + { + pubrelform = (Form_pg_publication_rel) GETSTRUCT(tup); + is_except = pubrelform->prexcept; + prid = pubrelform->oid; + ReleaseSysCache(tup); + } + + /* + * DROP TABLE operates only on regular member rows. A missing row + * and an EXCEPT row both mean the table isn't currently published, + * but we distinguish them so the EXCEPT case can carry a hint + * pointing the user at the EXCEPT list. The SET-cleanup caller + * (delete_excluded = true) intends to remove EXCEPT rows and so + * bypasses the EXCEPT half of this check. + */ + if (!OidIsValid(prid) || (is_except && !delete_excluded)) { if (missing_ok) continue; + if (is_except) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("cannot drop table \"%s\" from publication \"%s\"", + RelationGetQualifiedRelationName(rel), + get_publication_name(pubid, false)), + errdetail("The table is currently listed in the EXCEPT clause of the publication."), + errhint("Use ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT to modify the EXCEPT list."))); + ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("relation \"%s\" is not part of the publication", @@ -2463,6 +2557,7 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) foreach(lc, schemas) { Oid schemaid = lfirst_oid(lc); + List *except_relids; psid = GetSysCacheOid2(PUBLICATIONNAMESPACEMAP, Anum_pg_publication_namespace_oid, @@ -2479,8 +2574,40 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) get_namespace_name(schemaid)))); } + /* + * Collect EXCEPT entries for tables belonging to this schema before + * removing the schema entry. + */ + except_relids = GetExcludedPublicationTables(pubid, PUBLICATION_PART_ROOT); + ObjectAddressSet(obj, PublicationNamespaceRelationId, psid); performDeletion(&obj, DROP_CASCADE, 0); + + /* + * Drop any prexcept rows for tables belonging to this schema. These + * rows have no pg_depend entry pointing at the + * pg_publication_namespace row, so they are not cascaded by the + * performDeletion() call above and must be cleaned up explicitly. + */ + foreach_oid(relid, except_relids) + { + Oid proid; + + if (get_rel_namespace(relid) != schemaid) + continue; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + list_free(except_relids); } } diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index bf206aa6210..e67b9c63a5a 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2376,6 +2376,23 @@ match_previous_words(int pattern_id, } else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) COMPLETE_WITH(")"); + /* After a single schema name in SET context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 77570833087..dd4b2f35a6e 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -694,6 +694,115 @@ Except tables: "pub_test.testpub_tbl_s1" "pub_test.testpub_tbl_s2" +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s2" + +-- fail: table in EXCEPT clause also appears in the explicit table list +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot be both published and excluded +-- fail: explicit partition + EXCEPT-ed root, given in a single SET statement +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_part_s, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ERROR: partition "pub_test.testpub_part_s" cannot be both published and excluded +DETAIL: Ancestor "pub_test.testpub_parted_s" of partition "pub_test.testpub_part_s" is currently listed in the EXCEPT clause of this command. +-- fail: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 1: ...xcept SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.tes... + ^ +-- SET: unqualified name in EXCEPT is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- SET without EXCEPT clears the existing except list +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + +-- SET to a different schema removes old schema's EXCEPT entries +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA public; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "public" + +-- fail: nonexistent table in EXCEPT clause (SET path) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- SET: multiple schemas each with their own EXCEPT clause +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- fail: ALTER PUBLICATION ... DROP TABLE on an excluded table is rejected +-- with an EXCEPT-specific error. +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_tbl_s1; +ERROR: cannot drop table "pub_test.testpub_tbl_s1" from publication "testpub_alter_except" +DETAIL: The table is currently listed in the EXCEPT clause of the publication. +HINT: Use ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT to modify the EXCEPT list. +-- the EXCEPT entry is still present after the rejected DROP TABLE +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- fail: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +ERROR: EXCEPT clause is not supported with DROP in ALTER PUBLICATION +-- DROP TABLES IN SCHEMA removes associated EXCEPT entries +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "public" +Except tables: + "public.testpub_tbl1" + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index a7edd8493e5..367835f0fcd 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -367,6 +367,53 @@ ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_parted_s; ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); \dRp+ testpub_alter_except +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + +-- fail: table in EXCEPT clause also appears in the explicit table list +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: explicit partition + EXCEPT-ed root, given in a single SET statement +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_part_s, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); + +-- fail: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- SET: unqualified name in EXCEPT is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +\dRp+ testpub_alter_except + +-- SET without EXCEPT clears the existing except list +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + +-- SET to a different schema removes old schema's EXCEPT entries +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA public; +\dRp+ testpub_alter_except + +-- fail: nonexistent table in EXCEPT clause (SET path) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- SET: multiple schemas each with their own EXCEPT clause +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_alter_except + +-- fail: ALTER PUBLICATION ... DROP TABLE on an excluded table is rejected +-- with an EXCEPT-specific error. +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_tbl_s1; +-- the EXCEPT entry is still present after the rejected DROP TABLE +\dRp+ testpub_alter_except + +-- fail: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); + +-- DROP TABLES IN SCHEMA removes associated EXCEPT entries +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index d69b43c14b5..bcd8ac7bc1f 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -376,6 +376,61 @@ $result = is($result, qq(0), 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); +# SET: replace the except list; tab_excluded is now included and tab_published is excluded. +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_published)" +); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (7); + INSERT INTO sch1.tab_excluded VALUES (7); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded WHERE a = 7"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: newly included table is replicated' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published WHERE a = 7"); +is($result, qq(0), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: now-excluded table is not replicated' +); + +# SET without EXCEPT: clears the except list; both tables are now published. +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1"); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (8); + INSERT INTO sch1.tab_excluded VALUES (8); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published WHERE a = 8"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_published replicated after except list cleared' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded WHERE a = 8"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_excluded replicated after except list cleared' +); + $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); @@ -518,6 +573,36 @@ $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); +# OK when a table is excluded by a TABLES IN SCHEMA EXCEPT publication, +# but is included by another publication. +$node_publisher->safe_psql('postgres', 'TRUNCATE tab1'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE tab1'); + +$node_publisher->safe_psql( + 'postgres', qq( + CREATE PUBLICATION tap_pub1 FOR TABLES IN SCHEMA public EXCEPT (TABLE public.tab1); + CREATE PUBLICATION tap_pub2 FOR TABLE tab1; + INSERT INTO tab1 VALUES(1); +)); +$node_subscriber->psql('postgres', + "CREATE SUBSCRIPTION tap_sub CONNECTION '$publisher_connstr' PUBLICATION tap_pub1, tap_pub2" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'tap_sub'); + +$node_publisher->safe_psql('postgres', qq(INSERT INTO tab1 VALUES(2))); +$node_publisher->wait_for_catchup('tap_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT * FROM tab1 ORDER BY a"); +is( $result, qq(1 +2), + "TABLES IN SCHEMA EXCEPT: table excluded in schema pub but included by another pub is replicated" +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); + $node_publisher->stop('fast'); done_testing(); -- 2.50.1 (Apple Git-155)
v21-0005-Documentation-Patch.patch (application/x-patch, 11.6K) download From 309a39f9060c873b73dd060b031895c7e86ce1ba Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Thu, 18 Jun 2026 09:03:08 +0530 Subject: [PATCH v21 5/5] Documentation Patch --- doc/src/sgml/logical-replication.sgml | 3 +- doc/src/sgml/ref/alter_publication.sgml | 58 +++++++++++++++++++++++- doc/src/sgml/ref/create_publication.sgml | 42 +++++++++++++---- 3 files changed, 91 insertions(+), 12 deletions(-) diff --git a/doc/src/sgml/logical-replication.sgml b/doc/src/sgml/logical-replication.sgml index 690598bff98..46c944beae8 100644 --- a/doc/src/sgml/logical-replication.sgml +++ b/doc/src/sgml/logical-replication.sgml @@ -117,7 +117,8 @@ or <literal>FOR ALL SEQUENCES</literal>. Unlike tables, sequences can be synchronized at any time. For more information, see <xref linkend="logical-replication-sequences"/>. When a publication is - created with <literal>FOR ALL TABLES</literal>, a table or set of tables can + created with <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal>, a table or set of tables can be explicitly excluded from publication using the <link linkend="sql-createpublication-params-for-except-table"><literal>EXCEPT</literal></link> clause. diff --git a/doc/src/sgml/ref/alter_publication.sgml b/doc/src/sgml/ref/alter_publication.sgml index 52114a16a39..037ddfa9404 100644 --- a/doc/src/sgml/ref/alter_publication.sgml +++ b/doc/src/sgml/ref/alter_publication.sgml @@ -31,7 +31,7 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA <replaceable class="parameter">tables_in_schema</replaceable> [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -47,6 +47,10 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <replaceable class="parameter">table_object</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] [ WHERE ( <replaceable class="parameter">expression</replaceable> ) ] +<phrase>and <replaceable class="parameter">tables_in_schema</replaceable> is:</phrase> + + { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] + <phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> TABLE <replaceable class="parameter">table_object</replaceable> [, ... ] @@ -69,6 +73,9 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r The first two variants modify which tables/schemas are part of the publication. The <literal>ADD</literal> and <literal>DROP</literal> clauses will add and remove one or more tables/schemas from the publication. + The <literal>EXCEPT</literal> clause can be used with + <literal>ADD TABLES IN SCHEMA</literal> to exclude specific tables from a + schema-level publication. </para> <para> @@ -93,7 +100,11 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r used with a publication defined with <literal>FOR TABLE</literal> or <literal>FOR TABLES IN SCHEMA</literal>, replaces the list of tables/schemas in the publication with the specified list; the existing tables or schemas - that were present in the publication will be removed. + that were present in the publication will be removed. When + <literal>SET TABLES IN SCHEMA</literal> is used with an + <literal>EXCEPT</literal> clause, the excluded tables for each schema are + replaced with the specified list; if <literal>EXCEPT</literal> is omitted + for a schema, any existing exclusions for that schema are cleared. </para> <para> @@ -198,6 +209,27 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r </listitem> </varlistentry> + <varlistentry> + <term><literal>EXCEPT</literal></term> + <listitem> + <para> + When used with <literal>ADD TABLES IN SCHEMA</literal> + or <literal>SET TABLES IN SCHEMA</literal>, specifies + tables to be excluded from the publication. Each named + table must belong to the schema specified in the same + <literal>TABLES IN SCHEMA</literal> clause. Table names may be + schema-qualified or unqualified; unqualified names are implicitly + qualified with the schema named in the same clause. See + <xref linkend="sql-createpublication"/> for further details on the + semantics of <literal>EXCEPT</literal>. + </para> + <para> + Dropping a table always removes it from the <literal>EXCEPT</literal> + clause. + </para> + </listitem> + </varlistentry> + <varlistentry> <term><literal>SET ( <replaceable class="parameter">publication_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] )</literal></term> <listitem> @@ -288,6 +320,28 @@ ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA marketing, sales; </programlisting> </para> + <para> + Add schema <structname>sales</structname> to the publication + <structname>sales_publication</structname>, excluding the + <structname>sales.internal</structname> and + <structname>sales.drafts</structname> tables: +<programlisting> +ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA sales EXCEPT (TABLE internal, drafts); +</programlisting> + </para> + + <para> + Replace the schema list of <structname>sales_publication</structname> with + <structname>sales</structname>, excluding only + <structname>sales.drafts</structname>. Other than + <structname>sales.drafts</structname>, any previously excluded tables for schema + <structname>sales</structname> are no longer excluded. Any schemas previously in + <structname>sales_publication</structname> are removed: +<programlisting> +ALTER PUBLICATION sales_publication SET TABLES IN SCHEMA sales EXCEPT (TABLE drafts); +</programlisting> + </para> + <para> Add tables <structname>users</structname>, <structname>departments</structname> and schema diff --git a/doc/src/sgml/ref/create_publication.sgml b/doc/src/sgml/ref/create_publication.sgml index 85cfcaddafa..d16b4067fe6 100644 --- a/doc/src/sgml/ref/create_publication.sgml +++ b/doc/src/sgml/ref/create_publication.sgml @@ -28,7 +28,7 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA <replaceable class="parameter">tables_in_schema</replaceable> [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -39,6 +39,10 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <replaceable class="parameter">table_object</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] [ WHERE ( <replaceable class="parameter">expression</replaceable> ) ] +<phrase>and <replaceable class="parameter">tables_in_schema</replaceable> is:</phrase> + + { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] + <phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> TABLE <replaceable class="parameter">table_object</replaceable> [, ... ] @@ -142,6 +146,8 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <para> Marks the publication as one that replicates changes for all tables in the specified list of schemas, including tables created in the future. + Tables listed in the <literal>EXCEPT</literal> clause for a given schema + are excluded from the publication. </para> <para> @@ -173,7 +179,7 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <para> Marks the publication as one that replicates changes for all tables in the database, including tables created in the future. Tables listed in - <literal>EXCEPT</literal> clause are excluded from the publication. + the <literal>EXCEPT</literal> clause are excluded from the publication. </para> </listitem> </varlistentry> @@ -198,13 +204,21 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <listitem> <para> This clause specifies a list of tables to be excluded from the - publication. + publication. It can be used with <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal>. For <literal>FOR TABLES IN + SCHEMA</literal>, the exclusion applies only to tables in the schema + associated with the <literal>EXCEPT</literal>. </para> <para> - Once a table is excluded, the exclusion applies to that table - regardless of its name or schema. Renaming the table or moving it to - another schema using <command>ALTER TABLE ... SET SCHEMA</command> does - not remove the exclusion. + Once a table is excluded under <literal>FOR ALL TABLES</literal>, the + exclusion applies to that table regardless of its name or schema. + Renaming the table or moving it to another schema using + <command>ALTER TABLE ... SET SCHEMA</command> does not remove the + exclusion. However, for <literal>FOR TABLES IN SCHEMA</literal>, because + the <literal>EXCEPT</literal> is schema-scoped, moving a schema-excluded + table to another schema does remove the exclusion; if the table is later + moved back, the exclusion is not restored and must be re-established + with <command>ALTER PUBLICATION</command>. </para> <para> For inherited tables, if <literal>ONLY</literal> is specified before the @@ -216,8 +230,9 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> </para> <para> For partitioned tables, only the root partitioned table may be specified - in <literal>EXCEPT</literal>. Doing so excludes the root table and - all of its partitions from replication. The optional + in <literal>EXCEPT</literal>. Excluding the root table automatically + excludes all of its partitions from replication, even those in + schemas that are otherwise included in the publication. The optional <literal>ONLY</literal> and <literal>*</literal> has no effect for partitioned tables. </para> @@ -521,6 +536,15 @@ CREATE PUBLICATION production_publication FOR TABLE users, departments, TABLES I CREATE PUBLICATION sales_publication FOR TABLES IN SCHEMA marketing, sales; </programlisting></para> + <para> + Create a publication that publishes all changes for all the tables present in + the schema <structname>sales</structname>, except + <structname>internal</structname> and <structname>drafts</structname>: +<programlisting> +CREATE PUBLICATION sales_filtered FOR TABLES IN SCHEMA sales EXCEPT (TABLE internal, drafts); +</programlisting> + </para> + <para> Create a publication that publishes all changes for table <structname>users</structname>, but replicates only columns <structname>user_id</structname> and -- 2.50.1 (Apple Git-155)
^ permalink raw reply [nested|flat] 196+ messages in thread

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-15 16:48  Nisha Moond <nisha.moond412@gmail.com>
  parent: Peter Smith <smithpb2250@gmail.com>
  0 siblings, 0 replies; 196+ messages in thread

From: Nisha Moond @ 2026-07-15 16:48 UTC (permalink / raw)
  To: Peter Smith <smithpb2250@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; Amit Kapila <amit.kapila16@gmail.com>

On Wed, Jul 15, 2026 at 10:19 AM Peter Smith <smithpb2250@gmail.com> wrote:
>
> Some review comments for v20-0001.
>

Thanks for review. All suggestions are incorporated. Please find
responses for few below.

> ~~~
>
> 6.
> + /*
> + * GetTopMostAncestorInPublication() returns InvalidOid both when no
> + * ancestor matched at all, and when the root is excluded via EXCEPT.
> + * Disambiguate here: if the root is excluded, the partition is never
> + * published through this publication, regardless of whether the
> + * partition's own schema is separately included.
> + */
>
> When you say "the partition's own schema", it seems to be viewed
> through the lens of FOR TABLES IN SCHEMA, but the partition could also
> be explicitly included (e.g. FOR TABLE xxx).
>
> IOW, does "own schema" need to be mentioned, or can that last sentence
> say "regardless of whether the partition is separately included".
>

I think it is better to view this through the lens of FOR TABLES IN
SCHEMA, since a partition cannot be included by any other means if its
root is excluded.
My intent with this comment is to clarify that a partition should not
be assumed to be included simply because its schema is included --
hence the additional check.

I reworded it as: "regardless of whether the partition's schema is
separately included".

> ~~~
>
> 7.
> + *
> + * A pg_publication_rel row with prexcept=true means the table is
> + * explicitly excluded via EXCEPT and must not be reported as published,
> + * even if its schema is otherwise included.  A row with prexcept=false
> + * means it is explicitly included.  If no pg_publication_rel row exists,
> + * the table is published iff its schema appears in
> + * pg_publication_namespace.
>
> Again, this comment seems viewed the the lens of FOR TABLES IN SCHEMA.
>
> That last part, ("If no pg_publication_rel row exists, the table is
> published iff its schema appears in pg_publication_namespace."), seems
> not quite correct. For example, a table can be published by a FOR ALL
> TABLES publication, which has nothing in pg_publication_namespace at
> all.
>

IIUC, we reach this code only for non-FOR ALL TABLES publications,
since the pub->alltables case is handled before reaching here.
Therefore, the pointed "last part" of comment holds true. Please
correct me if I'm missing another scenario where this would not be the
case.

>
> ======
> src/backend/replication/pgoutput/pgoutput.c
>
> get_rel_sync_entry:
>
> 10.
> + /*
> + * GetTopMostAncestorInPublication() itself skips
> + * schema-based ancestor matches when the partition root
> + * is excluded via this publication's EXCEPT clause.
> + */
>   ancestor = GetTopMostAncestorInPublication(pub->oid,
>      ancestors,
>      &level);
>
> I'm not sure if that comment is helpful here or not. Why is the caller
> describing the inner logic of the function it is calling?

I missed removing the comment during the recent code optimization.
It's removed now.

>
> ~~~
> ~~~
>
> 12.
> + /*
> + * schemaPubids is relid's own schema, independent of the
> + * ancestor walk above -- a partition can live in a
> + * different schema than its root.  Still need to check
> + * for exclusion here, using the top-most ancestor since
> + * only a root (non-partition) table can appear in an
> + * EXCEPT clause.
> + */
>
> I don't know what "schemaPubids is relid's own schema" means. AFAIK
> the `schemaPubids` was a list of publications this schemas is a member
> of (??).
>

Correct. Reworded the comment as: "schemaPubids is the list of
publications that include relid's schema..."

> ======
> src/test/regress/sql/publication.sql
>
> 13.
> +-- fail: partition still rejected from EXCEPT even when its own root is also
> +-- named in the same EXCEPT list
> +CREATE PUBLICATION testpub_except_partition_with_root
> +    FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE
> pub_test.testpub_part_s, TABLE pub_test.testpub_parted_s);
> +
>
> Is this test needed? Isn't the previous test ("only root tables are
> allowed") covering this?
>

Okay, makes sense. I've removed it.

> Alternatively, consider to put the partition in a different schema
> (e.g. see the review comment #15 just below)

Added a test case covering the cross-schema failure scenario.

>
> ~~~
>
> 15.
> +-- test for EXCEPT clause with schema publication, where the excluded root's
> +-- partition lives in a different schema that is separately, fully included
> +-- (no EXCEPT) in the same publication.  The root's exclusion must cascade to
> +-- the partition regardless of the partition's own schema membership.
> +CREATE SCHEMA gpt_cross_sch1;
> +CREATE SCHEMA gpt_cross_sch2;
> +CREATE TABLE gpt_cross_sch1.croot (id int) PARTITION BY RANGE (id);
> +CREATE TABLE gpt_cross_sch2.cpart1 PARTITION OF gpt_cross_sch1.croot
> FOR VALUES FROM (1) TO (10);
> +
> +SET client_min_messages = 'ERROR';
> +CREATE PUBLICATION pub_cross_schema_except FOR TABLES IN SCHEMA
> gpt_cross_sch1 EXCEPT (TABLE gpt_cross_sch1.croot), TABLES IN SCHEMA
> gpt_cross_sch2;
>
> IIUC, a different way to do this test would be to name the partition explicitly:
> CREATE PUBLICATION pub_cross_schema_except FOR TABLES IN SCHEMA
> gpt_cross_sch1 EXCEPT (TABLE gpt_cross_sch1.croot), TABLE
> gpt_cross_sch2.cpart1;
>
> Is it worth adding this way as well?
>

This test is intended to verify pg_get_publication_tables() for the
case where a partition's schema is included, but the partition itself
should not appear in the publication.

The suggested command would not cover that code path. That said, I
agree that explicitly adding such a partition should also fail, so
I've added a failure test under the "EXCEPT tests for TABLES IN
SCHEMA" section.

--
Thanks,
Nisha





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-15 16:48  Nisha Moond <nisha.moond412@gmail.com>
  parent: Peter Smith <smithpb2250@gmail.com>
  0 siblings, 0 replies; 196+ messages in thread

From: Nisha Moond @ 2026-07-15 16:48 UTC (permalink / raw)
  To: Peter Smith <smithpb2250@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; Amit Kapila <amit.kapila16@gmail.com>

On Wed, Jul 15, 2026 at 2:13 PM Peter Smith <smithpb2250@gmail.com> wrote:
>
> Hi Nisha.
>
> Here are my review comments for all the rest of the v20* patches
>

Thanks for the review. I've addressed all the comments as suggested in v21.

>
> 3.
> Something about this logic seems over-complicated to me.
>
> e.g. All this stuff about `schema_repeated`?
>
> AFAICT, you only need to be accumulating 2 lists
> - list1 = schemas without EXCEPT
> - list2 = schemas with EXCEPT
>
> To check conflicting the logic is simple:
> - before adding to list1 ensure same schema is not already in list2, else error
> - before adding to list2 ensure same schema is not already in list1, else error
>
> Those checks can be done before you verify the qualified schema names
> match their schema...
>

After addressing Shveta's comments in [1], the function is much
simpler. I also adjusted the if conditions to improve readability.
Please let me know if this looks acceptable or if you see further
opportunities for improvement.

[1] https://www.postgresql.org/message-id/CAJpy0uCFCdL97L3Pt8f586br5irqkzCa_i3tXMjH6JFCPxxr4Q%40mail.gma...

--
Thanks,
Nisha






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-16 04:45  shveta malik <shveta.malik@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  3 siblings, 1 reply; 196+ messages in thread

From: shveta malik @ 2026-07-16 04:45 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; shveta malik <shveta.malik@gmail.com>

On Wed, Jul 15, 2026 at 10:16 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
>
> On Mon, Jul 13, 2026 at 3:31 PM shveta malik <shveta.malik@gmail.com> wrote:
> >
> > On Fri, Jul 10, 2026 at 5:07 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
> > >
> > >
> > > Yes, that works for me as we have FOR TABLES example to follow. I've
> > > made the changes in v20.
> > >
> >
> > Thanks! I had a quick look, few initial comments:
> >
> >
> > 1)
> > GetTopMostAncestorInPublication():
> >
> > + if (ancestors == NIL)
> > + return InvalidOid;
> >
> > Should this be Assert or can there be a case where ancestors list can
> > come as NIL?
> >
>
> I found one case where ancestors can be NIL.
> Test case:
>   CREATE TABLE t1 (a int) PARTITION BY RANGE (a);
>   CREATE TABLE t1_part PARTITION OF t1 FOR VALUES FROM (1) TO (100);
>   CREATE PUBLICATION mypub FOR TABLE t1;
>
> -- Get the partition into the pending-detach state:
>  -- Session A:
>   BEGIN;
>   SELECT * FROM t1;
>   -- leave open
>
> -- Session B (blocks, waiting on Session A's lock on t1):
>   ALTER TABLE t1 DETACH PARTITION t1_part CONCURRENTLY;
>
> -- Session C, while B is blocked:
>   SELECT * FROM pg_get_publication_tables('{mypub}'::text[],
> 't1_part'::regclass);
>
> In this scenario, Session C reaches GetTopMostAncestorInPublication()
> with ancestors == NIL. So I think we should keep return InvalidOid;
> rather than replacing it with an Assert.
>
> While investigating this race, I also hit assertions at places that
> call "llast_oid(ancestors)" without checking for NIL, for example in
> check_publication_add_relation() and RelationBuildPublicationDesc(). I
> fixed those by guarding with if (ancestors != NIL).

Okay, I will review.

> But due to this same race, other existing callers of llast_oid() on
> HEAD that assume ancestors is never NIL can also hit the following
> assertion:
>   "TRAP: failed Assert("list != NIL"), File:
> "../../../../src/include/nodes/pg_list.h" ..."
>
> One such case is pgoutput.c:get_rel_sync_entry(). To reproduce on HEAD:
> -- create a slot
> SELECT pg_create_logical_replication_slot('myslot', 'pgoutput');
>
> -- get the partition into the pending-detach state (using same A & B
> sessions), and in session C run -
> INSERT INTO t1_part VALUES (5);
> SELECT * FROM pg_logical_slot_get_binary_changes('myslot', NULL, NULL,
> 'proto_version', '1', 'publication_names', 'mypub');
>
> I think this should be handled separately after analyzing whether
> there's a better fix than simply adding if (ancestors != NIL) guards
> at each call site.
> Note: Other callers of llast_oid(ancestors) may need similar review.
>
> Thoughts?
>

Nisha, I am not able to reproduce this on HEAD. Can you please verify
if you missed providing any steps? This I what I have tried:

Session1:
postgres=# SELECT pg_create_logical_replication_slot('myslot', 'pgoutput');
 pg_create_logical_replication_slot
------------------------------------
 (myslot,0/0178F5B8)
(1 row)

postgres=#   CREATE TABLE t1 (a int) PARTITION BY RANGE (a);
  CREATE TABLE t1_part PARTITION OF t1 FOR VALUES FROM (1) TO (100);
  CREATE PUBLICATION mypub FOR TABLE t1;
CREATE TABLE
CREATE TABLE
CREATE PUBLICATION

Session2:
postgres=#  BEGIN;
  SELECT * FROM t1;
BEGIN
 a
---
(0 rows)

Session3:
postgres=#   ALTER TABLE t1 DETACH PARTITION t1_part CONCURRENTLY;
<hanging>

Session4:
postgres=# INSERT INTO t1_part VALUES (5);
SELECT * FROM pg_logical_slot_get_binary_changes('myslot', NULL, NULL,
'proto_version', '1', 'publication_names', 'mypub');
INSERT 0 1
 lsn | xid | data
-----+-----+------
(0 rows)

thanks
Shveta






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-16 05:44  Nisha Moond <nisha.moond412@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: Nisha Moond @ 2026-07-16 05:44 UTC (permalink / raw)
  To: shveta malik <shveta.malik@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Thu, Jul 16, 2026 at 10:15 AM shveta malik <shveta.malik@gmail.com> wrote:
>
> On Wed, Jul 15, 2026 at 10:16 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
> >
> > On Mon, Jul 13, 2026 at 3:31 PM shveta malik <shveta.malik@gmail.com> wrote:
> > >
> > > On Fri, Jul 10, 2026 at 5:07 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
> > > >
> > > >
> > > > Yes, that works for me as we have FOR TABLES example to follow. I've
> > > > made the changes in v20.
> > > >
> > >
> > > Thanks! I had a quick look, few initial comments:
> > >
> > >
> > > 1)
> > > GetTopMostAncestorInPublication():
> > >
> > > + if (ancestors == NIL)
> > > + return InvalidOid;
> > >
> > > Should this be Assert or can there be a case where ancestors list can
> > > come as NIL?
> > >
> >
> > I found one case where ancestors can be NIL.
> > Test case:
> >   CREATE TABLE t1 (a int) PARTITION BY RANGE (a);
> >   CREATE TABLE t1_part PARTITION OF t1 FOR VALUES FROM (1) TO (100);
> >   CREATE PUBLICATION mypub FOR TABLE t1;
> >
> > -- Get the partition into the pending-detach state:
> >  -- Session A:
> >   BEGIN;
> >   SELECT * FROM t1;
> >   -- leave open
> >
> > -- Session B (blocks, waiting on Session A's lock on t1):
> >   ALTER TABLE t1 DETACH PARTITION t1_part CONCURRENTLY;
> >
> > -- Session C, while B is blocked:
> >   SELECT * FROM pg_get_publication_tables('{mypub}'::text[],
> > 't1_part'::regclass);
> >
> > In this scenario, Session C reaches GetTopMostAncestorInPublication()
> > with ancestors == NIL. So I think we should keep return InvalidOid;
> > rather than replacing it with an Assert.
> >
> > While investigating this race, I also hit assertions at places that
> > call "llast_oid(ancestors)" without checking for NIL, for example in
> > check_publication_add_relation() and RelationBuildPublicationDesc(). I
> > fixed those by guarding with if (ancestors != NIL).
>
> Okay, I will review.
>
> > But due to this same race, other existing callers of llast_oid() on
> > HEAD that assume ancestors is never NIL can also hit the following
> > assertion:
> >   "TRAP: failed Assert("list != NIL"), File:
> > "../../../../src/include/nodes/pg_list.h" ..."
> >
> > One such case is pgoutput.c:get_rel_sync_entry(). To reproduce on HEAD:
> > -- create a slot
> > SELECT pg_create_logical_replication_slot('myslot', 'pgoutput');
> >
> > -- get the partition into the pending-detach state (using same A & B
> > sessions), and in session C run -
> > INSERT INTO t1_part VALUES (5);
> > SELECT * FROM pg_logical_slot_get_binary_changes('myslot', NULL, NULL,
> > 'proto_version', '1', 'publication_names', 'mypub');
> >
> > I think this should be handled separately after analyzing whether
> > there's a better fix than simply adding if (ancestors != NIL) guards
> > at each call site.
> > Note: Other callers of llast_oid(ancestors) may need similar review.
> >
> > Thoughts?
> >
>
> Nisha, I am not able to reproduce this on HEAD. Can you please verify
> if you missed providing any steps? This I what I have tried:
>
> Session1:
> postgres=# SELECT pg_create_logical_replication_slot('myslot', 'pgoutput');
>  pg_create_logical_replication_slot
> ------------------------------------
>  (myslot,0/0178F5B8)
> (1 row)
>
> postgres=#   CREATE TABLE t1 (a int) PARTITION BY RANGE (a);
>   CREATE TABLE t1_part PARTITION OF t1 FOR VALUES FROM (1) TO (100);
>   CREATE PUBLICATION mypub FOR TABLE t1;
> CREATE TABLE
> CREATE TABLE
> CREATE PUBLICATION
>
> Session2:
> postgres=#  BEGIN;
>   SELECT * FROM t1;
> BEGIN
>  a
> ---
> (0 rows)
>
> Session3:
> postgres=#   ALTER TABLE t1 DETACH PARTITION t1_part CONCURRENTLY;
> <hanging>
>
> Session4:
> postgres=# INSERT INTO t1_part VALUES (5);
> SELECT * FROM pg_logical_slot_get_binary_changes('myslot', NULL, NULL,
> 'proto_version', '1', 'publication_names', 'mypub');
> INSERT 0 1
>  lsn | xid | data
> -----+-----+------
> (0 rows)
>

A zero-row result indicates the INSERT wasn't decoded, so seems
get_rel_sync_entry() wasn't reached. Sorry for the ambiguous test
steps -- the slot creation order matters.
Please follow these steps to reproduce the issue on HEAD:

Session1:
  CREATE TABLE t1 (a int) PARTITION BY RANGE (a);
  CREATE TABLE t1_part PARTITION OF t1 FOR VALUES FROM (1) TO (100);
  CREATE PUBLICATION mypub FOR ALL TABLES;
  SELECT pg_create_logical_replication_slot('myslot', 'pgoutput');

Session 2:
  BEGIN;
  SELECT * FROM t1;
  -- leave open

Session 3 (hangs):
  ALTER TABLE t1 DETACH PARTITION t1_part CONCURRENTLY;

Session 4, while 3 is blocked:
  INSERT INTO t1_part VALUES (5);
  SELECT * FROM pg_logical_slot_get_binary_changes('myslot', NULL,
NULL, 'proto_version', '1', 'publication_names', 'mypub');

--
Thanks,
Nisha





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-16 06:15  shveta malik <shveta.malik@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: shveta malik @ 2026-07-16 06:15 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; shveta malik <shveta.malik@gmail.com>

On Thu, Jul 16, 2026 at 11:14 AM Nisha Moond <nisha.moond412@gmail.com> wrote:
>
> A zero-row result indicates the INSERT wasn't decoded, so seems
> get_rel_sync_entry() wasn't reached. Sorry for the ambiguous test
> steps -- the slot creation order matters.
> Please follow these steps to reproduce the issue on HEAD:
>
> Session1:
>   CREATE TABLE t1 (a int) PARTITION BY RANGE (a);
>   CREATE TABLE t1_part PARTITION OF t1 FOR VALUES FROM (1) TO (100);
>   CREATE PUBLICATION mypub FOR ALL TABLES;
>   SELECT pg_create_logical_replication_slot('myslot', 'pgoutput');
>
> Session 2:
>   BEGIN;
>   SELECT * FROM t1;
>   -- leave open
>
> Session 3 (hangs):
>   ALTER TABLE t1 DETACH PARTITION t1_part CONCURRENTLY;
>
> Session 4, while 3 is blocked:
>   INSERT INTO t1_part VALUES (5);
>   SELECT * FROM pg_logical_slot_get_binary_changes('myslot', NULL,
> NULL, 'proto_version', '1', 'publication_names', 'mypub');
>

Okay thanks. I am able to reproduce the crash on HEAD now. We can
pursue this in separate thread. I am not immediately clear on the
solution yet. I think this is introduced by:
https://www.postgresql.org/message-id/E1lPX7q-0001lJ-NO%40gemulon.postgresql.org

it seems 'get_partition_parent' is changed to accept an arguement
'even_if_detached' to control whether caller wants detached partition
or  should error-out but no such arguement in
get_partition_ancestors(). We can discuss this in separate thread.

thanks
Shveta






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-16 08:34  Peter Smith <smithpb2250@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  3 siblings, 2 replies; 196+ messages in thread

From: Peter Smith @ 2026-07-16 08:34 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

Hi Nisha.

Some review comments for v21-0001.

======
src/backend/catalog/pg_publication.c

1.
+bool
+get_publication_rel_entry(Oid pubid, Oid relid, bool *is_except)

This is a bit like the 'is_table_publication' function and others.
Perhaps it should be moved nearer that one?

~~~

check_publication_add_relation:

2.
+ Oid relid = RelationGetRelid(targetrel);
+ Oid root;
+ bool root_except;

Those declarations can all be moved closer to where they are used.

~~~

3.
+ * A partition cannot be included when its partition root is in the
+ * same publication's EXCEPT list.  Doing so would leave the catalog
+ * inconsistent (root excluded, partition included) and the
+ * ancestor-cascade rule would silently override the include at
+ * replication time.

Hmm. A single publication may have multiple EXCEPT clauses, but that
first sentence wording seems to be suggesting there is only one.
Perhaps better to say:

SUGGESTION
A partition cannot be included when its partition root is excluded by
the same publication.

~~~

4.
+ errdetail("Ancestor \"%s\" of partition \"%s\" is currently listed
in the EXCEPT clause of the publication.",

For the same reason (a publication may have multiple EXCEPT clauses, I
think this errdetail should change:

/the EXCEPT clause/an EXCEPT clause/

~~~

GetTopMostAncestorInPublication:

5.
+ * If the partition root (the last element of ancestors) is excluded from
+ * this publication via its EXCEPT clause, the partition is not published
+ * through this publication at all, so we short-circuit and return
+ * InvalidOid without walking the ancestor list.  Only the root of a

Similar to above. Should not be singular "its EXCEPT clause".

/via its EXCEPT clause/via an EXCEPT clause/

~~~

6.
  {
- table_close(rel, RowExclusiveLock);
+ bool is_except;

- if (if_not_exists)
- return InvalidObjectAddress;
-
- ereport(ERROR,
- (errcode(ERRCODE_DUPLICATE_OBJECT),
- errmsg("relation \"%s\" is already member of publication \"%s\"",
- RelationGetRelationName(targetrel), pub->name)));
+ if (get_publication_rel_entry(pubid, relid, &is_except))
+ {
...
+ }
  }

I think having a code block like this just for the variable
declaration is unconventional for PG source code; it's not necessary
here, so maybe don't do it.

~~~

7.
+ errdetail("Ancestor \"%s\" of partition \"%s\" is currently listed
in the EXCEPT clause of the publication.",
+   quote_qualified_identifier(get_namespace_name(get_rel_namespace(root)),

Similar (singular) comment to before.

/in the EXCEPT clause/in an EXCEPT clause/

~~~

GetAllSchemaPublicationRelations:

8.
 /*
  * Gets the list of all relations published by FOR TABLES IN SCHEMA
- * publication.
+ * publication, excluding any tables listed in the EXCEPT clause.
  */

/EXCEPT clause./EXCEPT clauses./

~~~

9.
+ /* filter out any tables that appear in the EXCEPT list */
+ ListCell   *rlc;
+
+ foreach(rlc, schemaRels)
+ {
+ Oid relid = lfirst_oid(rlc);

Isn't this loop something that can be simplified using foreach_oid macro?

~~~

10.
+ * A partition whose root is in the publication's EXCEPT list
+ * is also excluded, even if the partition itself lives in a
+ * different (included) schema.  Only the topmost root of a

SUGGESTION #1
A partition whose root is in an EXCEPT list of the publication is also
excluded, even if...

SUGGESTION #2
A partition whose root is excluded from the publication is also
excluded, even if...

~~~

is_table_publishable_in_publication:

11.
+ {
+ bool is_except;
+
+ if (get_publication_rel_entry(pub->oid, relid, &is_except))
+ return !is_except;
+ }

Here is another code block which AFAIK is uncommon in PG source code.
IMO would be better to remove this and have a new function variable
`is_except`. You can also remove the other existing `root_except`
declaration because they can bother share this same var. So, the
result will be fewer vars, less unusual code blocks, less code.

======
src/backend/commands/tablecmds.c

12.
+ errhint("%s", has_alltables_pub ?
+ _("Change the publication's EXCEPT clause using ALTER PUBLICATION
... SET ALL TABLES ... EXCEPT.") :
+ _("Change the publication's EXCEPT clause using ALTER PUBLICATION
... SET TABLES IN SCHEMA ... EXCEPT.")));

12a.
The message wording is slightly broken now because there is potential
for even a single publication to have multiple EXCEPT clauses.

Here it might be OK to reword it like:

BEFORE
Change the publication's EXCEPT clause...

SUGGESTION
Change the EXCEPT clause...

~

12b.
Also, IMO the errmsg_plural might be better if reworded:

BEFORE
"cannot attach table \"%s\" as partition because it is referenced in
publication %s EXCEPT clause",
"cannot attach table \"%s\" as partition because it is referenced in
publications %s EXCEPT clause",

SUGGESTION
"cannot attach table \"%s\" as partition because it is referenced in
EXCEPT clause of publication %s",
"cannot attach table \"%s\" as partition because it is referenced in
EXCEPT clause of publications %s",

======
src/include/catalog/pg_publication.h

13.
+extern bool get_publication_rel_entry(Oid pubid, Oid relid, bool *is_except);

Do you think this function name should be CamelCase (more common for
non-static functions), instead of snake_case?

======
Kind Regards,
Peter Smith.
Fujitsu Australia






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-16 10:32  shveta malik <shveta.malik@gmail.com>
  parent: Peter Smith <smithpb2250@gmail.com>
  1 sibling, 1 reply; 196+ messages in thread

From: shveta malik @ 2026-07-16 10:32 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; Peter Smith <smithpb2250@gmail.com>; shveta malik <shveta.malik@gmail.com>

I have reviewed a portion of v21-001 yet. The comments so far:

1)
check_publication_add_relation:

+ Oid relid = RelationGetRelid(targetrel);

Please move this inside :
+ if (targetrel->rd_rel->relispartition)

2)
Please shorten this comment:

+ /*
+ * If the partition root (the last element of ancestors) is excluded from
+ * this publication via its EXCEPT clause, the partition is not published
+ * through this publication at all, so we short-circuit and return
+ * InvalidOid without walking the ancestor list.  Only the root of a
+ * partition hierarchy can ever appear in a publication's EXCEPT clause (a
+ * partition itself is rejected from EXCEPT elsewhere), so it's the only
+ * one worth a catalog lookup.
+ */

Suggestion:
/*
 * If the partition root is excluded from this publication via its EXCEPT
 * clause, the partition is not published through this publication, so return
 * InvalidOid. Since only partition roots can appear in an EXCEPT clause, the
 * root is the only ancestor worth a catalog lookup.
 */

3)
postgres=#  ALTER TABLE s2.tab_root_new ATTACH PARTITION s2.tab_root
FOR VALUES FROM (1) TO (2000);
ERROR:  cannot attach table "tab_root" as partition because it is
referenced in publication "pub1" EXCEPT clause
DETAIL:  The publication EXCEPT clause cannot contain tables that are
partitions.
HINT:  Change the publication's EXCEPT clause using ALTER PUBLICATION
... SET TABLES IN SCHEMA ... EXCEPT.

postgres=# ALTER publication pub1 add TABLE s2.tab_part_1_p2;
ERROR:  cannot add partition "s2.tab_part_1_p2" to publication "pub1"
DETAIL:  Ancestor "s2.tab_root" of partition "s2.tab_part_1_p2" is
currently listed in the EXCEPT clause of the publication.
HINT:  Change EXCEPT list using ALTER PUBLICATION ... SET TABLES IN
SCHEMA ... EXCEPT.

Can we make HINT same? We can retain the wording of HINT given in
ATTACH PARTITION case as that is existing one.

4)
postgres=# create publication pub1 for tables in schema s2 except
(table s2.tab_root), table s2.tab_part_2, table s2.tab_part_1_p2;
ERROR:  partition "s2.tab_part_2" cannot be both published and excluded
DETAIL:  Ancestor "s2.tab_root" of partition "s2.tab_part_2" is
currently listed in the EXCEPT clause of this command.

postgres=# ALTER publication pub1 add TABLE s2.tab_part_1_p2;
ERROR:  cannot add partition "s2.tab_part_1_p2" to publication "pub1"
DETAIL:  Ancestor "s2.tab_root" of partition "s2.tab_part_1_p2" is
currently listed in the EXCEPT clause of the publication.
HINT:  Change EXCEPT list using ALTER PUBLICATION ... SET TABLES IN
SCHEMA ... EXCEPT.


Should the DETAIL be just:
DETAIL:  Partition root "s2.tab_root" is listed in the publication's
EXCEPT clause.

Thoughts?

thanks
Shveta






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-17 04:19  Peter Smith <smithpb2250@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  3 siblings, 2 replies; 196+ messages in thread

From: Peter Smith @ 2026-07-17 04:19 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

Hi Nisha.

I noticed multiple places where these patches want to discover the
root partition table OID, but they are not interested in the ancestor
tree.

I've created another thread/patch [1] to introduce a
`get_partition_root` C function. I think this could simplify some of
your code by removing the requirement to declare and free the unwanted
ancestor lists.

Please take a look and give your +1 there if you think it would be useful.

======
[1] https://www.postgresql.org/message-id/CAHut%2BPtc73UpWSn4teMyMxQoHwGJjRwhWiu%3DhGJqAj5k2AOXEw%40mail...

Kind Regards,
Peter Smith.
Fujitsu Australia






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-17 06:56  Peter Smith <smithpb2250@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  0 siblings, 0 replies; 196+ messages in thread

From: Peter Smith @ 2026-07-17 06:56 UTC (permalink / raw)
  To: shveta malik <shveta.malik@gmail.com>; +Cc: Nisha Moond <nisha.moond412@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Thu, Jul 16, 2026 at 8:32 PM shveta malik <shveta.malik@gmail.com> wrote:
...
> 4)
> postgres=# create publication pub1 for tables in schema s2 except
> (table s2.tab_root), table s2.tab_part_2, table s2.tab_part_1_p2;
> ERROR:  partition "s2.tab_part_2" cannot be both published and excluded
> DETAIL:  Ancestor "s2.tab_root" of partition "s2.tab_part_2" is
> currently listed in the EXCEPT clause of this command.
>
> postgres=# ALTER publication pub1 add TABLE s2.tab_part_1_p2;
> ERROR:  cannot add partition "s2.tab_part_1_p2" to publication "pub1"
> DETAIL:  Ancestor "s2.tab_root" of partition "s2.tab_part_1_p2" is
> currently listed in the EXCEPT clause of the publication.
> HINT:  Change EXCEPT list using ALTER PUBLICATION ... SET TABLES IN
> SCHEMA ... EXCEPT.
>
>
> Should the DETAIL be just:
> DETAIL:  Partition root "s2.tab_root" is listed in the publication's
> EXCEPT clause.
>
> Thoughts?

After some offline discussion, we've landed on the following consensus
for this errdetail replacement:

DETAIL: Partition root "s2.tab_root" is named in the publication's
EXCEPT clause for schema "s2"

- The earlier message wrongly implied that a publication can have only
1 EXCEPT clause
- This new one explicitly identifies exactly which EXCEPT clause is involved
- IIUC, this particular message is never used by the ALL TABLES EXCEPT
logic, so naming the schema should be fine

======
Kind Regards,
Peter Smith.
Fujitsu Australia






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-17 08:07  Peter Smith <smithpb2250@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  3 siblings, 2 replies; 196+ messages in thread

From: Peter Smith @ 2026-07-17 08:07 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

Some review comments for v21-0002.

======
Commit message.

1.
Add ProcessSchemaExceptTables() to qualify each mention's EXCEPT
entries, build a sorted signature per schema OID, and compare it
against any prior mention of the same schema in the same statement,
erroring on a mismatch. It also checks there are no clashes of the
same schema with or without EXCEPT.

~

IMO it's too confusing to explain the implementation detail here
instead of the purpose. Also, it should say "with *and* without".

SUGGESTION
Add ProcessSchemaExceptTables(), which errors if the same schema is
mentioned more than once with EXCEPT, or both with and without EXCEPT.
It also checks that a schema's EXCEPT clause only lists tables from
that same schema.

======
src/backend/commands/publicationcmds.c

ProcessSchemaExceptTables:

2.
+/*
+ * Qualify unqualified EXCEPT table names with the given schema, reject
+ * entries explicitly qualified with a different schema, and append the (now
+ * qualified) tables to *except_pubtables.
+ *
+ * Also rejects a repeated mention of the same schema in the same TABLES IN
+ * SCHEMA list if it, or an earlier mention of the same schema, specified a
+ * non-empty EXCEPT list, without checking whether the EXCEPT lists across
+ * all the mentions actually name the same tables. This mirrors
+ * OpenTableList()'s handling of repeated tables with column lists (e.g.
+ * "FOR TABLE t1(a), t1(a)" is rejected even though the lists match):
+ * repeated mentions of the same schema wouldn't have a well-defined single
+ * EXCEPT list to enforce, so they're rejected as conflicting or redundant
+ * rather than silently unioned or compared for equivalence.  A schema may
+ * still be mentioned multiple times as long as none of the mentions
+ * specify EXCEPT.
+ * *schemas_with_except accumulates the OIDs of schemas already seen with a
+ * non-empty EXCEPT list in this statement.
+ */

2a.
This function comment seems very complex. Here is a simpler version;
AFAICT it says the same:

SUGGESTION
/*
 * Qualify unqualified EXCEPT table names with the given schema (rejecting
 * any explicitly qualified with a different schema), and append them to
 * *except_pubtables.
 *
 * Also rejects a schema being mentioned more than once with an EXCEPT
 * clause, even if the EXCEPT lists are identical — much like
 * OpenTableList() rejects "FOR TABLE t1(a), t1(a)" despite the column
 * lists matching. A schema can still be mentioned multiple times, just
 * not more than once with EXCEPT.
 *
 * *schemas_with_except tracks which schema OIDs have already been seen
 * with an EXCEPT clause in this statement.
 */

~~

2b.
It would also be helpful to explain what the other parameters are.

IIUC, it is something like:

`*except_tables` = "the EXCEPT list (or NIL) for this schema"
`*schemas` =  "the list of all schema OIDs seen so far for this statement"

~~~

3.
+ /*
+ * A repeat is only a problem if this mention has EXCEPT, or an earlier
+ * mention of the same schema did.
+ */

/A repeat is only a problem/A repeating schema is only a problem/

~~~

4.
+ /*
+ * A repeat is only a problem if this mention has EXCEPT, or an earlier
+ * mention of the same schema did.
+ */
+ if (list_member_oid(*schemas, schemaid))
+ {
+ if (except_tables != NIL ||
+ list_member_oid(*schemas_with_except, schemaid))
+ ereport(ERROR,
+ errcode(ERRCODE_DUPLICATE_OBJECT),
+ errmsg("conflicting or redundant EXCEPT lists for schema \"%s\"",
+    schema_name));
+ }
+
+ if (except_tables != NIL)
+ *schemas_with_except = lappend_oid(*schemas_with_except, schemaid);
+
+ /* Filter out duplicates if the user specifies "sch1, sch1" */
+ *schemas = list_append_unique_oid(*schemas, schemaid);
+
+ if (except_tables == NIL)
+ return;

All the except_tables checks are making this code harder to read than
it needs to be. How about having another variable:

bool schema_has_except = (except_tables != NIL);

======
Kind Regards,
Peter Smith.
Fujitsu Australia






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-20 02:20  Peter Smith <smithpb2250@gmail.com>
  parent: Peter Smith <smithpb2250@gmail.com>
  1 sibling, 0 replies; 196+ messages in thread

From: Peter Smith @ 2026-07-20 02:20 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

One more v21* review comment...

1.
@@ -6838,6 +6838,24 @@ describePublications(const char *pattern)
  if (!addFooterToPublicationDesc(&buf, _("Tables from schemas:"),
  true, &cont))
  goto error_return;
+
+ if (pset.sversion >= 190000)
+ {
+ /*
+ * Get tables in the EXCEPT clause for this schema
+ * publication.
+ */

The SCHEMA EXCEPT does not exist in PG19, so shouldn't that version
check be 200000?

======
Kind Regards,
Peter Smith.
Fujitsu Australia






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-20 07:21  Nisha Moond <nisha.moond412@gmail.com>
  parent: Peter Smith <smithpb2250@gmail.com>
  1 sibling, 0 replies; 196+ messages in thread

From: Nisha Moond @ 2026-07-20 07:21 UTC (permalink / raw)
  To: Peter Smith <smithpb2250@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Fri, Jul 17, 2026 at 9:50 AM Peter Smith <smithpb2250@gmail.com> wrote:
>
> Hi Nisha.
>
> I noticed multiple places where these patches want to discover the
> root partition table OID, but they are not interested in the ancestor
> tree.
>
> I've created another thread/patch [1] to introduce a
> `get_partition_root` C function. I think this could simplify some of
> your code by removing the requirement to declare and free the unwanted
> ancestor lists.
>
> Please take a look and give your +1 there if you think it would be useful.
>

Okay, the idea looks reasonable to me. I'll review the patch and share
my thoughts on the thread.

--
Thanks,
Nisha






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-20 08:22  Nisha Moond <nisha.moond412@gmail.com>
  parent: Peter Smith <smithpb2250@gmail.com>
  1 sibling, 1 reply; 196+ messages in thread

From: Nisha Moond @ 2026-07-20 08:22 UTC (permalink / raw)
  To: Peter Smith <smithpb2250@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Thu, Jul 16, 2026 at 2:04 PM Peter Smith <smithpb2250@gmail.com> wrote:
>
> Hi Nisha.
>
> Some review comments for v21-0001.
>

Thanks for the review. I've applied all the suggestions in v22.

> ~~~
>
> 7.
> + errdetail("Ancestor \"%s\" of partition \"%s\" is currently listed
> in the EXCEPT clause of the publication.",
> +   quote_qualified_identifier(get_namespace_name(get_rel_namespace(root)),
>
> Similar (singular) comment to before.
>
> /in the EXCEPT clause/in an EXCEPT clause/
>

It looks like comment #4 is repeated here. In any case, I addressed
both occurrences of the errdetail (in check_publication_add_relation()
and CheckExceptNotInTableList()):
  "Ancestor \"%s\" of partition \"%s\" is curre..".

> ~~~
> 9.
> + /* filter out any tables that appear in the EXCEPT list */
> + ListCell   *rlc;
> +
> + foreach(rlc, schemaRels)
> + {
> + Oid relid = lfirst_oid(rlc);
>
> Isn't this loop something that can be simplified using foreach_oid macro?
>

Yes, that's possible. I've simplified it.

> ~~~
>
> 10.
> + * A partition whose root is in the publication's EXCEPT list
> + * is also excluded, even if the partition itself lives in a
> + * different (included) schema.  Only the topmost root of a
>
> SUGGESTION #1
> A partition whose root is in an EXCEPT list of the publication is also
> excluded, even if...
>
> SUGGESTION #2
> A partition whose root is excluded from the publication is also
> excluded, even if...
>

Changed as per SUGGESTION #2.

> ======
> src/include/catalog/pg_publication.h
>
> 13.
> +extern bool get_publication_rel_entry(Oid pubid, Oid relid, bool *is_except);
>
> Do you think this function name should be CamelCase (more common for
> non-static functions), instead of snake_case?
>

I kept it consistent with the nearby functions, but I agree, it should
use CamelCase for a non-static function.
~~~

Attached is the v22 patch set. Also incorporated all the other
suggestions and feedback from Shveta and Peter at [1], [2], [3], and
[4].

[1] https://www.postgresql.org/message-id/CAJpy0uCj8NdSuWSWkn8iGriz1D1i1g-rMLs9Fk8SEf8uWs60ww%40mail.gma...
[2] https://www.postgresql.org/message-id/CAHut%2BPsqq%3DNT%3DbhuKtqTU%2B0esbk2cxhxPYp3jjn3KTR%2BL4wc9w%...
[3] https://www.postgresql.org/message-id/CAHut%2BPuA8YUdqMLS9QjU991bb6N1i5Eo9gq5wUzA7WJbG4FB3g%40mail.g...
[4] https://www.postgresql.org/message-id/CAHut%2BPvCeJ6yDdRu3Qo7-M5fMzZnV1aEDPckW3oLmgY4xPw3HA%40mail.g...

--
Thanks,
Nisha

Attachments: download all (5 files, .tar.gz)

v22-0001-Support-EXCEPT-clause-for-schema-level-publicati.patch (application/octet-stream, 79.2K) download From 787a4108724ea96548c7384a4637dae64bc1a25d Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Tue, 16 Jun 2026 10:58:49 +0530 Subject: [PATCH v22 1/5] Support EXCEPT clause for schema-level publications Extend table exclusion support in publications to allow specific tables to be excluded from schema-level publications using an EXCEPT clause in CREATE PUBLICATION. Supported syntax: CREATE PUBLICATION <pub> FOR TABLES IN SCHEMA s EXCEPT (TABLE t1,...); --- src/backend/catalog/pg_publication.c | 237 ++++++++++++++++---- src/backend/commands/publicationcmds.c | 197 +++++++++++++++- src/backend/commands/tablecmds.c | 24 +- src/backend/parser/gram.y | 54 ++++- src/backend/replication/pgoutput/pgoutput.c | 32 ++- src/backend/utils/cache/relcache.c | 44 ++-- src/bin/psql/describe.c | 18 ++ src/bin/psql/tab-complete.in.c | 35 ++- src/include/catalog/pg_publication.h | 1 + src/include/commands/publicationcmds.h | 2 + src/include/nodes/parsenodes.h | 2 + src/test/regress/expected/publication.out | 226 ++++++++++++++++++- src/test/regress/sql/publication.sql | 143 +++++++++++- src/test/subscription/t/037_except.pl | 208 ++++++++++++++++- 14 files changed, 1126 insertions(+), 97 deletions(-) diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index 1ec94c851b2..145559e9248 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -53,7 +53,7 @@ typedef struct * error if not. */ static void -check_publication_add_relation(PublicationRelInfo *pri) +check_publication_add_relation(PublicationRelInfo *pri, Oid pubid) { Relation targetrel = pri->relation; const char *relname; @@ -70,12 +70,46 @@ check_publication_add_relation(PublicationRelInfo *pri) errormsg = gettext_noop("cannot add relation \"%s\" to publication"); } - /* If in EXCEPT clause, must be root partitioned table */ - if (pri->except && targetrel->rd_rel->relispartition) - ereport(ERROR, - (errcode(ERRCODE_INVALID_PARAMETER_VALUE), - errmsg(errormsg, relname), - errdetail("This operation is not supported for individual partitions."))); + if (targetrel->rd_rel->relispartition) + { + Oid relid = RelationGetRelid(targetrel); + Oid root; + bool root_except; + + if (pri->except) + { + /* If in EXCEPT clause, must be root partitioned table */ + ereport(ERROR, + (errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg(errormsg, relname), + errdetail("This operation is not supported for individual partitions."))); + } + + /* + * A partition cannot be included when its partition root is excluded + * by the same publication. Doing so would leave the catalog + * inconsistent (root excluded, partition included) and the + * ancestor-cascade rule would silently override the include at + * replication time. + * + * For partition hierarchies, only the partition root can be in an + * EXCEPT clause (a partition itself is rejected just above), so we + * only need to look up the catalog for the root. + */ + root = llast_oid(get_partition_ancestors(relid)); + + if (GetPublicationRelEntry(pubid, root, &root_except) && root_except) + ereport(ERROR, + errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("cannot add partition \"%s\" to publication \"%s\"", + RelationGetQualifiedRelationName(targetrel), + get_publication_name(pubid, false)), + errdetail("Partition root \"%s\" is named in the publication's EXCEPT clause for schema \"%s\".", + quote_qualified_identifier(get_namespace_name(get_rel_namespace(root)), + get_rel_name(root)), + get_namespace_name(get_rel_namespace(root))), + errhint("Change the EXCEPT clause using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT.")); + } /* Must be a regular or partitioned table */ if (RelationGetForm(targetrel)->relkind != RELKIND_RELATION && @@ -319,7 +353,7 @@ is_schema_publication(Oid pubid) } /* - * Returns true if the publication has explicitly included relation (i.e., + * Returns true if the publication has an explicitly-included relation (i.e., * not marked as EXCEPT). */ bool @@ -340,19 +374,20 @@ is_table_publication(Oid pubid) scan = systable_beginscan(pubrelsrel, PublicationRelPrpubidIndexId, true, NULL, 1, &scankey); - tup = systable_getnext(scan); - if (HeapTupleIsValid(tup)) - { - Form_pg_publication_rel pubrel; - pubrel = (Form_pg_publication_rel) GETSTRUCT(tup); - - /* - * For any publication, pg_publication_rel contains either only EXCEPT - * entries or only explicitly included tables. Therefore, examining - * the first tuple is sufficient to determine table inclusion. - */ - result = !pubrel->prexcept; + /* + * A publication can hold both explicitly-included (prexcept=false) and + * EXCEPT (prexcept=true) rows for the same pubid. Scan until we find an + * explicitly-included row, rather than relying on the first row's + * prexcept value. + */ + while (HeapTupleIsValid(tup = systable_getnext(scan))) + { + if (!((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept) + { + result = true; + break; + } } systable_endscan(scan); @@ -361,6 +396,27 @@ is_table_publication(Oid pubid) return result; } +/* + * Check whether a pg_publication_rel row exists for (pubid, relid); if so, + * set *is_except to its prexcept flag. + */ +bool +GetPublicationRelEntry(Oid pubid, Oid relid, bool *is_except) +{ + HeapTuple tup; + + tup = SearchSysCache2(PUBLICATIONRELMAP, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (!HeapTupleIsValid(tup)) + return false; + + *is_except = ((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept; + ReleaseSysCache(tup); + + return true; +} + /* * Returns true if the relation has column list associated with the * publication, false otherwise. @@ -456,11 +512,26 @@ GetPubPartitionOptionRelations(List *result, PublicationPartOpt pub_partopt, * ancestor is at the end of the list. */ Oid -GetTopMostAncestorInPublication(Oid puboid, List *ancestors, int *ancestor_level) +GetTopMostAncestorInPublication(Oid puboid, List *ancestors, + int *ancestor_level) { ListCell *lc; Oid topmost_relid = InvalidOid; int level = 0; + bool root_except; + + if (ancestors == NIL) + return InvalidOid; + + /* + * If the partition root is excluded from this publication via an EXCEPT + * clause, the partition is not published through this publication, so + * return InvalidOid. Since only partition roots can appear in an EXCEPT + * clause, the root is the only ancestor worth a catalog lookup. + */ + if (GetPublicationRelEntry(puboid, llast_oid(ancestors), &root_except) && + root_except) + return InvalidOid; /* * Find the "topmost" ancestor that is in this publication. @@ -547,6 +618,7 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, List *relids = NIL; int i; bool inval_except_table; + bool is_except; rel = table_open(PublicationRelRelationId, RowExclusiveLock); @@ -555,21 +627,29 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, * duplicates, it's here just to provide nicer error message in common * case. The real protection is the unique key on the catalog. */ - if (SearchSysCacheExists2(PUBLICATIONRELMAP, ObjectIdGetDatum(relid), - ObjectIdGetDatum(pubid))) + if (GetPublicationRelEntry(pubid, relid, &is_except)) { table_close(rel, RowExclusiveLock); if (if_not_exists) return InvalidObjectAddress; - ereport(ERROR, - (errcode(ERRCODE_DUPLICATE_OBJECT), - errmsg("relation \"%s\" is already member of publication \"%s\"", - RelationGetRelationName(targetrel), pub->name))); + if (is_except) + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("cannot add table \"%s\" to publication \"%s\"", + RelationGetQualifiedRelationName(targetrel), + pub->name), + errdetail("The table is currently listed in the EXCEPT clause of the publication."), + errhint("Change the EXCEPT clause using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT."))); + else + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("relation \"%s\" is already member of publication \"%s\"", + RelationGetRelationName(targetrel), pub->name))); } - check_publication_add_relation(pri); + check_publication_add_relation(pri, pubid); /* Validate and translate column names into a Bitmapset of attnums. */ attnums = pub_collist_validate(pri->relation, pri->columns); @@ -992,12 +1072,13 @@ GetIncludedPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) * Gets list of table oids that were specified in the EXCEPT clause for a * publication. * - * This should only be used FOR ALL TABLES publications. + * This is used for FOR ALL TABLES and FOR TABLES IN SCHEMA publications, + * both of which support EXCEPT TABLE. */ List * GetExcludedPublicationTables(Oid pubid, PublicationPartOpt pub_partopt) { - Assert(GetPublication(pubid)->alltables); + Assert(GetPublication(pubid)->alltables || is_schema_publication(pubid)); return get_publication_relations(pubid, pub_partopt, true); } @@ -1059,15 +1140,15 @@ GetAllPublicationRelations(Oid pubid, char relkind, bool pubviaroot) TableScanDesc scan; HeapTuple tuple; List *result = NIL; - List *exceptlist = NIL; + List *except_relids = NIL; Assert(!(relkind == RELKIND_SEQUENCE && pubviaroot)); /* EXCEPT filtering applies only to relations, not sequences */ if (relkind == RELKIND_RELATION) - exceptlist = GetExcludedPublicationTables(pubid, pubviaroot ? - PUBLICATION_PART_ROOT : - PUBLICATION_PART_LEAF); + except_relids = GetExcludedPublicationTables(pubid, pubviaroot ? + PUBLICATION_PART_ROOT : + PUBLICATION_PART_LEAF); classRel = table_open(RelationRelationId, AccessShareLock); @@ -1085,7 +1166,7 @@ GetAllPublicationRelations(Oid pubid, char relkind, bool pubviaroot) if (is_publishable_class(relid, relForm) && !(relForm->relispartition && pubviaroot) && - !list_member_oid(exceptlist, relid)) + !list_member_oid(except_relids, relid)) result = lappend_oid(result, relid); } @@ -1107,7 +1188,7 @@ GetAllPublicationRelations(Oid pubid, char relkind, bool pubviaroot) if (is_publishable_class(relid, relForm) && !relForm->relispartition && - !list_member_oid(exceptlist, relid)) + !list_member_oid(except_relids, relid)) result = lappend_oid(result, relid); } @@ -1242,22 +1323,60 @@ GetSchemaPublicationRelations(Oid schemaid, PublicationPartOpt pub_partopt) /* * Gets the list of all relations published by FOR TABLES IN SCHEMA - * publication. + * publication, excluding any tables listed in EXCEPT clauses. */ List * GetAllSchemaPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) { List *result = NIL; List *pubschemalist = GetPublicationSchemas(pubid); + List *except_relids = NIL; ListCell *cell; + /* get the list of tables excluded via EXCEPT TABLE for this publication */ + if (pubschemalist != NIL) + except_relids = GetExcludedPublicationTables(pubid, pub_partopt); + foreach(cell, pubschemalist) { Oid schemaid = lfirst_oid(cell); List *schemaRels = NIL; schemaRels = GetSchemaPublicationRelations(schemaid, pub_partopt); - result = list_concat(result, schemaRels); + + if (except_relids != NIL) + { + /* filter out any tables that appear in the EXCEPT list */ + foreach_oid(relid, schemaRels) + { + bool excluded = list_member_oid(except_relids, relid); + + /* + * A partition whose root is excluded from the publication is + * also excluded, even if the partition itself lives in a + * different (included) schema. Only the topmost root of a + * partition hierarchy can ever appear in EXCEPT (see + * check_publication_add_relation()), so it's enough to check + * the last element of the ancestors list, rather than walking + * the whole chain. + */ + if (!excluded && get_rel_relispartition(relid)) + { + List *ancestors = get_partition_ancestors(relid); + + if (ancestors != NIL) + excluded = list_member_oid(except_relids, + llast_oid(ancestors)); + list_free(ancestors); + } + + if (!excluded) + result = lappend_oid(result, relid); + } + list_free(schemaRels); + } + else + result = list_concat(result, schemaRels); } return result; @@ -1334,6 +1453,7 @@ is_table_publishable_in_publication(Oid relid, Publication *pub) { bool relispartition; List *ancestors = NIL; + bool is_except; /* * For non-pubviaroot publications, a partitioned table is never the @@ -1390,20 +1510,43 @@ is_table_publishable_in_publication(Oid relid, Publication *pub) * If it's false, the partition is covered by its ancestor's presence in * the publication, it should be included (return true). */ - if (relispartition && - OidIsValid(GetTopMostAncestorInPublication(pub->oid, ancestors, NULL))) - return !pub->pubviaroot; + if (relispartition) + { + if (OidIsValid(GetTopMostAncestorInPublication(pub->oid, ancestors, NULL))) + return !pub->pubviaroot; + + /* + * GetTopMostAncestorInPublication() returns InvalidOid both when no + * ancestor matched at all, and when the root is excluded via EXCEPT. + * Disambiguate here: if the root is excluded, the partition is never + * published through this publication, regardless of whether the + * partition's schema is separately included. ancestors can be NIL + * for a partition whose DETACH ... CONCURRENTLY is pending, in which + * case there is no ancestor to check. + */ + if (ancestors != NIL && + GetPublicationRelEntry(pub->oid, llast_oid(ancestors), &is_except) && + is_except) + return false; + } /* * Check whether the table is explicitly published via pg_publication_rel * or pg_publication_namespace. + * + * A pg_publication_rel row with prexcept=true means the table is + * explicitly excluded via EXCEPT and must not be reported as published, + * even if its schema is otherwise included. A row with prexcept=false + * means it is explicitly included. If no pg_publication_rel row exists, + * the table is published iff its schema appears in + * pg_publication_namespace. */ - return (SearchSysCacheExists2(PUBLICATIONRELMAP, - ObjectIdGetDatum(relid), - ObjectIdGetDatum(pub->oid)) || - SearchSysCacheExists2(PUBLICATIONNAMESPACEMAP, - ObjectIdGetDatum(get_rel_namespace(relid)), - ObjectIdGetDatum(pub->oid))); + if (GetPublicationRelEntry(pub->oid, relid, &is_except)) + return !is_except; + + return SearchSysCacheExists2(PUBLICATIONNAMESPACEMAP, + ObjectIdGetDatum(get_rel_namespace(relid)), + ObjectIdGetDatum(pub->oid)); } /* diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 440adb356ad..ba35e48b306 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -22,6 +22,7 @@ #include "catalog/namespace.h" #include "catalog/objectaccess.h" #include "catalog/objectaddress.h" +#include "catalog/partition.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" #include "catalog/pg_namespace.h" @@ -71,6 +72,7 @@ static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); static char defGetGeneratedColsOption(DefElem *def); +static void CheckExceptNotInTableList(List *except_rels, List *explicitrelids); static void @@ -181,7 +183,7 @@ parse_publication_options(ParseState *pstate, */ static void ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, - List **rels, List **exceptrels, List **schemas) + List **rels, List **except_pubtables, List **schemas) { ListCell *cell; PublicationObjSpec *pubobj; @@ -200,7 +202,7 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, { case PUBLICATIONOBJ_EXCEPT_TABLE: pubobj->pubtable->except = true; - *exceptrels = lappend(*exceptrels, pubobj->pubtable); + *except_pubtables = lappend(*except_pubtables, pubobj->pubtable); break; case PUBLICATIONOBJ_TABLE: pubobj->pubtable->except = false; @@ -224,6 +226,38 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, /* Filter out duplicates if user specifies "sch1, sch1" */ *schemas = list_append_unique_oid(*schemas, schemaid); + + /* + * Qualify unqualified EXCEPT table names with the resolved + * current schema and reject any explicitly cross-schema + * entries. This mirrors the parse-time handling done for + * TABLES_IN_SCHEMA in preprocess_pubobj_list(), deferred here + * because CURRENT_SCHEMA is not known until execution time. + */ + if (pubobj->except_tables != NIL) + { + char *cur_schema_name = get_namespace_name(schemaid); + + foreach_ptr(PublicationObjSpec, eobj, pubobj->except_tables) + { + const char *eobj_schemaname = + eobj->pubtable->relation->schemaname; + const char *eobj_relname = + eobj->pubtable->relation->relname; + + if (eobj_schemaname == NULL) + eobj->pubtable->relation->schemaname = cur_schema_name; + else if (strcmp(eobj_schemaname, cur_schema_name) != 0) + ereport(ERROR, + errcode(ERRCODE_INVALID_OBJECT_DEFINITION), + errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", + quote_qualified_identifier(eobj_schemaname, eobj_relname), + cur_schema_name)); + + *except_pubtables = lappend(*except_pubtables, + eobj->pubtable); + } + } break; default: /* shouldn't happen */ @@ -770,6 +804,60 @@ TransformPubWhereClauses(List *tables, const char *queryString, } } +/* + * Check that a table is not both excluded and published in the same DDL. + * + * An excluded relation (except_rels) cannot also be present in + * explicitrelids, the list of OIDs added to the publication by the explicit + * TABLE list. + * + * Also reject any relation in explicitrelids whose partition root is in + * except_rels. Otherwise the catalog would be inconsistent (root excluded, + * partition explicitly included), and the ancestor-cascade rule would + * silently override the include at replication time. + */ +static void +CheckExceptNotInTableList(List *except_rels, List *explicitrelids) +{ + foreach_oid(explicitrelid, explicitrelids) + { + Oid root = InvalidOid; + + if (get_rel_relispartition(explicitrelid)) + { + List *ancestors = get_partition_ancestors(explicitrelid); + + /* + * ancestors is NIL for a partition with a pending DETACH + * CONCURRENTLY. + */ + if (ancestors != NIL) + root = llast_oid(ancestors); + list_free(ancestors); + } + + foreach_ptr(PublicationRelInfo, pri, except_rels) + { + Oid exceptrelid = RelationGetRelid(pri->relation); + + if (exceptrelid == explicitrelid) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" cannot be both published and excluded", + RelationGetQualifiedRelationName(pri->relation))); + + if (OidIsValid(root) && exceptrelid == root) + ereport(ERROR, + (errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("partition \"%s\" cannot be both published and excluded", + quote_qualified_identifier(get_namespace_name(get_rel_namespace(explicitrelid)), + get_rel_name(explicitrelid))), + errdetail("Partition root \"%s\" is named in the publication's EXCEPT clause for schema \"%s\".", + RelationGetQualifiedRelationName(pri->relation), + get_namespace_name(RelationGetNamespace(pri->relation))))); + } + } +} /* * Given a list of tables that are going to be added to a publication, @@ -849,7 +937,7 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) char publish_generated_columns; AclResult aclresult; List *relations = NIL; - List *exceptrelations = NIL; + List *except_pubtables = NIL; List *schemaidlist = NIL; /* must have CREATE privilege on database */ @@ -936,16 +1024,16 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) /* Associate objects with the publication. */ ObjectsInPublicationToOids(stmt->pubobjects, pstate, &relations, - &exceptrelations, &schemaidlist); + &except_pubtables, &schemaidlist); if (stmt->for_all_tables) { /* Process EXCEPT table list */ - if (exceptrelations != NIL) + if (except_pubtables != NIL) { List *rels; - rels = OpenTableList(exceptrelations); + rels = OpenTableList(except_pubtables); PublicationAddTables(puboid, rels, true, NULL); CloseTableList(rels); } @@ -959,6 +1047,8 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) } else if (!stmt->for_all_sequences) { + List *explicitrelids = NIL; + /* FOR TABLES IN SCHEMA requires superuser */ if (schemaidlist != NIL && !superuser()) ereport(ERROR, @@ -977,6 +1067,19 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) schemaidlist != NIL, publish_via_partition_root); + /* + * Collect explicit table OIDs now, before we close the relation + * list, so that except-table validation below can check for + * contradictions without relying on a catalog scan that might not + * yet see the just-inserted rows. + */ + if (except_pubtables != NIL) + { + foreach_ptr(PublicationRelInfo, pri, rels) + explicitrelids = lappend_oid(explicitrelids, + RelationGetRelid(pri->relation)); + } + PublicationAddTables(puboid, rels, true, NULL); CloseTableList(rels); } @@ -989,6 +1092,26 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) */ LockSchemaList(schemaidlist); PublicationAddSchemas(puboid, schemaidlist, true, NULL); + + if (except_pubtables != NIL) + { + List *except_rels; + + except_rels = OpenTableList(except_pubtables); + + /* + * Validate that each excluded table is not also in the + * explicit table list (which would be contradictory), and + * that no explicit partition's root is in the except list. + * Use the in-memory explicitrelids collected above rather + * than re-reading the catalog, which may not yet see the + * just-inserted rows. + */ + CheckExceptNotInTableList(except_rels, explicitrelids); + + PublicationAddTables(puboid, except_rels, true, NULL); + CloseTableList(except_rels); + } } } @@ -1683,12 +1806,12 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) else { List *relations = NIL; - List *exceptrelations = NIL; + List *except_pubtables = NIL; List *schemaidlist = NIL; Oid pubid = pubform->oid; ObjectsInPublicationToOids(stmt->pubobjects, pstate, &relations, - &exceptrelations, &schemaidlist); + &except_pubtables, &schemaidlist); CheckAlterPublication(stmt, tup, relations, schemaidlist); @@ -1711,7 +1834,7 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) errmsg("publication \"%s\" does not exist", stmt->pubname)); - relations = list_concat(relations, exceptrelations); + relations = list_concat(relations, except_pubtables); AlterPublicationTables(stmt, tup, relations, pstate->p_sourcetext, schemaidlist != NIL); AlterPublicationSchemas(stmt, tup, schemaidlist); @@ -1829,6 +1952,62 @@ RemovePublicationSchemaById(Oid psoid) table_close(rel, RowExclusiveLock); } +/* + * Remove any EXCEPT clause entries for a relation from schema publications. + * Called when a table changes schema (ALTER TABLE ... SET SCHEMA), so that + * a schema-scoped exclusion does not silently follow the table to its new + * schema. + */ +void +RemoveSchemaPubExceptForRel(Oid relid, Oid oldNspOid, Oid newNspOid) +{ + List *pubids; + + /* + * If the table is not actually moving to a different schema (no-op ALTER + * TABLE ... SET SCHEMA <current_schema>), there is nothing to do. + */ + if (oldNspOid == newNspOid) + return; + + pubids = GetRelationExcludedPublications(relid); + + foreach_oid(pubid, pubids) + { + Oid proid; + + /* + * This problem does not apply to FOR ALL TABLES publications, because + * their EXCEPT clause is publication-scoped, not schema-scoped: the + * exclusion should persist regardless of what schema the table is in. + */ + if (!is_schema_publication(pubid)) + continue; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddress obj; + + ObjectAddressSet(obj, PublicationRelRelationId, proid); + + ereport(DEBUG2, + errmsg_internal("auto-remove exclusion of table \"%s.%s\" from publication \"%s\": table moved to schema \"%s\"", + get_namespace_name(oldNspOid), + get_rel_name(relid), + get_publication_name(pubid, false), + get_namespace_name(newNspOid))); + + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + list_free(pubids); +} + /* * Open relations specified by a PublicationTable list. * The returned tables are locked in ShareUpdateExclusiveLock mode in order to diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..7e71b3d5e3b 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -49,6 +49,7 @@ #include "catalog/pg_opclass.h" #include "catalog/pg_policy.h" #include "catalog/pg_proc.h" +#include "catalog/pg_publication.h" #include "catalog/pg_publication_rel.h" #include "catalog/pg_rewrite.h" #include "catalog/pg_statistic_ext.h" @@ -63,6 +64,7 @@ #include "commands/event_trigger.h" #include "commands/extension.h" #include "commands/repack.h" +#include "commands/publicationcmds.h" #include "commands/sequence.h" #include "commands/tablecmds.h" #include "commands/tablespace.h" @@ -19745,6 +19747,16 @@ AlterTableNamespaceInternal(Relation rel, Oid oldNspOid, Oid nspOid, AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid, false, objsMoved); + /* + * Remove any EXCEPT clause entries for this relation from schema + * publications. A schema-scoped exclusion is no longer meaningful once + * the table moves to a different schema. + */ + if (rel->rd_rel->relkind == RELKIND_RELATION || + rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE) + RemoveSchemaPubExceptForRel(RelationGetRelid(rel), oldNspOid, + nspOid); + table_close(classRel, RowExclusiveLock); } @@ -21078,6 +21090,7 @@ ATExecAttachPartition(List **wqueue, Relation rel, PartitionCmd *cmd, if (exceptpuboids != NIL) { bool first = true; + bool has_alltables_pub = false; StringInfoData pubnames; initStringInfo(&pubnames); @@ -21091,17 +21104,22 @@ ATExecAttachPartition(List **wqueue, Relation rel, PartitionCmd *cmd, else appendStringInfo(&pubnames, _(", \"%s\""), pubname); first = false; + + if (GetPublication(pubid)->alltables) + has_alltables_pub = true; } ereport(ERROR, errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), - errmsg_plural("cannot attach table \"%s\" as partition because it is referenced in publication %s EXCEPT clause", - "cannot attach table \"%s\" as partition because it is referenced in publications %s EXCEPT clause", + errmsg_plural("cannot attach table \"%s\" as partition because it is referenced in EXCEPT clause of publication %s", + "cannot attach table \"%s\" as partition because it is referenced in EXCEPT clause of publications %s", list_length(exceptpuboids), RelationGetRelationName(attachrel), pubnames.data), errdetail("The publication EXCEPT clause cannot contain tables that are partitions."), - errhint("Change the publication's EXCEPT clause using ALTER PUBLICATION ... SET ALL TABLES.")); + errhint("%s", has_alltables_pub ? + _("Change the EXCEPT clause using ALTER PUBLICATION ... SET ALL TABLES ... EXCEPT.") : + _("Change the EXCEPT clause using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT."))); } list_free(exceptpuboids); diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y index 17035fb4d15..18826a74b77 100644 --- a/src/backend/parser/gram.y +++ b/src/backend/parser/gram.y @@ -58,6 +58,7 @@ #include "nodes/makefuncs.h" #include "nodes/nodeFuncs.h" #include "parser/parser.h" +#include "utils/builtins.h" #include "utils/datetime.h" #include "utils/xml.h" @@ -11282,7 +11283,7 @@ AlterOwnerStmt: ALTER AGGREGATE aggregate_with_argtypes OWNER TO RoleSpec * pub_obj is one of: * * TABLE table [, ...] - * TABLES IN SCHEMA schema [, ...] + * TABLES IN SCHEMA schema [EXCEPT (TABLE table [, ...] )] [, ...] * *****************************************************************************/ @@ -11342,23 +11343,26 @@ PublicationObjSpec: $$->pubtable->columns = $3; $$->pubtable->whereClause = $4; } - | TABLES IN_P SCHEMA ColId + | TABLES IN_P SCHEMA ColId opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_SCHEMA; $$->name = $4; + $$->except_tables = $5; $$->location = @4; } - | TABLES IN_P SCHEMA CURRENT_SCHEMA + | TABLES IN_P SCHEMA CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_CUR_SCHEMA; + $$->except_tables = $5; $$->location = @4; } - | ColId opt_column_list OptWhereClause + | ColId opt_column_list OptWhereClause opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $4; /* * If either a row filter or column list is specified, create * a PublicationTable object. @@ -11402,10 +11406,11 @@ PublicationObjSpec: $$->pubtable->columns = $2; $$->pubtable->whereClause = $3; } - | CURRENT_SCHEMA + | CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $2; $$->location = @1; } ; @@ -20867,6 +20872,8 @@ preprocess_pub_all_objtype_list(List *all_objects_list, List **pubobjects, /* * Process pubobjspec_list to check for errors in any of the objects and * convert PUBLICATIONOBJ_CONTINUATION into appropriate PublicationObjSpecType. + * Also flattens except_tables from TABLES IN SCHEMA nodes into the list so + * that ObjectsInPublicationToOids() sees them as top-level EXCEPT_TABLE entries. */ static void preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) @@ -20895,6 +20902,13 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLE) { + /* EXCEPT is not valid for table objects */ + if (pubobj->except_tables != NIL) + ereport(ERROR, + errcode(ERRCODE_SYNTAX_ERROR), + errmsg("EXCEPT is not allowed for TABLE publication objects"), + parser_errposition(pubobj->location)); + /* relation name or pubtable must be set for this type of object */ if (!pubobj->name && !pubobj->pubtable) ereport(ERROR, @@ -20943,6 +20957,36 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) errcode(ERRCODE_SYNTAX_ERROR), errmsg("invalid schema name"), parser_errposition(pubobj->location)); + + /* + * For TABLES_IN_SCHEMA, qualify unqualified EXCEPT table names + * with the parent schema and reject cross-schema entries at parse + * time, then flatten into the top-level list. + * + * For TABLES_IN_CUR_SCHEMA the schema name is not yet known, so + * skip both steps here; ObjectsInPublicationToOids() will + * qualify names and validate schema membership at execution time. + */ + if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLES_IN_SCHEMA) + { + foreach_ptr(PublicationObjSpec, eobj, pubobj->except_tables) + { + const char *eobj_schemaname = eobj->pubtable->relation->schemaname; + const char *eobj_relname = eobj->pubtable->relation->relname; + + if (eobj_schemaname == NULL) + eobj->pubtable->relation->schemaname = pubobj->name; + else if (strcmp(eobj_schemaname, pubobj->name) != 0) + ereport(ERROR, + errcode(ERRCODE_INVALID_OBJECT_DEFINITION), + errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", + quote_qualified_identifier(eobj_schemaname, eobj_relname), + pubobj->name), + parser_errposition(eobj->location)); + } + pubobjspec_list = list_concat(pubobjspec_list, pubobj->except_tables); + pubobj->except_tables = NIL; + } } prevobjtype = pubobj->pubobjtype; diff --git a/src/backend/replication/pgoutput/pgoutput.c b/src/backend/replication/pgoutput/pgoutput.c index 4ecfcbff7ab..3e37beddfe1 100644 --- a/src/backend/replication/pgoutput/pgoutput.c +++ b/src/backend/replication/pgoutput/pgoutput.c @@ -2280,10 +2280,36 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) } } - if (list_member_oid(pubids, pub->oid) || - list_member_oid(schemaPubids, pub->oid) || - ancestor_published) + if (list_member_oid(pubids, pub->oid) || ancestor_published) publish = true; + else if (list_member_oid(schemaPubids, pub->oid)) + { + Oid root_relid; + bool root_is_except = false; + + /* + * schemaPubids is the list of publications that include + * relid's own schema, independent of the ancestor walk + * above -- a partition can live in a different schema + * than its root. Still need to check for exclusion here, + * using the top-most ancestor since only a root + * (non-partition) table can appear in an EXCEPT clause. + */ + if (am_partition) + { + List *ancestors = get_partition_ancestors(relid); + + root_relid = llast_oid(ancestors); + list_free(ancestors); + } + else + root_relid = relid; + + GetPublicationRelEntry(pub->oid, root_relid, &root_is_except); + + if (!root_is_except) + publish = true; + } } /* diff --git a/src/backend/utils/cache/relcache.c b/src/backend/utils/cache/relcache.c index 19c4ff6e75e..b14de79d918 100644 --- a/src/backend/utils/cache/relcache.c +++ b/src/backend/utils/cache/relcache.c @@ -5847,16 +5847,32 @@ RelationBuildPublicationDesc(Relation relation, PublicationDesc *pubdesc) /* Fetch the publication membership info. */ puboids = GetRelationIncludedPublications(relid); schemaid = RelationGetNamespace(relation); - puboids = list_concat_unique_oid(puboids, GetSchemaPublications(schemaid)); if (relation->rd_rel->relispartition) { - Oid last_ancestor_relid; - - /* Add publications that the ancestors are in too. */ ancestors = get_partition_ancestors(relid); - last_ancestor_relid = llast_oid(ancestors); + /* ancestors is NIL for a partition with a pending DETACH CONCURRENTLY. */ + if (ancestors != NIL) + exceptpuboids = GetRelationExcludedPublications(llast_oid(ancestors)); + } + else + exceptpuboids = GetRelationExcludedPublications(relid); + + /* + * Subtract exceptpuboids from the schema-publication contribution so that + * a relation EXCEPT'd from a schema publication does not inherit that + * publication's pubactions. Without this filter, + * CheckCmdReplicaIdentity() would demand REPLICA IDENTITY for + * UPDATE/DELETE even on a explicitly excluded table. + */ + puboids = list_concat_unique_oid(puboids, + list_difference_oid(GetSchemaPublications(schemaid), + exceptpuboids)); + + if (relation->rd_rel->relispartition) + { + /* Add publications that the ancestors are in too. */ foreach(lc, ancestors) { Oid ancestor = lfirst_oid(lc); @@ -5865,23 +5881,9 @@ RelationBuildPublicationDesc(Relation relation, PublicationDesc *pubdesc) GetRelationIncludedPublications(ancestor)); schemaid = get_rel_namespace(ancestor); puboids = list_concat_unique_oid(puboids, - GetSchemaPublications(schemaid)); + list_difference_oid(GetSchemaPublications(schemaid), + exceptpuboids)); } - - /* - * Only the top-most ancestor can appear in the EXCEPT clause. - * Therefore, for a partition, exclusion must be evaluated at the - * top-most ancestor. - */ - exceptpuboids = GetRelationExcludedPublications(last_ancestor_relid); - } - else - { - /* - * For a regular table or a root partitioned table, check exclusion on - * table itself. - */ - exceptpuboids = GetRelationExcludedPublications(relid); } alltablespuboids = GetAllTablesPublications(); diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c index a2f09c26369..39886f85e6a 100644 --- a/src/bin/psql/describe.c +++ b/src/bin/psql/describe.c @@ -6838,6 +6838,24 @@ describePublications(const char *pattern) if (!addFooterToPublicationDesc(&buf, _("Tables from schemas:"), true, &cont)) goto error_return; + + if (pset.sversion >= 200000) + { + /* + * Get tables in the EXCEPT clause for this schema + * publication. + */ + printfPQExpBuffer(&buf, + "SELECT concat(c.relnamespace::regnamespace, '.', c.relname)\n" + "FROM pg_catalog.pg_class c\n" + " JOIN pg_catalog.pg_publication_rel pr ON c.oid = pr.prrelid\n" + "WHERE pr.prpubid = '%s'\n" + " AND pr.prexcept\n" + "ORDER BY 1", pubid); + if (!addFooterToPublicationDesc(&buf, _("Except tables:"), + true, &cont)) + goto error_return; + } } } else diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index 1cacc8c3ea2..7d8b4504194 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -1065,6 +1065,24 @@ static const SchemaQuery Query_for_trigger_of_table = { "SELECT nspname FROM pg_catalog.pg_namespace "\ " WHERE nspname LIKE '%s'" +#define Query_for_list_of_tables_in_schema \ +"SELECT n.nspname || '.' || c.relname "\ +" FROM pg_catalog.pg_class c "\ +" JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "\ +" WHERE c.relkind IN (" CppAsString2(RELKIND_RELATION) ", " \ + CppAsString2(RELKIND_PARTITIONED_TABLE) ") "\ +" AND (n.nspname || '.' || c.relname) LIKE '%s' "\ +" AND n.nspname = '%s'" + +#define Query_for_list_of_tables_in_current_schema \ +"SELECT c.relname "\ +" FROM pg_catalog.pg_class c "\ +" JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "\ +" WHERE c.relkind IN (" CppAsString2(RELKIND_RELATION) ", " \ + CppAsString2(RELKIND_PARTITIONED_TABLE) ") "\ +" AND c.relname LIKE '%s' "\ +" AND n.nspname = pg_catalog.current_schema()" + /* Use COMPLETE_WITH_QUERY_VERBATIM with these queries for GUC names: */ #define Query_for_list_of_alter_system_set_vars \ "SELECT pg_catalog.lower(name) FROM pg_catalog.pg_settings "\ @@ -3774,8 +3792,21 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); - else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && (!ends_with(prev_wd, ','))) - COMPLETE_WITH("WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE", "WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* Complete "CREATE PUBLICATION <name> [...] WITH" */ else if (Matches("CREATE", "PUBLICATION", MatchAnyN, "WITH", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/include/catalog/pg_publication.h b/src/include/catalog/pg_publication.h index 89b4bb14f62..67410ae6f5b 100644 --- a/src/include/catalog/pg_publication.h +++ b/src/include/catalog/pg_publication.h @@ -192,6 +192,7 @@ extern List *GetPubPartitionOptionRelations(List *result, Oid relid); extern Oid GetTopMostAncestorInPublication(Oid puboid, List *ancestors, int *ancestor_level); +extern bool GetPublicationRelEntry(Oid pubid, Oid relid, bool *is_except); extern bool is_publishable_relation(Relation rel); extern bool is_schema_publication(Oid pubid); diff --git a/src/include/commands/publicationcmds.h b/src/include/commands/publicationcmds.h index 4cf45c17cc5..fb1703aa675 100644 --- a/src/include/commands/publicationcmds.h +++ b/src/include/commands/publicationcmds.h @@ -27,6 +27,8 @@ extern void AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt); extern void RemovePublicationById(Oid pubid); extern void RemovePublicationRelById(Oid proid); extern void RemovePublicationSchemaById(Oid psoid); +extern void RemoveSchemaPubExceptForRel(Oid relid, Oid oldNspOid, + Oid newNspOid); extern ObjectAddress AlterPublicationOwner(const char *name, Oid newOwnerId); extern void AlterPublicationOwner_oid(Oid pubid, Oid newOwnerId); diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h index 5c8f9a07b62..0cccb4393c2 100644 --- a/src/include/nodes/parsenodes.h +++ b/src/include/nodes/parsenodes.h @@ -4530,6 +4530,8 @@ typedef struct PublicationObjSpec PublicationObjSpecType pubobjtype; /* type of this publication object */ char *name; PublicationTable *pubtable; + List *except_tables; /* tables specified in the EXCEPT clause (for + * TABLES IN SCHEMA) */ ParseLoc location; /* token location, or -1 if unknown */ } PublicationObjSpec; diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 9c6386d518a..e51ea53466f 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -279,6 +279,12 @@ CREATE PUBLICATION testpub_foralltables_excepttable2 FOR ALL TABLES EXCEPT (test ERROR: syntax error at or near "testpub_tbl1" LINE 1: ..._foralltables_excepttable2 FOR ALL TABLES EXCEPT (testpub_tb... ^ +-- fail - EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testpub_tbl3); +ERROR: EXCEPT is not allowed for TABLE publication objects +LINE 2: FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testp... + ^ --------------------------------------------- -- SET ALL TABLES/SEQUENCES --------------------------------------------- @@ -473,13 +479,161 @@ CREATE TABLE tab_main (a int) PARTITION BY RANGE(a); -- Attaching a partition is not allowed if the partitioned table appears in a -- publication's EXCEPT clause. ALTER TABLE tab_main ATTACH PARTITION testpub_root FOR VALUES FROM (0) TO (200); -ERROR: cannot attach table "testpub_root" as partition because it is referenced in publication "testpub8" EXCEPT clause +ERROR: cannot attach table "testpub_root" as partition because it is referenced in EXCEPT clause of publication "testpub8" DETAIL: The publication EXCEPT clause cannot contain tables that are partitions. -HINT: Change the publication's EXCEPT clause using ALTER PUBLICATION ... SET ALL TABLES. +HINT: Change the EXCEPT clause using ALTER PUBLICATION ... SET ALL TABLES ... EXCEPT. RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Create same-named tables in public to verify unqualified EXCEPT entries +-- are qualified with the named schema, not public +CREATE TABLE testpub_nopk (foo int, bar int); +CREATE TABLE testpub_tbl_s1 (a int primary key, b text); +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + Publication testpub_schema_except1 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- Exclude multiple tables using unqualified names; same-named tables exist in +-- public to confirm unqualified names resolve to pub_test, not public +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + Publication testpub_schema_except2 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_nopk" + "pub_test.testpub_tbl_s1" + +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testp... + ^ +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); +ERROR: table "pub_test.testpub_tbl_s1" in EXCEPT clause does not belong to schema "public" +LINE 2: ...R TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.t... + ^ +-- Multiple schemas each with their own EXCEPT clause +CREATE PUBLICATION testpub_schema_except_multi + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_schema_except_multi + Publication testpub_schema_except_multi + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- ALTER TABLE ... SET SCHEMA on a table excluded by a schema publication: +-- the schema-scoped exclusion is no longer meaningful once the table moves +-- out of its schema, so the exclusion is auto-removed. +CREATE PUBLICATION testpub_schema_except_setsch + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_schema_except_setsch + Publication testpub_schema_except_setsch + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s2" + +ALTER TABLE pub_test.testpub_tbl_s2 SET SCHEMA public; +\dRp+ testpub_schema_except_setsch + Publication testpub_schema_except_setsch + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + +DROP PUBLICATION testpub_schema_except_setsch; +-- Restore for further tests +ALTER TABLE public.testpub_tbl_s2 SET SCHEMA pub_test; +-- fail: table appears in both the explicit table list and the EXCEPT clause +CREATE PUBLICATION testpub_except_conflict + FOR TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot be both published and excluded +-- fail: nonexistent table in EXCEPT clause +CREATE PUBLICATION testpub_except_norel + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- fail: partition cannot appear in EXCEPT clause; only root tables are allowed +CREATE TABLE pub_test.testpub_parted_s (a int) PARTITION BY LIST (a); +CREATE TABLE pub_test.testpub_part_s PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (1); +CREATE PUBLICATION testpub_except_partition + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); +ERROR: cannot specify relation "pub_test.testpub_part_s" in the publication EXCEPT clause +DETAIL: This operation is not supported for individual partitions. +-- fail: TABLE keyword is required for the first entry in the EXCEPT clause +CREATE PUBLICATION testpub_except_nokw + FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +ERROR: syntax error at or near "testpub_nopk" +LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + ^ +-- fail: ADD TABLE for a partition is rejected when a partition ancestor +-- is currently in the publication's EXCEPT list. +CREATE PUBLICATION testpub_except_ancestor + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ALTER PUBLICATION testpub_except_ancestor ADD TABLE pub_test.testpub_part_s; +ERROR: cannot add partition "pub_test.testpub_part_s" to publication "testpub_except_ancestor" +DETAIL: Partition root "pub_test.testpub_parted_s" is named in the publication's EXCEPT clause for schema "pub_test". +HINT: Change the EXCEPT clause using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT. +DROP PUBLICATION testpub_except_ancestor; +-- fail: same contradiction (explicit partition + EXCEPT-ed ancestor), but +-- given in a single statement instead of two separate ones +CREATE PUBLICATION testpub_except_ancestor_same_create + FOR TABLE pub_test.testpub_part_s, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ERROR: partition "pub_test.testpub_part_s" cannot be both published and excluded +DETAIL: Partition root "pub_test.testpub_parted_s" is named in the publication's EXCEPT clause for schema "pub_test". +-- fail: same contradiction as above, but the partition lives in a different +-- schema (public) than its EXCEPT-ed root (pub_test) +CREATE TABLE public.testpub_part_s2 PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (2); +CREATE PUBLICATION testpub_except_ancestor_cross_schema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s), + TABLE public.testpub_part_s2; +ERROR: partition "public.testpub_part_s2" cannot be both published and excluded +DETAIL: Partition root "pub_test.testpub_parted_s" is named in the publication's EXCEPT clause for schema "pub_test". +DROP TABLE public.testpub_part_s2; +-- Cleanup +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP TABLE pub_test.testpub_parted_s CASCADE; +DROP TABLE testpub_nopk, testpub_tbl_s1; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +--------------------------------------------- +-- Tests for publications with SEQUENCES +--------------------------------------------- CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; -- FOR ALL SEQUENCES @@ -1970,6 +2124,27 @@ ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b); ERROR: column specification not allowed for schema LINE 1: ...TION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b)... ^ +-- EXCEPT clause with CURRENT_SCHEMA: cross-schema entry must be rejected +SET search_path = pub_test1; +-- qualified name from wrong schema -> error +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.tbl1); +ERROR: table "pub_test2.tbl1" in EXCEPT clause does not belong to schema "pub_test1" +-- unqualified name implicitly qualified with current schema (pub_test1.tbl) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl); +RESET client_min_messages; +\dRp+ testpub_cursch_except + Publication testpub_cursch_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test1" +Except tables: + "pub_test1.tbl" + +DROP PUBLICATION testpub_cursch_except; +RESET search_path; -- cleanup pub_test1 schema for invalidation tests ALTER PUBLICATION testpub2_forschema DROP TABLES IN SCHEMA pub_test1; DROP PUBLICATION testpub3_forschema, testpub4_forschema, testpub5_forschema, testpub6_forschema, testpub_fortable; @@ -2321,6 +2496,7 @@ DROP ROLE regress_publication_user_dummy; -- Test pg_get_publication_tables(text[], oid) function CREATE SCHEMA gpt_test_sch; CREATE TABLE gpt_test_sch.tbl_sch (id int); +CREATE TABLE gpt_test_sch.tbl_sch2 (id int); CREATE TABLE tbl_normal (id int); CREATE TABLE tbl_parent (id1 int, id2 int, id3 int) PARTITION BY RANGE (id1); CREATE TABLE tbl_part1 PARTITION OF tbl_parent FOR VALUES FROM (1) TO (10); @@ -2331,6 +2507,7 @@ CREATE PUBLICATION pub_all_no_viaroot FOR ALL TABLES WITH (publish_via_partition CREATE PUBLICATION pub_all_except FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = true); CREATE PUBLICATION pub_all_except_no_viaroot FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_schema FOR TABLES IN SCHEMA gpt_test_sch; +CREATE PUBLICATION pub_schema_except FOR TABLES IN SCHEMA gpt_test_sch EXCEPT (TABLE gpt_test_sch.tbl_sch); CREATE PUBLICATION pub_normal FOR TABLE tbl_normal WHERE (id < 10); CREATE PUBLICATION pub_part_leaf FOR TABLE tbl_part1 WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_part_parent FOR TABLE tbl_parent (id1, id2) WHERE (id1 = 10) WITH (publish_via_partition_root = true); @@ -2482,6 +2659,44 @@ SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_part1'); -- no r ---------+---------+-------+------ (0 rows) +-- test for EXCEPT clause with schema publication +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch'); -- no result (excluded) + pubname | relname | attrs | qual +---------+---------+-------+------ +(0 rows) + +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch2'); -- one row (included via schema) + pubname | relname | attrs | qual +-------------------+----------+-------+------ + pub_schema_except | tbl_sch2 | 1 | +(1 row) + +-- test for EXCEPT clause with schema publication, where the excluded root's +-- partition lives in a different schema that is separately, fully included +-- (no EXCEPT) in the same publication. The root's exclusion must cascade to +-- the partition regardless of the partition's own schema membership. +CREATE SCHEMA gpt_cross_sch1; +CREATE SCHEMA gpt_cross_sch2; +CREATE TABLE gpt_cross_sch1.croot (id int) PARTITION BY RANGE (id); +CREATE TABLE gpt_cross_sch2.cpart1 PARTITION OF gpt_cross_sch1.croot FOR VALUES FROM (1) TO (10); +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION pub_cross_schema_except FOR TABLES IN SCHEMA gpt_cross_sch1 EXCEPT (TABLE gpt_cross_sch1.croot), TABLES IN SCHEMA gpt_cross_sch2; +RESET client_min_messages; +SELECT * FROM test_gpt(ARRAY['pub_cross_schema_except'], 'gpt_cross_sch1.croot'); -- no result (excluded) + pubname | relname | attrs | qual +---------+---------+-------+------ +(0 rows) + +-- no result (excluded via cascading root exclusion, even though cpart1's own +-- schema gpt_cross_sch2 is separately, fully included with no EXCEPT) +SELECT * FROM test_gpt(ARRAY['pub_cross_schema_except'], 'gpt_cross_sch2.cpart1'); + pubname | relname | attrs | qual +---------+---------+-------+------ +(0 rows) + +DROP PUBLICATION pub_cross_schema_except; +DROP TABLE gpt_cross_sch2.cpart1, gpt_cross_sch1.croot; +DROP SCHEMA gpt_cross_sch1, gpt_cross_sch2; -- two rows with different row filter SELECT * FROM test_gpt(ARRAY['pub_all', 'pub_normal'], 'tbl_normal'); pubname | relname | attrs | qual @@ -2534,6 +2749,7 @@ DROP PUBLICATION pub_all_no_viaroot; DROP PUBLICATION pub_all_except; DROP PUBLICATION pub_all_except_no_viaroot; DROP PUBLICATION pub_schema; +DROP PUBLICATION pub_schema_except; DROP PUBLICATION pub_normal; DROP PUBLICATION pub_part_leaf; DROP PUBLICATION pub_part_parent; @@ -2542,7 +2758,9 @@ DROP PUBLICATION pub_part_parent_child; DROP VIEW gpt_test_view; DROP TABLE tbl_normal, tbl_parent, tbl_part1; DROP SCHEMA gpt_test_sch CASCADE; -NOTICE: drop cascades to table gpt_test_sch.tbl_sch +NOTICE: drop cascades to 2 other objects +DETAIL: drop cascades to table gpt_test_sch.tbl_sch +drop cascades to table gpt_test_sch.tbl_sch2 -- stage objects for pg_dump tests CREATE SCHEMA pubme CREATE TABLE t0 (c int, d int) CREATE TABLE t1 (c int); CREATE SCHEMA pubme2 CREATE TABLE t0 (c int, d int); diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index fac54b02e27..4a86d699e84 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -125,6 +125,9 @@ CREATE PUBLICATION testpub_foralltables_excepttable1 FOR ALL TABLES EXCEPT (TABL \d testpub_tbl1 -- fail - first table in the EXCEPT list should use TABLE keyword CREATE PUBLICATION testpub_foralltables_excepttable2 FOR ALL TABLES EXCEPT (testpub_tbl1, testpub_tbl2); +-- fail - EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testpub_tbl3); --------------------------------------------- -- SET ALL TABLES/SEQUENCES @@ -222,7 +225,104 @@ RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Create same-named tables in public to verify unqualified EXCEPT entries +-- are qualified with the named schema, not public +CREATE TABLE testpub_nopk (foo int, bar int); +CREATE TABLE testpub_tbl_s1 (a int primary key, b text); + +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + +-- Exclude multiple tables using unqualified names; same-named tables exist in +-- public to confirm unqualified names resolve to pub_test, not public +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); + +-- Multiple schemas each with their own EXCEPT clause +CREATE PUBLICATION testpub_schema_except_multi + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_schema_except_multi + +-- ALTER TABLE ... SET SCHEMA on a table excluded by a schema publication: +-- the schema-scoped exclusion is no longer meaningful once the table moves +-- out of its schema, so the exclusion is auto-removed. +CREATE PUBLICATION testpub_schema_except_setsch + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_schema_except_setsch +ALTER TABLE pub_test.testpub_tbl_s2 SET SCHEMA public; +\dRp+ testpub_schema_except_setsch +DROP PUBLICATION testpub_schema_except_setsch; +-- Restore for further tests +ALTER TABLE public.testpub_tbl_s2 SET SCHEMA pub_test; + +-- fail: table appears in both the explicit table list and the EXCEPT clause +CREATE PUBLICATION testpub_except_conflict + FOR TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: nonexistent table in EXCEPT clause +CREATE PUBLICATION testpub_except_norel + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- fail: partition cannot appear in EXCEPT clause; only root tables are allowed +CREATE TABLE pub_test.testpub_parted_s (a int) PARTITION BY LIST (a); +CREATE TABLE pub_test.testpub_part_s PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (1); +CREATE PUBLICATION testpub_except_partition + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); + +-- fail: TABLE keyword is required for the first entry in the EXCEPT clause +CREATE PUBLICATION testpub_except_nokw + FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + +-- fail: ADD TABLE for a partition is rejected when a partition ancestor +-- is currently in the publication's EXCEPT list. +CREATE PUBLICATION testpub_except_ancestor + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ALTER PUBLICATION testpub_except_ancestor ADD TABLE pub_test.testpub_part_s; +DROP PUBLICATION testpub_except_ancestor; + +-- fail: same contradiction (explicit partition + EXCEPT-ed ancestor), but +-- given in a single statement instead of two separate ones +CREATE PUBLICATION testpub_except_ancestor_same_create + FOR TABLE pub_test.testpub_part_s, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); + +-- fail: same contradiction as above, but the partition lives in a different +-- schema (public) than its EXCEPT-ed root (pub_test) +CREATE TABLE public.testpub_part_s2 PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (2); +CREATE PUBLICATION testpub_except_ancestor_cross_schema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s), + TABLE public.testpub_part_s2; +DROP TABLE public.testpub_part_s2; + +-- Cleanup +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP TABLE pub_test.testpub_parted_s CASCADE; +DROP TABLE testpub_nopk, testpub_tbl_s1; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; + +--------------------------------------------- +-- Tests for publications with SEQUENCES +--------------------------------------------- CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; @@ -1194,6 +1294,18 @@ ALTER PUBLICATION testpub1_forschema SET TABLES IN SCHEMA pub_test1, pub_test1; ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo (a, b); ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b); +-- EXCEPT clause with CURRENT_SCHEMA: cross-schema entry must be rejected +SET search_path = pub_test1; +-- qualified name from wrong schema -> error +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.tbl1); +-- unqualified name implicitly qualified with current schema (pub_test1.tbl) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl); +RESET client_min_messages; +\dRp+ testpub_cursch_except +DROP PUBLICATION testpub_cursch_except; +RESET search_path; + -- cleanup pub_test1 schema for invalidation tests ALTER PUBLICATION testpub2_forschema DROP TABLES IN SCHEMA pub_test1; DROP PUBLICATION testpub3_forschema, testpub4_forschema, testpub5_forschema, testpub6_forschema, testpub_fortable; @@ -1448,6 +1560,7 @@ DROP ROLE regress_publication_user_dummy; -- Test pg_get_publication_tables(text[], oid) function CREATE SCHEMA gpt_test_sch; CREATE TABLE gpt_test_sch.tbl_sch (id int); +CREATE TABLE gpt_test_sch.tbl_sch2 (id int); CREATE TABLE tbl_normal (id int); CREATE TABLE tbl_parent (id1 int, id2 int, id3 int) PARTITION BY RANGE (id1); CREATE TABLE tbl_part1 PARTITION OF tbl_parent FOR VALUES FROM (1) TO (10); @@ -1459,6 +1572,7 @@ CREATE PUBLICATION pub_all_no_viaroot FOR ALL TABLES WITH (publish_via_partition CREATE PUBLICATION pub_all_except FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = true); CREATE PUBLICATION pub_all_except_no_viaroot FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_schema FOR TABLES IN SCHEMA gpt_test_sch; +CREATE PUBLICATION pub_schema_except FOR TABLES IN SCHEMA gpt_test_sch EXCEPT (TABLE gpt_test_sch.tbl_sch); CREATE PUBLICATION pub_normal FOR TABLE tbl_normal WHERE (id < 10); CREATE PUBLICATION pub_part_leaf FOR TABLE tbl_part1 WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_part_parent FOR TABLE tbl_parent (id1, id2) WHERE (id1 = 10) WITH (publish_via_partition_root = true); @@ -1515,6 +1629,32 @@ SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'gpt_test_sch.tbl_sch SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_parent'); -- no result (excluded) SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_part1'); -- no result +-- test for EXCEPT clause with schema publication +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch'); -- no result (excluded) +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch2'); -- one row (included via schema) + +-- test for EXCEPT clause with schema publication, where the excluded root's +-- partition lives in a different schema that is separately, fully included +-- (no EXCEPT) in the same publication. The root's exclusion must cascade to +-- the partition regardless of the partition's own schema membership. +CREATE SCHEMA gpt_cross_sch1; +CREATE SCHEMA gpt_cross_sch2; +CREATE TABLE gpt_cross_sch1.croot (id int) PARTITION BY RANGE (id); +CREATE TABLE gpt_cross_sch2.cpart1 PARTITION OF gpt_cross_sch1.croot FOR VALUES FROM (1) TO (10); + +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION pub_cross_schema_except FOR TABLES IN SCHEMA gpt_cross_sch1 EXCEPT (TABLE gpt_cross_sch1.croot), TABLES IN SCHEMA gpt_cross_sch2; +RESET client_min_messages; + +SELECT * FROM test_gpt(ARRAY['pub_cross_schema_except'], 'gpt_cross_sch1.croot'); -- no result (excluded) +-- no result (excluded via cascading root exclusion, even though cpart1's own +-- schema gpt_cross_sch2 is separately, fully included with no EXCEPT) +SELECT * FROM test_gpt(ARRAY['pub_cross_schema_except'], 'gpt_cross_sch2.cpart1'); + +DROP PUBLICATION pub_cross_schema_except; +DROP TABLE gpt_cross_sch2.cpart1, gpt_cross_sch1.croot; +DROP SCHEMA gpt_cross_sch1, gpt_cross_sch2; + -- two rows with different row filter SELECT * FROM test_gpt(ARRAY['pub_all', 'pub_normal'], 'tbl_normal'); @@ -1543,6 +1683,7 @@ DROP PUBLICATION pub_all_no_viaroot; DROP PUBLICATION pub_all_except; DROP PUBLICATION pub_all_except_no_viaroot; DROP PUBLICATION pub_schema; +DROP PUBLICATION pub_schema_except; DROP PUBLICATION pub_normal; DROP PUBLICATION pub_part_leaf; DROP PUBLICATION pub_part_parent; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 8c58d282eee..c4e4efafec8 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -24,14 +24,17 @@ my $result; sub test_except_root_partition { - my ($pubviaroot) = @_; + my ($pubviaroot, $pubsql) = @_; + $pubsql //= + "CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1)"; + $pubsql .= " WITH (publish_via_partition_root = $pubviaroot)"; # If the root partitioned table is in the EXCEPT clause, all its # partitions are excluded from publication, regardless of the # publish_via_partition_root setting. $node_publisher->safe_psql( 'postgres', qq( - CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1) WITH (publish_via_partition_root = $pubviaroot); + $pubsql; INSERT INTO root1 VALUES (1), (101); )); $node_subscriber->safe_psql('postgres', @@ -223,6 +226,206 @@ $node_subscriber->safe_psql( test_except_root_partition('false'); test_except_root_partition('true'); +# Same validation using TABLES IN SCHEMA instead of FOR ALL TABLES. +my $schema_pub = + "CREATE PUBLICATION tap_pub_part FOR TABLES IN SCHEMA public EXCEPT (TABLE public.root1)"; +test_except_root_partition('false', $schema_pub); +test_except_root_partition('true', $schema_pub); + +# ============================================ +# EXCEPT test cases for TABLES IN SCHEMA +# ============================================ + +# Create a dedicated schema with two tables: one to be published and one to be +# excluded. Also create inherited tables to verify ONLY semantics. +$node_publisher->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_published AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.tab_excluded AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.parent (a int); + CREATE TABLE sch1.child (b int) INHERITS (sch1.parent); +)); + +$node_subscriber->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_published (a int); + CREATE TABLE sch1.tab_excluded (a int); + CREATE TABLE sch1.parent (a int); + CREATE TABLE sch1.child (b int) INHERITS (sch1.parent); +)); + +# Basic test: initial sync respects EXCEPT. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_excluded)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: initial sync copies included table'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: initial sync skips excluded table'); + +# DML: only the included table should be replicated. +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (6); + INSERT INTO sch1.tab_excluded VALUES (6); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(6), + 'TABLES IN SCHEMA EXCEPT: DML on included table is replicated'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: DML on excluded table is not replicated'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Inherited tables: excluding the parent (without ONLY) also excludes the child. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.parent)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.child VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.child"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: excluding parent (without ONLY) also excludes child' +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Test that EXCEPT (TABLE ONLY parent) excludes only the parent itself, not its +# child. Truncate child first so rows from the previous test are not copied by +# the initial table sync of the next subscription. +$node_publisher->safe_psql('postgres', 'TRUNCATE sch1.child'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE sch1.child'); +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE ONLY sch1.parent)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.child VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.child"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: ONLY parent in EXCEPT does not exclude child'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Cleanup schema tables before the multi-publication section. +$node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); +$node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); + +# ============================================ +# EXCEPT test cases for TABLES IN SCHEMA with a cross-schema partition +# ============================================ + +# A partition can live in a different schema than its partitioned root. If +# the root is excluded via EXCEPT under its own schema's clause, the +# exclusion must cascade to all its partitions, even when the partition's +# own schema is separately, fully included (no EXCEPT) in the same +# publication. +$node_publisher->safe_psql( + 'postgres', qq( + CREATE SCHEMA csch1; + CREATE SCHEMA csch2; + CREATE TABLE csch1.croot(a int) PARTITION BY RANGE(a); + CREATE TABLE csch2.cpart1 PARTITION OF csch1.croot FOR VALUES FROM (0) TO (100); + INSERT INTO csch1.croot VALUES (generate_series(1,5)); +)); + +$node_subscriber->safe_psql( + 'postgres', qq( + CREATE SCHEMA csch1; + CREATE SCHEMA csch2; + CREATE TABLE csch1.croot(a int); + CREATE TABLE csch2.cpart1(a int); +)); + +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION cross_sch_pub FOR TABLES IN SCHEMA csch1 EXCEPT (TABLE csch1.croot), TABLES IN SCHEMA csch2 WITH (publish_via_partition_root = false)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION cross_sch_sub CONNECTION '$publisher_connstr' PUBLICATION cross_sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'cross_sch_sub'); + +# Baseline: the root itself, pre-populated with rows before the subscription +# was created, is excluded by its own schema's EXCEPT clause -- initial sync +# must not have copied it. +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM csch1.croot"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: cross-schema partition root is excluded by initial sync' +); + +# Regression case: the partition's own schema (csch2) is separately, fully +# included with no EXCEPT, but the root's exclusion must still cascade to it +# -- initial sync must not have copied the pre-existing rows routed into this +# partition via the root. +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM csch2.cpart1"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: cross-schema partition is excluded by initial sync via cascading root exclusion' +); + +# Insert distinct, identifiable data directly into the partition and verify +# it is not replicated either. +$node_publisher->safe_psql('postgres', + "INSERT INTO csch2.cpart1 VALUES (generate_series(1,5))"); +$node_publisher->wait_for_catchup('cross_sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM csch1.croot"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: cross-schema partition root remains excluded after DML' +); +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM csch2.cpart1"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: cross-schema partition remains excluded after DML via cascading root exclusion' +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION cross_sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION cross_sch_pub'); +$node_publisher->safe_psql('postgres', 'DROP SCHEMA csch1, csch2 CASCADE'); +$node_subscriber->safe_psql('postgres', 'DROP SCHEMA csch1, csch2 CASCADE'); + # ============================================ # Test when a subscription is subscribing to multiple publications # ============================================ @@ -254,6 +457,7 @@ $node_publisher->safe_psql( DROP PUBLICATION tap_pub2; TRUNCATE tab1; )); +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_subscriber->safe_psql('postgres', qq(TRUNCATE tab1)); # OK when a table is excluded by pub1 EXCEPT clause, but it is included by pub2 -- 2.50.1 (Apple Git-155)
v22-0002-Restrict-conflicting-EXCEPT-lists-in-multi-schem.patch (application/octet-stream, 14.7K) download From a0e5756206d264f7f675755cbd25065cffce1f7a Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Wed, 15 Jul 2026 21:18:51 +0530 Subject: [PATCH v22 2/5] Restrict conflicting EXCEPT lists in multi-schema publications Add ProcessSchemaExceptTables(), which errors if the same schema is mentioned more than once with EXCEPT, or both with and without EXCEPT. It also checks that a schema's EXCEPT clause only lists tables from that same schema. --- src/backend/commands/publicationcmds.c | 117 +++++++++++++++------- src/backend/parser/gram.y | 37 +------ src/test/regress/expected/publication.out | 38 +++++++ src/test/regress/sql/publication.sql | 31 ++++++ 4 files changed, 155 insertions(+), 68 deletions(-) diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index ba35e48b306..780374ef7f4 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -73,6 +73,10 @@ static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); static char defGetGeneratedColsOption(DefElem *def); static void CheckExceptNotInTableList(List *except_rels, List *explicitrelids); +static void ProcessSchemaExceptTables(Oid schemaid, List *except_tables, + ParseState *pstate, List **schemas, + List **schemas_with_except, + List **except_pubtables); static void @@ -177,6 +181,74 @@ parse_publication_options(ParseState *pstate, } } +/* + * Qualify unqualified EXCEPT table names with the given schema (rejecting + * any explicitly qualified with a different schema), and append them to + * *except_pubtables. + * + * Also rejects a schema being mentioned more than once with an EXCEPT + * clause, even if the EXCEPT lists are identical — much like + * OpenTableList() rejects "FOR TABLE t1(a), t1(a)" despite the column + * lists matching. A schema can still be mentioned multiple times, just + * not more than once with EXCEPT. + * + * schemaid: OID of the schema for this TABLES IN SCHEMA mention. + * except_tables: the EXCEPT list (or NIL) attached to this mention. + * *schemas: accumulates all schema OIDs seen so far in this statement. + * *schemas_with_except: tracks which schema OIDs have already been seen + * with an EXCEPT clause in this statement. + * *except_pubtables: accumulates the (now schema-qualified) EXCEPT table + * entries across the whole statement. + */ +static void +ProcessSchemaExceptTables(Oid schemaid, List *except_tables, + ParseState *pstate, List **schemas, + List **schemas_with_except, List **except_pubtables) +{ + char *schema_name = get_namespace_name(schemaid); + bool schema_has_except = (except_tables != NIL); + + /* + * A repeating schema is only a problem if this mention has EXCEPT, or an + * earlier mention of the same schema did. + */ + if (list_member_oid(*schemas, schemaid)) + { + if (schema_has_except || + list_member_oid(*schemas_with_except, schemaid)) + ereport(ERROR, + errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("conflicting or redundant EXCEPT lists for schema \"%s\"", + schema_name)); + } + + if (schema_has_except) + *schemas_with_except = lappend_oid(*schemas_with_except, schemaid); + + /* Filter out duplicates if the user specifies "sch1, sch1" */ + *schemas = list_append_unique_oid(*schemas, schemaid); + + if (!schema_has_except) + return; + + foreach_ptr(PublicationObjSpec, eobj, except_tables) + { + RangeVar *relation = eobj->pubtable->relation; + + if (relation->schemaname == NULL) + relation->schemaname = schema_name; + else if (strcmp(relation->schemaname, schema_name) != 0) + ereport(ERROR, + errcode(ERRCODE_INVALID_OBJECT_DEFINITION), + errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", + quote_qualified_identifier(relation->schemaname, relation->relname), + schema_name), + parser_errposition(pstate, eobj->location)); + + *except_pubtables = lappend(*except_pubtables, eobj->pubtable); + } +} + /* * Convert the PublicationObjSpecType list into schema oid list and * PublicationTable list. @@ -187,6 +259,7 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, { ListCell *cell; PublicationObjSpec *pubobj; + List *schemas_with_except = NIL; if (!pubobjspec_list) return; @@ -211,8 +284,10 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, case PUBLICATIONOBJ_TABLES_IN_SCHEMA: schemaid = get_namespace_oid(pubobj->name, false); - /* Filter out duplicates if user specifies "sch1, sch1" */ - *schemas = list_append_unique_oid(*schemas, schemaid); + ProcessSchemaExceptTables(schemaid, pubobj->except_tables, + pstate, schemas, + &schemas_with_except, + except_pubtables); break; case PUBLICATIONOBJ_TABLES_IN_CUR_SCHEMA: search_path = fetch_search_path(false); @@ -224,40 +299,10 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, schemaid = linitial_oid(search_path); list_free(search_path); - /* Filter out duplicates if user specifies "sch1, sch1" */ - *schemas = list_append_unique_oid(*schemas, schemaid); - - /* - * Qualify unqualified EXCEPT table names with the resolved - * current schema and reject any explicitly cross-schema - * entries. This mirrors the parse-time handling done for - * TABLES_IN_SCHEMA in preprocess_pubobj_list(), deferred here - * because CURRENT_SCHEMA is not known until execution time. - */ - if (pubobj->except_tables != NIL) - { - char *cur_schema_name = get_namespace_name(schemaid); - - foreach_ptr(PublicationObjSpec, eobj, pubobj->except_tables) - { - const char *eobj_schemaname = - eobj->pubtable->relation->schemaname; - const char *eobj_relname = - eobj->pubtable->relation->relname; - - if (eobj_schemaname == NULL) - eobj->pubtable->relation->schemaname = cur_schema_name; - else if (strcmp(eobj_schemaname, cur_schema_name) != 0) - ereport(ERROR, - errcode(ERRCODE_INVALID_OBJECT_DEFINITION), - errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", - quote_qualified_identifier(eobj_schemaname, eobj_relname), - cur_schema_name)); - - *except_pubtables = lappend(*except_pubtables, - eobj->pubtable); - } - } + ProcessSchemaExceptTables(schemaid, pubobj->except_tables, + pstate, schemas, + &schemas_with_except, + except_pubtables); break; default: /* shouldn't happen */ diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y index 18826a74b77..14520a5ccab 100644 --- a/src/backend/parser/gram.y +++ b/src/backend/parser/gram.y @@ -20872,8 +20872,11 @@ preprocess_pub_all_objtype_list(List *all_objects_list, List **pubobjects, /* * Process pubobjspec_list to check for errors in any of the objects and * convert PUBLICATIONOBJ_CONTINUATION into appropriate PublicationObjSpecType. - * Also flattens except_tables from TABLES IN SCHEMA nodes into the list so - * that ObjectsInPublicationToOids() sees them as top-level EXCEPT_TABLE entries. + * + * The except_tables attached to TABLES IN SCHEMA nodes are left in place here; + * ObjectsInPublicationToOids() qualifies their names, validates schema + * membership, and merges the qualified tables into its except_pubtables + * output list once the schema OID is known. */ static void preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) @@ -20957,36 +20960,6 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) errcode(ERRCODE_SYNTAX_ERROR), errmsg("invalid schema name"), parser_errposition(pubobj->location)); - - /* - * For TABLES_IN_SCHEMA, qualify unqualified EXCEPT table names - * with the parent schema and reject cross-schema entries at parse - * time, then flatten into the top-level list. - * - * For TABLES_IN_CUR_SCHEMA the schema name is not yet known, so - * skip both steps here; ObjectsInPublicationToOids() will - * qualify names and validate schema membership at execution time. - */ - if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLES_IN_SCHEMA) - { - foreach_ptr(PublicationObjSpec, eobj, pubobj->except_tables) - { - const char *eobj_schemaname = eobj->pubtable->relation->schemaname; - const char *eobj_relname = eobj->pubtable->relation->relname; - - if (eobj_schemaname == NULL) - eobj->pubtable->relation->schemaname = pubobj->name; - else if (strcmp(eobj_schemaname, pubobj->name) != 0) - ereport(ERROR, - errcode(ERRCODE_INVALID_OBJECT_DEFINITION), - errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", - quote_qualified_identifier(eobj_schemaname, eobj_relname), - pubobj->name), - parser_errposition(eobj->location)); - } - pubobjspec_list = list_concat(pubobjspec_list, pubobj->except_tables); - pubobj->except_tables = NIL; - } } prevobjtype = pubobj->pubobjtype; diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index e51ea53466f..3a2db8642cc 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -552,6 +552,17 @@ Except tables: "pub_test.testpub_tbl_s1" "public.testpub_tbl1" +-- fail: same schema repeated with same EXCEPT lists +CREATE PUBLICATION testpub_schema_except_conflict + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: conflicting or redundant EXCEPT lists for schema "pub_test" +-- fail: same schema repeated with conflicting or no EXCEPT lists +CREATE PUBLICATION testpub_schema_except_conflict2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2), + pub_test; +ERROR: conflicting or redundant EXCEPT lists for schema "pub_test" -- ALTER TABLE ... SET SCHEMA on a table excluded by a schema publication: -- the schema-scoped exclusion is no longer meaningful once the table moves -- out of its schema, so the exclusion is auto-removed. @@ -2129,6 +2140,8 @@ SET search_path = pub_test1; -- qualified name from wrong schema -> error CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.tbl1); ERROR: table "pub_test2.tbl1" in EXCEPT clause does not belong to schema "pub_test1" +LINE 1: ...FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.... + ^ -- unqualified name implicitly qualified with current schema (pub_test1.tbl) SET client_min_messages = 'ERROR'; CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl); @@ -2144,6 +2157,31 @@ Except tables: "pub_test1.tbl" DROP PUBLICATION testpub_cursch_except; +-- succeeds: CURRENT_SCHEMA and pub_test1 (same schema) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_named_same + FOR TABLES IN SCHEMA CURRENT_SCHEMA, pub_test1; +RESET client_min_messages; +\dRp+ testpub_cursch_named_same + Publication testpub_cursch_named_same + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test1" + +DROP PUBLICATION testpub_cursch_named_same; +-- fail: CURRENT_SCHEMA and pub_test1 (same schema) have +-- conflicting EXCEPT lists +CREATE PUBLICATION testpub_cursch_named_conflict + FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl), + pub_test1 EXCEPT (TABLE tbl1); +ERROR: conflicting or redundant EXCEPT lists for schema "pub_test1" +-- fail: two CURRENT_SCHEMA mentions with conflicting EXCEPT lists +CREATE PUBLICATION testpub_cursch_cursch_conflict + FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl), + CURRENT_SCHEMA EXCEPT (TABLE tbl1); +ERROR: conflicting or redundant EXCEPT lists for schema "pub_test1" RESET search_path; -- cleanup pub_test1 schema for invalidation tests ALTER PUBLICATION testpub2_forschema DROP TABLES IN SCHEMA pub_test1; diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 4a86d699e84..4a79055c4f3 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -262,6 +262,17 @@ CREATE PUBLICATION testpub_schema_except_multi public EXCEPT (TABLE testpub_tbl1); \dRp+ testpub_schema_except_multi +-- fail: same schema repeated with same EXCEPT lists +CREATE PUBLICATION testpub_schema_except_conflict + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: same schema repeated with conflicting or no EXCEPT lists +CREATE PUBLICATION testpub_schema_except_conflict2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2), + pub_test; + -- ALTER TABLE ... SET SCHEMA on a table excluded by a schema publication: -- the schema-scoped exclusion is no longer meaningful once the table moves -- out of its schema, so the exclusion is auto-removed. @@ -1304,6 +1315,26 @@ CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXC RESET client_min_messages; \dRp+ testpub_cursch_except DROP PUBLICATION testpub_cursch_except; + +-- succeeds: CURRENT_SCHEMA and pub_test1 (same schema) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_named_same + FOR TABLES IN SCHEMA CURRENT_SCHEMA, pub_test1; +RESET client_min_messages; +\dRp+ testpub_cursch_named_same +DROP PUBLICATION testpub_cursch_named_same; + +-- fail: CURRENT_SCHEMA and pub_test1 (same schema) have +-- conflicting EXCEPT lists +CREATE PUBLICATION testpub_cursch_named_conflict + FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl), + pub_test1 EXCEPT (TABLE tbl1); + +-- fail: two CURRENT_SCHEMA mentions with conflicting EXCEPT lists +CREATE PUBLICATION testpub_cursch_cursch_conflict + FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl), + CURRENT_SCHEMA EXCEPT (TABLE tbl1); + RESET search_path; -- cleanup pub_test1 schema for invalidation tests -- 2.50.1 (Apple Git-155)
v22-0003-Add-EXCEPT-support-to-ALTER-PUBLICATION-ADD-TABL.patch (application/octet-stream, 21.8K) download From e6e97680ed539af10ede32a763c1561b4b5c2342 Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Mon, 20 Jul 2026 13:24:33 +0530 Subject: [PATCH v22 3/5] Add EXCEPT support to ALTER PUBLICATION ADD TABLES IN SCHEMA Extend the EXCEPT clause support to allow tables to be excluded when adding a schema to a publication via ALTER PUBLICATION ... ADD. Syntax: ALTER PUBLICATION pub ADD TABLES IN SCHEMA s EXCEPT (TABLE s.t1); Since pg_dump uses ALTER PUBLICATION ... ADD, support for it is included in this patch. --- src/backend/catalog/pg_publication.c | 19 +++-- src/backend/commands/publicationcmds.c | 98 ++++++++++++++++++++++- src/bin/pg_dump/pg_dump.c | 30 ++++++- src/bin/pg_dump/t/002_pg_dump.pl | 24 ++++++ src/bin/psql/tab-complete.in.c | 17 ++++ src/test/regress/expected/publication.out | 60 +++++++++++++- src/test/regress/sql/publication.sql | 45 ++++++++++- src/test/subscription/t/037_except.pl | 32 ++++++++ 8 files changed, 311 insertions(+), 14 deletions(-) diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index 145559e9248..19f793b68d7 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -721,15 +721,18 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, * here, as CreatePublication() function invalidates all relations as part * of defining a FOR ALL TABLES publication. * - * For ALTER PUBLICATION, invalidation is needed only when adding an - * EXCEPT table to a publication already marked as ALL TABLES. For - * publications that were originally empty or defined as ALL SEQUENCES and - * are being converted to ALL TABLES, invalidation is skipped here, as - * AlterPublicationAllFlags() function invalidates all relations while - * marking the publication as ALL TABLES publication. + * For ALTER PUBLICATION, invalidation is needed when adding an EXCEPT + * table to either a FOR ALL TABLES publication (pub->alltables is true) + * or a FOR TABLES IN SCHEMA publication (is_schema_publication is true). + * The exception: when a publication is being converted to FOR ALL TABLES + * (pub->alltables is still false at this point), + * AlterPublicationAllFlags() will perform a full invalidation, so we skip + * it here. */ - inval_except_table = (alter_stmt != NULL) && pub->alltables && - (alter_stmt->for_all_tables && pri->except); + inval_except_table = (alter_stmt != NULL) && pri->except && + (pub->alltables + ? alter_stmt->for_all_tables + : is_schema_publication(pubid)); if (!pri->except || inval_except_table) { diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 780374ef7f4..2f21278ae64 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -71,6 +71,13 @@ static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok); static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); +static void AlterPublicationSchemas(AlterPublicationStmt *stmt, + HeapTuple tup, List *schemaidlist, + List *except_pubtables); +static void AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, + List *except_pubtables, + List *schemaidlist); static char defGetGeneratedColsOption(DefElem *def); static void CheckExceptNotInTableList(List *except_rels, List *explicitrelids); static void ProcessSchemaExceptTables(Oid schemaid, List *except_tables, @@ -1593,7 +1600,8 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, */ static void AlterPublicationSchemas(AlterPublicationStmt *stmt, - HeapTuple tup, List *schemaidlist) + HeapTuple tup, List *schemaidlist, + List *except_pubtables) { Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); @@ -1670,6 +1678,88 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, */ PublicationAddSchemas(pubform->oid, schemaidlist, true, stmt); } + + /* + * Increment the command counter so that is_schema_publication() in + * GetExcludedPublicationTables() can see the just-inserted schema + * rows when AlterPublicationSchemaExceptTables runs next. + */ + if (stmt->action == AP_AddObjects || stmt->action == AP_SetObjects) + CommandCounterIncrement(); + + AlterPublicationSchemaExceptTables(stmt, tup, except_pubtables, schemaidlist); +} + +/* + * Alter the EXCEPT list of a schema-level publication. + * + * Adds, removes, or replaces except-table entries in pg_publication_rel + * (rows with prexcept = true). These entries suppress publication of the + * named tables that would otherwise be covered by a FOR TABLES IN SCHEMA + * clause. + */ +static void +AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, List *except_pubtables, + List *schemaidlist) +{ + Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); + Oid pubid = pubform->oid; + + /* + * Nothing to do if no EXCEPT entries. + */ + if (!except_pubtables) + return; + + /* + * This function handles EXCEPT entries for schema-level publications + * only. For FOR ALL TABLES publications, EXCEPT entries are already + * processed by AlterPublicationTables(). + */ + if (schemaidlist == NIL && !is_schema_publication(pubid)) + return; + + /* + * Dropping a schema from a publication removes all its EXCEPT entries via + * cascade. The concept of "drop all schema tables from the publication + * EXCEPT these ones" is not supported. + */ + if (stmt->action == AP_DropObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); + + /* + * XXX EXCEPT with SET is not currently implemented. Workaround: DROP and + * re-ADD the schema with the desired EXCEPT list. + */ + if (stmt->action == AP_SetObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"), + errhint("Drop and re-add the schema with the desired EXCEPT list."))); + + if (stmt->action == AP_AddObjects) + { + List *rels; + List *explicitrelids; + + rels = OpenTableList(except_pubtables); + + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + /* + * Validate that each excluded table is not also in the explicit table + * list (which would be contradictory). + */ + CheckExceptNotInTableList(rels, explicitrelids); + + PublicationAddTables(pubid, rels, false, stmt); + + CloseTableList(rels); + } } /* @@ -1879,10 +1969,12 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) errmsg("publication \"%s\" does not exist", stmt->pubname)); - relations = list_concat(relations, except_pubtables); + if (stmt->for_all_tables) + relations = list_concat(relations, except_pubtables); + AlterPublicationTables(stmt, tup, relations, pstate->p_sourcetext, schemaidlist != NIL); - AlterPublicationSchemas(stmt, tup, schemaidlist); + AlterPublicationSchemas(stmt, tup, schemaidlist, except_pubtables); AlterPublicationAllFlags(stmt, rel, tup); } diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c index 4948e6d80c7..ecd518af02c 100644 --- a/src/bin/pg_dump/pg_dump.c +++ b/src/bin/pg_dump/pg_dump.c @@ -4973,6 +4973,7 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) PublicationInfo *pubinfo = pubsinfo->publication; PQExpBuffer query; char *tag; + bool has_except = false; /* Do nothing if not dumping schema */ if (!dopt->dumpSchema) @@ -4983,7 +4984,34 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) query = createPQExpBuffer(); appendPQExpBuffer(query, "ALTER PUBLICATION %s ", fmtId(pubinfo->dobj.name)); - appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s;\n", fmtId(schemainfo->dobj.name)); + appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s", fmtId(schemainfo->dobj.name)); + + /* + * Append EXCEPT clause for any tables that belong to this schema + * and are excluded from the publication. + */ + for (SimplePtrListCell *cell = pubinfo->except_tables.head; cell; cell = cell->next) + { + TableInfo *tbinfo = (TableInfo *) cell->ptr; + + if (strcmp(tbinfo->dobj.namespace->dobj.name, schemainfo->dobj.name) == 0) + { + if (!has_except) + { + appendPQExpBufferStr(query, " EXCEPT ("); + has_except = true; + } + else + appendPQExpBufferStr(query, ", "); + + appendPQExpBuffer(query, "TABLE ONLY %s", fmtId(tbinfo->dobj.name)); + } + } + + if (has_except) + appendPQExpBufferStr(query, ")"); + + appendPQExpBufferStr(query, ";\n"); /* * There is no point in creating drop query as the drop is done by schema diff --git a/src/bin/pg_dump/t/002_pg_dump.pl b/src/bin/pg_dump/t/002_pg_dump.pl index 9258948b583..d18b3b0d7b9 100644 --- a/src/bin/pg_dump/t/002_pg_dump.pl +++ b/src/bin/pg_dump/t/002_pg_dump.pl @@ -3283,6 +3283,30 @@ my %tests = ( like => { %full_runs, section_post_data => 1, }, }, + 'CREATE PUBLICATION pub11' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub11 FOR TABLES IN SCHEMA dump_test EXCEPT (TABLE test_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub11 WITH (publish = 'insert, update, delete, truncate');\E + .*? + \QALTER PUBLICATION pub11 ADD TABLES IN SCHEMA dump_test EXCEPT (TABLE ONLY test_table);\E + /xms, + like => { %full_runs, section_post_data => 1, }, + }, + + 'CREATE PUBLICATION pub12' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub12 FOR TABLES IN SCHEMA dump_test EXCEPT (TABLE test_table, dump_test.test_second_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub12 WITH (publish = 'insert, update, delete, truncate');\E + .*? + \QALTER PUBLICATION pub12 ADD TABLES IN SCHEMA dump_test EXCEPT (TABLE ONLY test_table, TABLE ONLY test_second_table);\E + /xms, + like => { %full_runs, section_post_data => 1, }, + }, + 'CREATE SUBSCRIPTION sub1' => { create_order => 50, create_sql => 'CREATE SUBSCRIPTION sub1 diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index 7d8b4504194..bf206aa6210 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2359,6 +2359,23 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); + /* After a single schema name in ADD context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 3a2db8642cc..cdcaf5afcb7 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -636,12 +636,70 @@ CREATE PUBLICATION testpub_except_ancestor_cross_schema ERROR: partition "public.testpub_part_s2" cannot be both published and excluded DETAIL: Partition root "pub_test.testpub_parted_s" is named in the publication's EXCEPT clause for schema "pub_test". DROP TABLE public.testpub_part_s2; +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; +-- fail: non-existing table in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- fail: EXCEPT table belongs to a different schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 1: ...xcept ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.tes... + ^ +-- fail: TABLE keyword is required for the first entry in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +ERROR: syntax error at or near "testpub_nopk" +LINE 1: ...lter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_no... + ^ +-- fail: exact same table given as both explicitly published and excluded +-- in a single ALTER ... ADD +ALTER PUBLICATION testpub_alter_except + ADD TABLE pub_test.testpub_tbl_s1, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot be both published and excluded +-- fail: add explicit partition and EXCEPT ancestor, given in a +-- single ALTER ... ADD statement +ALTER PUBLICATION testpub_alter_except + ADD TABLE pub_test.testpub_part_s, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ERROR: partition "pub_test.testpub_part_s" cannot be both published and excluded +DETAIL: Partition root "pub_test.testpub_parted_s" is named in the publication's EXCEPT clause for schema "pub_test". +-- fail: partition already explicitly published, then its root is EXCEPT-ed +-- via a later, separate ALTER ... ADD +ALTER PUBLICATION testpub_alter_except ADD TABLE pub_test.testpub_part_s; +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ERROR: partition "pub_test.testpub_part_s" cannot be both published and excluded +DETAIL: Partition root "pub_test.testpub_parted_s" is named in the publication's EXCEPT clause for schema "pub_test". +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_part_s; +-- fail: root already explicitly published, then its partition is rejected +-- from EXCEPT via a later, separate ALTER ... ADD (partitions can never +-- appear in EXCEPT, independent of the root's state) +ALTER PUBLICATION testpub_alter_except ADD TABLE pub_test.testpub_parted_s; +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); +ERROR: cannot specify relation "pub_test.testpub_part_s" in the publication EXCEPT clause +DETAIL: This operation is not supported for individual partitions. +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_parted_s; +-- ADD: qualified and unqualified names; unqualified is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + "pub_test.testpub_tbl_s2" + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP TABLE pub_test.testpub_parted_s CASCADE; DROP TABLE testpub_nopk, testpub_tbl_s1; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi, testpub_alter_except; --------------------------------------------- -- Tests for publications with SEQUENCES --------------------------------------------- diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 4a79055c4f3..a7edd8493e5 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -324,12 +324,55 @@ CREATE PUBLICATION testpub_except_ancestor_cross_schema TABLE public.testpub_part_s2; DROP TABLE public.testpub_part_s2; +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; + +-- fail: non-existing table in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- fail: EXCEPT table belongs to a different schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- fail: TABLE keyword is required for the first entry in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + +-- fail: exact same table given as both explicitly published and excluded +-- in a single ALTER ... ADD +ALTER PUBLICATION testpub_alter_except + ADD TABLE pub_test.testpub_tbl_s1, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: add explicit partition and EXCEPT ancestor, given in a +-- single ALTER ... ADD statement +ALTER PUBLICATION testpub_alter_except + ADD TABLE pub_test.testpub_part_s, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); + +-- fail: partition already explicitly published, then its root is EXCEPT-ed +-- via a later, separate ALTER ... ADD +ALTER PUBLICATION testpub_alter_except ADD TABLE pub_test.testpub_part_s; +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_part_s; + +-- fail: root already explicitly published, then its partition is rejected +-- from EXCEPT via a later, separate ALTER ... ADD (partitions can never +-- appear in EXCEPT, independent of the root's state) +ALTER PUBLICATION testpub_alter_except ADD TABLE pub_test.testpub_parted_s; +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_parted_s; + +-- ADD: qualified and unqualified names; unqualified is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); +\dRp+ testpub_alter_except + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP TABLE pub_test.testpub_parted_s CASCADE; DROP TABLE testpub_nopk, testpub_tbl_s1; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi, testpub_alter_except; --------------------------------------------- -- Tests for publications with SEQUENCES diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index c4e4efafec8..d69b43c14b5 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -347,6 +347,38 @@ is($result, qq(5), $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); +# ============================================ +# ALTER PUBLICATION EXCEPT for TABLES IN SCHEMA +# ============================================ + +# Truncate subscriber tables to remove data accumulated from previous tests. +$node_subscriber->safe_psql('postgres', + 'TRUNCATE sch1.tab_published, sch1.tab_excluded, sch1.parent, sch1.child'); + +# ADD: add a schema with an excepted table; verify the except entry takes effect. +$node_publisher->safe_psql('postgres', "CREATE PUBLICATION sch_pub"); +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub ADD TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_excluded)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(6), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: included table synced'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + # Cleanup schema tables before the multi-publication section. $node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); $node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); -- 2.50.1 (Apple Git-155)
v22-0004-Add-EXCEPT-support-to-ALTER-PUBLICATION-SET-TABL.patch (application/octet-stream, 27.3K) download From 84af021fbeb6e6787996e777418f449a53064698 Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Thu, 18 Jun 2026 11:32:32 +0530 Subject: [PATCH v22 4/5] Add EXCEPT support to ALTER PUBLICATION SET TABLES IN SCHEMA Extend AlterPublicationExceptTables() with the AP_SetObjects case, which redefines the publication and replaces the entire EXCEPT list. Syntax: ALTER PUBLICATION pub SET TABLES IN SCHEMA s EXCEPT (TABLE t1); This patch also cleans up EXCEPT entries when a schema is dropped from the publication. --- src/backend/commands/publicationcmds.c | 177 +++++++++++++++++++--- src/bin/psql/tab-complete.in.c | 17 +++ src/test/regress/expected/publication.out | 109 +++++++++++++ src/test/regress/sql/publication.sql | 47 ++++++ src/test/subscription/t/037_except.pl | 85 +++++++++++ 5 files changed, 410 insertions(+), 25 deletions(-) diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 2f21278ae64..8cbf41d324f 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -67,7 +67,8 @@ static void CloseTableList(List *rels); static void LockSchemaList(List *schemalist); static void PublicationAddTables(Oid pubid, List *rels, bool if_not_exists, AlterPublicationStmt *stmt); -static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok); +static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok, + bool delete_excluded); static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); @@ -1444,7 +1445,7 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, PublicationAddTables(pubid, rels, false, stmt); } else if (stmt->action == AP_DropObjects) - PublicationDropTables(pubid, rels, false); + PublicationDropTables(pubid, rels, false, false); else /* AP_SetObjects */ { List *oldrelids = NIL; @@ -1579,7 +1580,7 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, } /* And drop them. */ - PublicationDropTables(pubid, delrels, true); + PublicationDropTables(pubid, delrels, true, true); /* * Don't bother calculating the difference for adding, we'll catch and @@ -1681,8 +1682,8 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, /* * Increment the command counter so that is_schema_publication() in - * GetExcludedPublicationTables() can see the just-inserted schema - * rows when AlterPublicationSchemaExceptTables runs next. + * GetExcludedPublicationTables() can see the just-inserted schema rows + * when AlterPublicationSchemaExceptTables runs next. */ if (stmt->action == AP_AddObjects || stmt->action == AP_SetObjects) CommandCounterIncrement(); @@ -1700,16 +1701,18 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, */ static void AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, - HeapTuple tup, List *except_pubtables, - List *schemaidlist) + HeapTuple tup, List *except_pubtables, + List *schemaidlist) { Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); Oid pubid = pubform->oid; /* - * Nothing to do if no EXCEPT entries. + * Nothing to do if there are no EXCEPT entries, unless handling the SET + * command, because if the user has removed all exceptions we need to drop + * any existing ones. */ - if (!except_pubtables) + if (!except_pubtables && stmt->action != AP_SetObjects) return; /* @@ -1730,16 +1733,6 @@ AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); - /* - * XXX EXCEPT with SET is not currently implemented. Workaround: DROP and - * re-ADD the schema with the desired EXCEPT list. - */ - if (stmt->action == AP_SetObjects) - ereport(ERROR, - (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"), - errhint("Drop and re-add the schema with the desired EXCEPT list."))); - if (stmt->action == AP_AddObjects) { List *rels; @@ -1758,6 +1751,72 @@ AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, PublicationAddTables(pubid, rels, false, stmt); + CloseTableList(rels); + } + else /* AP_SetObjects */ + { + List *oldexceptrelids = NIL; + List *newexceptrelids = NIL; + List *delrelids = NIL; + List *rels; + List *explicitrelids; + + rels = OpenTableList(except_pubtables); + + /* Collect OIDs of the desired new EXCEPT list. */ + foreach_ptr(PublicationRelInfo, pri, rels) + newexceptrelids = lappend_oid(newexceptrelids, + RelationGetRelid(pri->relation)); + + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + /* Check that there is no clash between included and excluded tables. */ + CheckExceptNotInTableList(rels, explicitrelids); + + /* + * Get the current set of EXCEPT entries. Only FOR ALL TABLES and + * schema-level publications can have EXCEPT entries; for any other + * publication type oldexceptrelids stays NIL. + * + * Note: we check is_schema_publication() against the current catalog + * state (before AlterPublicationSchemas has run), so if the caller is + * doing SET TABLE t1 to convert a schema publication into a plain + * table publication, is_schema_publication() still returns true here. + * That is intentional: it lets us discover and clean up any stale + * EXCEPT entries that belong to the old schema definition. + */ + if (GetPublication(pubid)->alltables || is_schema_publication(pubid)) + oldexceptrelids = GetExcludedPublicationTables(pubid, + PUBLICATION_PART_ROOT); + + /* Build a list of old EXCEPT entries not present in the new list. */ + foreach_oid(oldrelid, oldexceptrelids) + { + if (!list_member_oid(newexceptrelids, oldrelid)) + delrelids = lappend_oid(delrelids, oldrelid); + } + + /* Drop old EXCEPT entries not present in the new list. */ + foreach_oid(relid, delrelids) + { + Oid proid; + ObjectAddress obj; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + /* Add new EXCEPT entries, skipping any already present. */ + PublicationAddTables(pubid, rels, true, stmt); + CloseTableList(rels); } } @@ -2381,33 +2440,68 @@ PublicationAddTables(Oid pubid, List *rels, bool if_not_exists, /* * Remove listed tables from the publication. + * + * delete_excluded controls how EXCEPT (prexcept=true) rows are handled: + * true - delete them silently. Used by the SET path to clear stale + * EXCEPT rows that are being replaced by a new EXCEPT list. + * false - treat them as "not a member". Used by ALTER ... DROP TABLE: an + * EXCEPT entry is not something DROP TABLE is expected to remove. */ static void -PublicationDropTables(Oid pubid, List *rels, bool missing_ok) +PublicationDropTables(Oid pubid, List *rels, bool missing_ok, + bool delete_excluded) { ObjectAddress obj; ListCell *lc; - Oid prid; foreach(lc, rels) { PublicationRelInfo *pubrel = (PublicationRelInfo *) lfirst(lc); Relation rel = pubrel->relation; Oid relid = RelationGetRelid(rel); + HeapTuple tup; + Form_pg_publication_rel pubrelform; + Oid prid = InvalidOid; + bool is_except = false; if (pubrel->columns) ereport(ERROR, errcode(ERRCODE_SYNTAX_ERROR), errmsg("column list must not be specified in ALTER PUBLICATION ... DROP")); - prid = GetSysCacheOid2(PUBLICATIONRELMAP, Anum_pg_publication_rel_oid, - ObjectIdGetDatum(relid), - ObjectIdGetDatum(pubid)); - if (!OidIsValid(prid)) + tup = SearchSysCache2(PUBLICATIONRELMAP, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (HeapTupleIsValid(tup)) + { + pubrelform = (Form_pg_publication_rel) GETSTRUCT(tup); + is_except = pubrelform->prexcept; + prid = pubrelform->oid; + ReleaseSysCache(tup); + } + + /* + * DROP TABLE operates only on regular member rows. A missing row + * and an EXCEPT row both mean the table isn't currently published, + * but we distinguish them so the EXCEPT case can carry a hint + * pointing the user at the EXCEPT list. The SET-cleanup caller + * (delete_excluded = true) intends to remove EXCEPT rows and so + * bypasses the EXCEPT half of this check. + */ + if (!OidIsValid(prid) || (is_except && !delete_excluded)) { if (missing_ok) continue; + if (is_except) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("cannot drop table \"%s\" from publication \"%s\"", + RelationGetQualifiedRelationName(rel), + get_publication_name(pubid, false)), + errdetail("The table is currently listed in the EXCEPT clause of the publication."), + errhint("Use ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT to modify the EXCEPT list."))); + ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("relation \"%s\" is not part of the publication", @@ -2463,6 +2557,7 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) foreach(lc, schemas) { Oid schemaid = lfirst_oid(lc); + List *except_relids; psid = GetSysCacheOid2(PUBLICATIONNAMESPACEMAP, Anum_pg_publication_namespace_oid, @@ -2479,8 +2574,40 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) get_namespace_name(schemaid)))); } + /* + * Collect EXCEPT entries for tables belonging to this schema before + * removing the schema entry. + */ + except_relids = GetExcludedPublicationTables(pubid, PUBLICATION_PART_ROOT); + ObjectAddressSet(obj, PublicationNamespaceRelationId, psid); performDeletion(&obj, DROP_CASCADE, 0); + + /* + * Drop any prexcept rows for tables belonging to this schema. These + * rows have no pg_depend entry pointing at the + * pg_publication_namespace row, so they are not cascaded by the + * performDeletion() call above and must be cleaned up explicitly. + */ + foreach_oid(relid, except_relids) + { + Oid proid; + + if (get_rel_namespace(relid) != schemaid) + continue; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + list_free(except_relids); } } diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index bf206aa6210..e67b9c63a5a 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2376,6 +2376,23 @@ match_previous_words(int pattern_id, } else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) COMPLETE_WITH(")"); + /* After a single schema name in SET context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index cdcaf5afcb7..889e29aaa35 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -694,6 +694,115 @@ Except tables: "pub_test.testpub_tbl_s1" "pub_test.testpub_tbl_s2" +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s2" + +-- fail: table in EXCEPT clause also appears in the explicit table list +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot be both published and excluded +-- fail: explicit partition + EXCEPT-ed root, given in a single SET statement +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_part_s, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ERROR: partition "pub_test.testpub_part_s" cannot be both published and excluded +DETAIL: Partition root "pub_test.testpub_parted_s" is named in the publication's EXCEPT clause for schema "pub_test". +-- fail: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 1: ...xcept SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.tes... + ^ +-- SET: unqualified name in EXCEPT is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- SET without EXCEPT clears the existing except list +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + +-- SET to a different schema removes old schema's EXCEPT entries +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA public; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "public" + +-- fail: nonexistent table in EXCEPT clause (SET path) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- SET: multiple schemas each with their own EXCEPT clause +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- fail: ALTER PUBLICATION ... DROP TABLE on an excluded table is rejected +-- with an EXCEPT-specific error. +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_tbl_s1; +ERROR: cannot drop table "pub_test.testpub_tbl_s1" from publication "testpub_alter_except" +DETAIL: The table is currently listed in the EXCEPT clause of the publication. +HINT: Use ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT to modify the EXCEPT list. +-- the EXCEPT entry is still present after the rejected DROP TABLE +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- fail: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +ERROR: EXCEPT clause is not supported with DROP in ALTER PUBLICATION +-- DROP TABLES IN SCHEMA removes associated EXCEPT entries +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "public" +Except tables: + "public.testpub_tbl1" + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index a7edd8493e5..367835f0fcd 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -367,6 +367,53 @@ ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_parted_s; ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); \dRp+ testpub_alter_except +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + +-- fail: table in EXCEPT clause also appears in the explicit table list +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: explicit partition + EXCEPT-ed root, given in a single SET statement +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_part_s, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); + +-- fail: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- SET: unqualified name in EXCEPT is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +\dRp+ testpub_alter_except + +-- SET without EXCEPT clears the existing except list +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + +-- SET to a different schema removes old schema's EXCEPT entries +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA public; +\dRp+ testpub_alter_except + +-- fail: nonexistent table in EXCEPT clause (SET path) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- SET: multiple schemas each with their own EXCEPT clause +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_alter_except + +-- fail: ALTER PUBLICATION ... DROP TABLE on an excluded table is rejected +-- with an EXCEPT-specific error. +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_tbl_s1; +-- the EXCEPT entry is still present after the rejected DROP TABLE +\dRp+ testpub_alter_except + +-- fail: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); + +-- DROP TABLES IN SCHEMA removes associated EXCEPT entries +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index d69b43c14b5..bcd8ac7bc1f 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -376,6 +376,61 @@ $result = is($result, qq(0), 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); +# SET: replace the except list; tab_excluded is now included and tab_published is excluded. +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_published)" +); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (7); + INSERT INTO sch1.tab_excluded VALUES (7); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded WHERE a = 7"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: newly included table is replicated' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published WHERE a = 7"); +is($result, qq(0), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: now-excluded table is not replicated' +); + +# SET without EXCEPT: clears the except list; both tables are now published. +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1"); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (8); + INSERT INTO sch1.tab_excluded VALUES (8); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published WHERE a = 8"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_published replicated after except list cleared' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded WHERE a = 8"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_excluded replicated after except list cleared' +); + $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); @@ -518,6 +573,36 @@ $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); +# OK when a table is excluded by a TABLES IN SCHEMA EXCEPT publication, +# but is included by another publication. +$node_publisher->safe_psql('postgres', 'TRUNCATE tab1'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE tab1'); + +$node_publisher->safe_psql( + 'postgres', qq( + CREATE PUBLICATION tap_pub1 FOR TABLES IN SCHEMA public EXCEPT (TABLE public.tab1); + CREATE PUBLICATION tap_pub2 FOR TABLE tab1; + INSERT INTO tab1 VALUES(1); +)); +$node_subscriber->psql('postgres', + "CREATE SUBSCRIPTION tap_sub CONNECTION '$publisher_connstr' PUBLICATION tap_pub1, tap_pub2" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'tap_sub'); + +$node_publisher->safe_psql('postgres', qq(INSERT INTO tab1 VALUES(2))); +$node_publisher->wait_for_catchup('tap_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT * FROM tab1 ORDER BY a"); +is( $result, qq(1 +2), + "TABLES IN SCHEMA EXCEPT: table excluded in schema pub but included by another pub is replicated" +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); + $node_publisher->stop('fast'); done_testing(); -- 2.50.1 (Apple Git-155)
v22-0005-Documentation-Patch.patch (application/octet-stream, 11.6K) download From 11f999a8fe68774932ec51d919cc99ee4ba4806f Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Thu, 18 Jun 2026 09:03:08 +0530 Subject: [PATCH v22 5/5] Documentation Patch --- doc/src/sgml/logical-replication.sgml | 3 +- doc/src/sgml/ref/alter_publication.sgml | 58 +++++++++++++++++++++++- doc/src/sgml/ref/create_publication.sgml | 42 +++++++++++++---- 3 files changed, 91 insertions(+), 12 deletions(-) diff --git a/doc/src/sgml/logical-replication.sgml b/doc/src/sgml/logical-replication.sgml index 690598bff98..46c944beae8 100644 --- a/doc/src/sgml/logical-replication.sgml +++ b/doc/src/sgml/logical-replication.sgml @@ -117,7 +117,8 @@ or <literal>FOR ALL SEQUENCES</literal>. Unlike tables, sequences can be synchronized at any time. For more information, see <xref linkend="logical-replication-sequences"/>. When a publication is - created with <literal>FOR ALL TABLES</literal>, a table or set of tables can + created with <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal>, a table or set of tables can be explicitly excluded from publication using the <link linkend="sql-createpublication-params-for-except-table"><literal>EXCEPT</literal></link> clause. diff --git a/doc/src/sgml/ref/alter_publication.sgml b/doc/src/sgml/ref/alter_publication.sgml index 52114a16a39..037ddfa9404 100644 --- a/doc/src/sgml/ref/alter_publication.sgml +++ b/doc/src/sgml/ref/alter_publication.sgml @@ -31,7 +31,7 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA <replaceable class="parameter">tables_in_schema</replaceable> [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -47,6 +47,10 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <replaceable class="parameter">table_object</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] [ WHERE ( <replaceable class="parameter">expression</replaceable> ) ] +<phrase>and <replaceable class="parameter">tables_in_schema</replaceable> is:</phrase> + + { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] + <phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> TABLE <replaceable class="parameter">table_object</replaceable> [, ... ] @@ -69,6 +73,9 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r The first two variants modify which tables/schemas are part of the publication. The <literal>ADD</literal> and <literal>DROP</literal> clauses will add and remove one or more tables/schemas from the publication. + The <literal>EXCEPT</literal> clause can be used with + <literal>ADD TABLES IN SCHEMA</literal> to exclude specific tables from a + schema-level publication. </para> <para> @@ -93,7 +100,11 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r used with a publication defined with <literal>FOR TABLE</literal> or <literal>FOR TABLES IN SCHEMA</literal>, replaces the list of tables/schemas in the publication with the specified list; the existing tables or schemas - that were present in the publication will be removed. + that were present in the publication will be removed. When + <literal>SET TABLES IN SCHEMA</literal> is used with an + <literal>EXCEPT</literal> clause, the excluded tables for each schema are + replaced with the specified list; if <literal>EXCEPT</literal> is omitted + for a schema, any existing exclusions for that schema are cleared. </para> <para> @@ -198,6 +209,27 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r </listitem> </varlistentry> + <varlistentry> + <term><literal>EXCEPT</literal></term> + <listitem> + <para> + When used with <literal>ADD TABLES IN SCHEMA</literal> + or <literal>SET TABLES IN SCHEMA</literal>, specifies + tables to be excluded from the publication. Each named + table must belong to the schema specified in the same + <literal>TABLES IN SCHEMA</literal> clause. Table names may be + schema-qualified or unqualified; unqualified names are implicitly + qualified with the schema named in the same clause. See + <xref linkend="sql-createpublication"/> for further details on the + semantics of <literal>EXCEPT</literal>. + </para> + <para> + Dropping a table always removes it from the <literal>EXCEPT</literal> + clause. + </para> + </listitem> + </varlistentry> + <varlistentry> <term><literal>SET ( <replaceable class="parameter">publication_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] )</literal></term> <listitem> @@ -288,6 +320,28 @@ ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA marketing, sales; </programlisting> </para> + <para> + Add schema <structname>sales</structname> to the publication + <structname>sales_publication</structname>, excluding the + <structname>sales.internal</structname> and + <structname>sales.drafts</structname> tables: +<programlisting> +ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA sales EXCEPT (TABLE internal, drafts); +</programlisting> + </para> + + <para> + Replace the schema list of <structname>sales_publication</structname> with + <structname>sales</structname>, excluding only + <structname>sales.drafts</structname>. Other than + <structname>sales.drafts</structname>, any previously excluded tables for schema + <structname>sales</structname> are no longer excluded. Any schemas previously in + <structname>sales_publication</structname> are removed: +<programlisting> +ALTER PUBLICATION sales_publication SET TABLES IN SCHEMA sales EXCEPT (TABLE drafts); +</programlisting> + </para> + <para> Add tables <structname>users</structname>, <structname>departments</structname> and schema diff --git a/doc/src/sgml/ref/create_publication.sgml b/doc/src/sgml/ref/create_publication.sgml index 85cfcaddafa..d16b4067fe6 100644 --- a/doc/src/sgml/ref/create_publication.sgml +++ b/doc/src/sgml/ref/create_publication.sgml @@ -28,7 +28,7 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA <replaceable class="parameter">tables_in_schema</replaceable> [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -39,6 +39,10 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <replaceable class="parameter">table_object</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] [ WHERE ( <replaceable class="parameter">expression</replaceable> ) ] +<phrase>and <replaceable class="parameter">tables_in_schema</replaceable> is:</phrase> + + { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] + <phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> TABLE <replaceable class="parameter">table_object</replaceable> [, ... ] @@ -142,6 +146,8 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <para> Marks the publication as one that replicates changes for all tables in the specified list of schemas, including tables created in the future. + Tables listed in the <literal>EXCEPT</literal> clause for a given schema + are excluded from the publication. </para> <para> @@ -173,7 +179,7 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <para> Marks the publication as one that replicates changes for all tables in the database, including tables created in the future. Tables listed in - <literal>EXCEPT</literal> clause are excluded from the publication. + the <literal>EXCEPT</literal> clause are excluded from the publication. </para> </listitem> </varlistentry> @@ -198,13 +204,21 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <listitem> <para> This clause specifies a list of tables to be excluded from the - publication. + publication. It can be used with <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal>. For <literal>FOR TABLES IN + SCHEMA</literal>, the exclusion applies only to tables in the schema + associated with the <literal>EXCEPT</literal>. </para> <para> - Once a table is excluded, the exclusion applies to that table - regardless of its name or schema. Renaming the table or moving it to - another schema using <command>ALTER TABLE ... SET SCHEMA</command> does - not remove the exclusion. + Once a table is excluded under <literal>FOR ALL TABLES</literal>, the + exclusion applies to that table regardless of its name or schema. + Renaming the table or moving it to another schema using + <command>ALTER TABLE ... SET SCHEMA</command> does not remove the + exclusion. However, for <literal>FOR TABLES IN SCHEMA</literal>, because + the <literal>EXCEPT</literal> is schema-scoped, moving a schema-excluded + table to another schema does remove the exclusion; if the table is later + moved back, the exclusion is not restored and must be re-established + with <command>ALTER PUBLICATION</command>. </para> <para> For inherited tables, if <literal>ONLY</literal> is specified before the @@ -216,8 +230,9 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> </para> <para> For partitioned tables, only the root partitioned table may be specified - in <literal>EXCEPT</literal>. Doing so excludes the root table and - all of its partitions from replication. The optional + in <literal>EXCEPT</literal>. Excluding the root table automatically + excludes all of its partitions from replication, even those in + schemas that are otherwise included in the publication. The optional <literal>ONLY</literal> and <literal>*</literal> has no effect for partitioned tables. </para> @@ -521,6 +536,15 @@ CREATE PUBLICATION production_publication FOR TABLE users, departments, TABLES I CREATE PUBLICATION sales_publication FOR TABLES IN SCHEMA marketing, sales; </programlisting></para> + <para> + Create a publication that publishes all changes for all the tables present in + the schema <structname>sales</structname>, except + <structname>internal</structname> and <structname>drafts</structname>: +<programlisting> +CREATE PUBLICATION sales_filtered FOR TABLES IN SCHEMA sales EXCEPT (TABLE internal, drafts); +</programlisting> + </para> + <para> Create a publication that publishes all changes for table <structname>users</structname>, but replicates only columns <structname>user_id</structname> and -- 2.50.1 (Apple Git-155)
^ permalink raw reply [nested|flat] 196+ messages in thread

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-20 08:22  Nisha Moond <nisha.moond412@gmail.com>
  parent: Peter Smith <smithpb2250@gmail.com>
  1 sibling, 1 reply; 196+ messages in thread

From: Nisha Moond @ 2026-07-20 08:22 UTC (permalink / raw)
  To: Peter Smith <smithpb2250@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Fri, Jul 17, 2026 at 1:37 PM Peter Smith <smithpb2250@gmail.com> wrote:
>
> Some review comments for v21-0002.
>
> ======
> Commit message.
>
> 1.
> Add ProcessSchemaExceptTables() to qualify each mention's EXCEPT
> entries, build a sorted signature per schema OID, and compare it
> against any prior mention of the same schema in the same statement,
> erroring on a mismatch. It also checks there are no clashes of the
> same schema with or without EXCEPT.
>
> ~
>
> IMO it's too confusing to explain the implementation detail here
> instead of the purpose. Also, it should say "with *and* without".
>
> SUGGESTION
> Add ProcessSchemaExceptTables(), which errors if the same schema is
> mentioned more than once with EXCEPT, or both with and without EXCEPT.
> It also checks that a schema's EXCEPT clause only lists tables from
> that same schema.
>

Updated as suggested in v22.
I think patch 002 is now in good shape to be merged into patch 001. Thoughts?

--
Thanks,
Nisha






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-20 10:17  shveta malik <shveta.malik@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  0 siblings, 2 replies; 196+ messages in thread

From: shveta malik @ 2026-07-20 10:17 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; shveta malik <shveta.malik@gmail.com>

On Mon, Jul 20, 2026 at 1:53 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
>
>
> Updated as suggested in v22.
> I think patch 002 is now in good shape to be merged into patch 001. Thoughts?
>

I will check it soon. A few comments on 001:


1)
+ /*
+ * A partition cannot be included when its partition root is excluded
+ * by the same publication.  Doing so would leave the catalog
+ * inconsistent (root excluded, partition included) and the
+ * ancestor-cascade rule would silently override the include at
+ * replication time.
+ *
+ * For partition hierarchies, only the partition root can be in an
+ * EXCEPT clause (a partition itself is rejected just above), so we
+ * only need to look up the catalog for the root.
+ */

Instead of mentioning the reason, can we simply mention below.

/*
 * A partition cannot be added to a publication if its partition root is
 * excluded by the publication. We follow the rule that excluding a
 * partition root means that the entire partition tree is excluded. Thus,
 * check whether the root is in the EXCEPT clause and reject adding the
 * individual partition to the publication.
 */

2)

+ /*
+ * A publication can hold both explicitly-included (prexcept=false) and
+ * EXCEPT (prexcept=true) rows for the same pubid.  Scan until we find an
+ * explicitly-included row, rather than relying on the first row's
+ * prexcept value.
+ */

Good to add one example to give clarity on the case here. Suggestion.

/*
 * A publication can have both explicitly included (prexcept = false) and
 * EXCEPT (prexcept = true) rows for the same pubid. For example:
 *
 *     CREATE PUBLICATION pub1 FOR TABLE s1.t1,
 *            TABLES IN SCHEMA s2 EXCEPT (TABLE s2.t1);
 *
 * Scan until we find an explicitly included row.
 */

3)
+/*
+ * Check whether a pg_publication_rel row exists for (pubid, relid); if so,
+ * set *is_except to its prexcept flag.
+ */
+bool
+GetPublicationRelEntry(Oid pubid, Oid relid, bool *is_except)

It is only checking (returning bool) and not getting the pg_pub_rel
row as such. Shall we name it as CheckPublicationRelEntry or
CheckPubRelEntry?

4)
Are the changes in GetAllPublicationRelations() intentional? We are
not changing any logic there though. So we can avoid touching this
function.

5)
GetAllSchemaPublicationRelations:
+ if (ancestors != NIL)
+ excluded = list_member_oid(except_relids,
+    llast_oid(ancestors));
+ list_free(ancestors);

Since we are already checking 'if (ancestors != NIL)', we can move
'list_free(ancestors)' also inside that if-block.

6)
+ }
+ list_free(schemaRels);

We an leave a blank line before list_free for better readibility.

7)
Currently is_table_publishable_in_publication() has:
----------------------------------
/*
 * If an ancestor is published, the partition's status depends on
 * publish_via_partition_root value.
 *
 * If it's true, the ancestor's relation OID is the effective published
 * OID, so the partition itself should be excluded (return false).
 *
 * If it's false, the partition is covered by its ancestor's presence in
 * the publication, it should be included (return true).
 */
if (relispartition)
{
if (OidIsValid(GetTopMostAncestorInPublication(pub->oid, ancestors, NULL)))
return !pub->pubviaroot;

/*
* GetTopMostAncestorInPublication() returns InvalidOid both when no
* ancestor matched at all, and when the root is excluded via EXCEPT.
* Disambiguate here: if the root is excluded, the partition is never
* published through this publication, regardless of whether the
* partition's schema is separately included.  ancestors can be NIL
* for a partition whose DETACH ... CONCURRENTLY is pending, in which
* case there is no ancestor to check.
*/
if (ancestors != NIL &&
GetPublicationRelEntry(pub->oid, llast_oid(ancestors), &is_except) &&
is_except)
return false;
}
----------------------------------

Shall we change this to:

/*
 * If the partition root is excluded via the EXCEPT clause, the partition
 * is never considered to be published through this publication. Check this
 * before checking whether an ancestor is published.
 *
 * If an ancestor is published, the partition's status depends on
 *....rest of the comment here...
 */
if (relispartition)
{
/*
 * ancestors can be NIL for a partition whose DETACH ... CONCURRENTLY is
 * pending, in which case there is no ancestor to check.
 */
if (ancestors != NIL &&
GetPublicationRelEntry(pub->oid, llast_oid(ancestors), &is_except) &&
is_except)
return false;

  if (OidIsValid(GetTopMostAncestorInPublication(pub->oid, ancestors, NULL)))
  return !pub->pubviaroot;
}


The benefit of above apporach is the bigger comment saying
'Disambiguate here' is not needed. That makes it complex to
understand. Plus if ROOT is excluded, we need not to execute ROOT
exlcusion check twice as you were doing earlier, one through
GetTopMostAncestorInPublication and one outside it. But let me know if
you see any issue in above changes.

thanks
Shveta






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-21 05:42  shveta malik <shveta.malik@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  1 sibling, 1 reply; 196+ messages in thread

From: shveta malik @ 2026-07-21 05:42 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; shveta malik <shveta.malik@gmail.com>

On Mon, Jul 20, 2026 at 3:47 PM shveta malik <shveta.malik@gmail.com> wrote:
>
> On Mon, Jul 20, 2026 at 1:53 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
> >
> >
> > Updated as suggested in v22.
> > I think patch 002 is now in good shape to be merged into patch 001. Thoughts?
> >
>
> I will check it soon. A few comments on 001:
>
>
> 1)
> + /*
> + * A partition cannot be included when its partition root is excluded
> + * by the same publication.  Doing so would leave the catalog
> + * inconsistent (root excluded, partition included) and the
> + * ancestor-cascade rule would silently override the include at
> + * replication time.
> + *
> + * For partition hierarchies, only the partition root can be in an
> + * EXCEPT clause (a partition itself is rejected just above), so we
> + * only need to look up the catalog for the root.
> + */
>
> Instead of mentioning the reason, can we simply mention below.
>
> /*
>  * A partition cannot be added to a publication if its partition root is
>  * excluded by the publication. We follow the rule that excluding a
>  * partition root means that the entire partition tree is excluded. Thus,
>  * check whether the root is in the EXCEPT clause and reject adding the
>  * individual partition to the publication.
>  */
>
> 2)
>
> + /*
> + * A publication can hold both explicitly-included (prexcept=false) and
> + * EXCEPT (prexcept=true) rows for the same pubid.  Scan until we find an
> + * explicitly-included row, rather than relying on the first row's
> + * prexcept value.
> + */
>
> Good to add one example to give clarity on the case here. Suggestion.
>
> /*
>  * A publication can have both explicitly included (prexcept = false) and
>  * EXCEPT (prexcept = true) rows for the same pubid. For example:
>  *
>  *     CREATE PUBLICATION pub1 FOR TABLE s1.t1,
>  *            TABLES IN SCHEMA s2 EXCEPT (TABLE s2.t1);
>  *
>  * Scan until we find an explicitly included row.
>  */
>
> 3)
> +/*
> + * Check whether a pg_publication_rel row exists for (pubid, relid); if so,
> + * set *is_except to its prexcept flag.
> + */
> +bool
> +GetPublicationRelEntry(Oid pubid, Oid relid, bool *is_except)
>
> It is only checking (returning bool) and not getting the pg_pub_rel
> row as such. Shall we name it as CheckPublicationRelEntry or
> CheckPubRelEntry?
>
> 4)
> Are the changes in GetAllPublicationRelations() intentional? We are
> not changing any logic there though. So we can avoid touching this
> function.
>
> 5)
> GetAllSchemaPublicationRelations:
> + if (ancestors != NIL)
> + excluded = list_member_oid(except_relids,
> +    llast_oid(ancestors));
> + list_free(ancestors);
>
> Since we are already checking 'if (ancestors != NIL)', we can move
> 'list_free(ancestors)' also inside that if-block.
>
> 6)
> + }
> + list_free(schemaRels);
>
> We an leave a blank line before list_free for better readibility.
>
> 7)
> Currently is_table_publishable_in_publication() has:
> ----------------------------------
> /*
>  * If an ancestor is published, the partition's status depends on
>  * publish_via_partition_root value.
>  *
>  * If it's true, the ancestor's relation OID is the effective published
>  * OID, so the partition itself should be excluded (return false).
>  *
>  * If it's false, the partition is covered by its ancestor's presence in
>  * the publication, it should be included (return true).
>  */
> if (relispartition)
> {
> if (OidIsValid(GetTopMostAncestorInPublication(pub->oid, ancestors, NULL)))
> return !pub->pubviaroot;
>
> /*
> * GetTopMostAncestorInPublication() returns InvalidOid both when no
> * ancestor matched at all, and when the root is excluded via EXCEPT.
> * Disambiguate here: if the root is excluded, the partition is never
> * published through this publication, regardless of whether the
> * partition's schema is separately included.  ancestors can be NIL
> * for a partition whose DETACH ... CONCURRENTLY is pending, in which
> * case there is no ancestor to check.
> */
> if (ancestors != NIL &&
> GetPublicationRelEntry(pub->oid, llast_oid(ancestors), &is_except) &&
> is_except)
> return false;
> }
> ----------------------------------
>
> Shall we change this to:
>
> /*
>  * If the partition root is excluded via the EXCEPT clause, the partition
>  * is never considered to be published through this publication. Check this
>  * before checking whether an ancestor is published.
>  *
>  * If an ancestor is published, the partition's status depends on
>  *....rest of the comment here...
>  */
> if (relispartition)
> {
> /*
>  * ancestors can be NIL for a partition whose DETACH ... CONCURRENTLY is
>  * pending, in which case there is no ancestor to check.
>  */
> if (ancestors != NIL &&
> GetPublicationRelEntry(pub->oid, llast_oid(ancestors), &is_except) &&
> is_except)
> return false;
>
>   if (OidIsValid(GetTopMostAncestorInPublication(pub->oid, ancestors, NULL)))
>   return !pub->pubviaroot;
> }
>
>
> The benefit of above apporach is the bigger comment saying
> 'Disambiguate here' is not needed. That makes it complex to
> understand. Plus if ROOT is excluded, we need not to execute ROOT
> exlcusion check twice as you were doing earlier, one through
> GetTopMostAncestorInPublication and one outside it. But let me know if
> you see any issue in above changes.
>

A few more comments:

8)
CreatePublication:
+ /*
+ * Collect explicit table OIDs now, before we close the relation
+ * list, so that except-table validation below can check for
+ * contradictions without relying on a catalog scan that might not
+ * yet see the just-inserted rows.
+ */
+ if (except_pubtables != NIL)
+ {
+ foreach_ptr(PublicationRelInfo, pri, rels)
+ explicitrelids = lappend_oid(explicitrelids,
+ RelationGetRelid(pri->relation));
+ }
+
  PublicationAddTables(puboid, rels, true, NULL);

Shall we make the explicitrelids collection after
'PublicationAddTables', as PublicationAddTables may error out too
while doing 'check_publication_add_relation'.

9)
In the check above, IIUC, except_pubtables can be there even for ALL
TABLES, but we want this handling only for schema-except list, so
shall we have the check as:

if (schemaidlist != NIL && except_pubtables != NIL)

10)
+ /*
+ * Validate that each excluded table is not also in the
+ * explicit table list (which would be contradictory), and
+ * that no explicit partition's root is in the except list.
+ * Use the in-memory explicitrelids collected above rather
+ * than re-reading the catalog, which may not yet see the
+ * just-inserted rows.
+ */

Can we please simplify this comment. The function
CheckExceptNotInTableList() already explains it in detail inside. Also
catalog-rows not visible is already explained by a comment where we
collect the relids.

/*
 * Validate that a table is not both explicitly included and excluded by
 * the schema's EXCEPT clause.
 */

11)
The changes in AlterPublication (variable name change) if really
needed can be shifter to alter-pub patch.

thanks
Shveta





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-21 05:52  Peter Smith <smithpb2250@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: Peter Smith @ 2026-07-21 05:52 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

Some review comments for v22*

======

1. GENERAL -- Consistent wording in messages

I found some examples of error messages that could be made more similar:

1a.
"modify" versus "change"

modify...

+ errhint("Use ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT
to modify the EXCEPT list.")));

versus (Change)

+ errhint("Change the EXCEPT clause using ALTER PUBLICATION ... SET
TABLES IN SCHEMA ... EXCEPT."));
+ errhint("Change the EXCEPT clause using ALTER PUBLICATION ... SET
TABLES IN SCHEMA ... EXCEPT.")));

+ errhint("%s", has_alltables_pub ?
+ _("Change the EXCEPT clause using ALTER PUBLICATION ... SET ALL
TABLES ... EXCEPT.") :
+ _("Change the EXCEPT clause using ALTER PUBLICATION ... SET TABLES
IN SCHEMA ... EXCEPT.")));

~

Shouldn't 1st one (from patch v22-0004) be identical to the others? e.g.:
Change the EXCEPT clause using ALTER PUBLICATION ... SET TABLES IN
SCHEMA ... EXCEPT.

~~~

1b.
"referenced" versus "named" versus "listed"

referenced...

+ errmsg_plural("cannot attach table \"%s\" as partition because it is
referenced in EXCEPT clause of publication %s",
+   "cannot attach table \"%s\" as partition because it is referenced
in EXCEPT clause of publications %s",

versus (named)

+ errdetail("Partition root \"%s\" is named in the publication's
EXCEPT clause for schema \"%s\".",
+   quote_qualified_identifier(get_namespace_name(get_rel_namespace(root)),
+ get_rel_name(root)),

+ errdetail("Partition root \"%s\" is named in the publication's
EXCEPT clause for schema \"%s\".",
+    RelationGetQualifiedRelationName(pri->relation),
+    get_namespace_name(RelationGetNamespace(pri->relation)))));

versus (listed)

+ errdetail("Ancestor \"%s\" of partition \"%s\" is currently listed
in the EXCEPT clause of the publication.",
+   quote_qualified_identifier(get_namespace_name(get_rel_namespace(root)),
+ get_rel_name(root)),

+ errdetail("The table is currently listed in the EXCEPT clause of the
publication."),

+ * publication, excluding any tables listed in the EXCEPT clause.

+ errdetail("Ancestor \"%s\" of partition \"%s\" is currently listed
in the EXCEPT clause of this command.",
+    RelationGetQualifiedRelationName(pri->relation),
+    quote_qualified_identifier(get_namespace_name(get_rel_namespace(explicitrelid)),

~

IMO there is no real difference here in saying "referenced" v "named"
v "listed", so why not make them all "named" so they are alike.

~~~

1c.
"EXCEPT list" versus "EXCEPT clause"

EXCEPT list:

+ errhint("Use ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT
to modify the EXCEPT list.")));

+ * A partition cannot be included when its partition root is in the
+ * same publication's EXCEPT list.  Doing so would leave the catalog

+ errhint("Change EXCEPT list using ALTER PUBLICATION ... SET TABLES
IN SCHEMA ... EXCEPT."));

+ errhint("Change EXCEPT list using ALTER PUBLICATION ... SET TABLES
IN SCHEMA ... EXCEPT.")));

+ /* filter out any tables that appear in the EXCEPT list */

+ * A partition whose root is in the publication's EXCEPT list
+ * is also excluded, even if the partition itself lives in a

+ * Validate that each excluded table is not also in the
+ * explicit table list (which would be contradictory), and
+ * that no explicit partition's root is in the except list.

etc.

I don't recognise the reasons for the difference -- it all seems a bit
random. There are a lot more "EXCEPT clause" than there are "EXCEPT
list".

EXCEPT list makes sense for some comments and parameters, but for
user-facing messages maybe those should consistently say "EXCEPT
clause"?

======
src/backend/catalog/pg_publication.c

2.
publication_add_relation:
On Mon, Jul 20, 2026 at 6:22 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
>
> On Thu, Jul 16, 2026 at 2:04 PM Peter Smith <smithpb2250@gmail.com> wrote:
> >
>
> > 7.
> > + errdetail("Ancestor \"%s\" of partition \"%s\" is currently listed
> > in the EXCEPT clause of the publication.",
> > +   quote_qualified_identifier(get_namespace_name(get_rel_namespace(root)),
> >
> > Similar (singular) comment to before.
> >
> > /in the EXCEPT clause/in an EXCEPT clause/
> >
>
> It looks like comment #4 is repeated here. In any case, I addressed
> both occurrences of the errdetail (in check_publication_add_relation()
> and CheckExceptNotInTableList()):
>   "Ancestor \"%s\" of partition \"%s\" is curre..".
>

Looks like a previous review comment #7 was missed despite saying it
was addressed. It still says:
+ errdetail("The table is currently listed in the EXCEPT clause of the
publication."),

======
src/backend/commands/publicationcmds.c

ProcessSchemaExceptTables

3.
(patch 0002)

+ * *schemas: accumulates all schema OIDs seen so far in this statement.
+ * *schemas_with_except: tracks which schema OIDs have already been seen
+ * with an EXCEPT clause in this statement.

Maybe this can clarify that `*schemas_with_except` OIDs will be a
subset of `*schemas`.OIDs

SUGGESTION
*schemas_with_except: This is a subset of *schemas. Tracks which of
the seen schemas of this statement had an EXCEPT clause.

======
Kind Regards,
Peter Smith.
Fujitsu Australia






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-23 11:55  Nisha Moond <nisha.moond412@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  1 sibling, 2 replies; 196+ messages in thread

From: Nisha Moond @ 2026-07-23 11:55 UTC (permalink / raw)
  To: shveta malik <shveta.malik@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Mon, Jul 20, 2026 at 3:47 PM shveta malik <shveta.malik@gmail.com> wrote:
>
> On Mon, Jul 20, 2026 at 1:53 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
> >
> >
> > Updated as suggested in v22.
> > I think patch 002 is now in good shape to be merged into patch 001. Thoughts?
> >
>
> I will check it soon. A few comments on 001:
>

Okay, thanks!

>
> 3)
> +/*
> + * Check whether a pg_publication_rel row exists for (pubid, relid); if so,
> + * set *is_except to its prexcept flag.
> + */
> +bool
> +GetPublicationRelEntry(Oid pubid, Oid relid, bool *is_except)
>
> It is only checking (returning bool) and not getting the pg_pub_rel
> row as such. Shall we name it as CheckPublicationRelEntry or
> CheckPubRelEntry?
>

CheckPublicationRelEntry looks good to me. Renamed accordingly.

> 4)
> Are the changes in GetAllPublicationRelations() intentional? We are
> not changing any logic there though. So we can avoid touching this
> function.
>

The changes were done as part of previous comment to make the
list/vars names used for EXCEPT specific objects consistent across
code. But yes I agree  GetAllPublicationRelations is untouched in the
patch, so should leave those as it is. Fixed.

>
> 7)
> Currently is_table_publishable_in_publication() has:
> ----------------------------------
> /*
>  * If an ancestor is published, the partition's status depends on
>  * publish_via_partition_root value.
>  *
>  * If it's true, the ancestor's relation OID is the effective published
>  * OID, so the partition itself should be excluded (return false).
>  *
>  * If it's false, the partition is covered by its ancestor's presence in
>  * the publication, it should be included (return true).
>  */
> if (relispartition)
> {
> if (OidIsValid(GetTopMostAncestorInPublication(pub->oid, ancestors, NULL)))
> return !pub->pubviaroot;
>
> /*
> * GetTopMostAncestorInPublication() returns InvalidOid both when no
> * ancestor matched at all, and when the root is excluded via EXCEPT.
> * Disambiguate here: if the root is excluded, the partition is never
> * published through this publication, regardless of whether the
> * partition's schema is separately included.  ancestors can be NIL
> * for a partition whose DETACH ... CONCURRENTLY is pending, in which
> * case there is no ancestor to check.
> */
> if (ancestors != NIL &&
> GetPublicationRelEntry(pub->oid, llast_oid(ancestors), &is_except) &&
> is_except)
> return false;
> }
> ----------------------------------
>
> Shall we change this to:
>
> /*
>  * If the partition root is excluded via the EXCEPT clause, the partition
>  * is never considered to be published through this publication. Check this
>  * before checking whether an ancestor is published.
>  *
>  * If an ancestor is published, the partition's status depends on
>  *....rest of the comment here...
>  */
> if (relispartition)
> {
> /*
>  * ancestors can be NIL for a partition whose DETACH ... CONCURRENTLY is
>  * pending, in which case there is no ancestor to check.
>  */
> if (ancestors != NIL &&
> GetPublicationRelEntry(pub->oid, llast_oid(ancestors), &is_except) &&
> is_except)
> return false;
>
>   if (OidIsValid(GetTopMostAncestorInPublication(pub->oid, ancestors, NULL)))
>   return !pub->pubviaroot;
> }
>
>
> The benefit of above apporach is the bigger comment saying
> 'Disambiguate here' is not needed. That makes it complex to
> understand. Plus if ROOT is excluded, we need not to execute ROOT
> exlcusion check twice as you were doing earlier, one through
> GetTopMostAncestorInPublication and one outside it. But let me know if
> you see any issue in above changes.
>

The suggestion makes sense to me. I've updated the code accordingly.
~~~

Attached v23 patch set addressing all of the above comments, as well
as the comments in [1] and [2].

[1] https://www.postgresql.org/message-id/CAJpy0uD%2BcODgXzM%3DyQFCVMDx3bPT18wiOUtEMTNvtSkzLUKnGw%40mail...
[2] https://www.postgresql.org/message-id/CAHut%2BPt_G%3DUm7vpY_eJLknOKVzcOrfY6ADzwcmfy09ZsG0sRTA%40mail...
--
Thanks,
Nisha

Attachments: download all (5 files, .tar.gz)

v23-0001-Support-EXCEPT-clause-for-schema-level-publicati.patch (application/octet-stream, 76.7K) download From 455d1e3c2cbf43f1585fe24053fa9c450fcd2db3 Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Tue, 16 Jun 2026 10:58:49 +0530 Subject: [PATCH v23 1/5] Support EXCEPT clause for schema-level publications Extend table exclusion support in publications to allow specific tables to be excluded from schema-level publications using an EXCEPT clause in CREATE PUBLICATION. Supported syntax: CREATE PUBLICATION <pub> FOR TABLES IN SCHEMA s EXCEPT (TABLE t1,...); --- src/backend/catalog/pg_publication.c | 226 ++++++++++++++++---- src/backend/commands/publicationcmds.c | 188 +++++++++++++++- src/backend/commands/tablecmds.c | 24 ++- src/backend/parser/gram.y | 54 ++++- src/backend/replication/pgoutput/pgoutput.c | 32 ++- src/backend/utils/cache/relcache.c | 44 ++-- src/bin/psql/describe.c | 18 ++ src/bin/psql/tab-complete.in.c | 35 ++- src/include/catalog/pg_publication.h | 1 + src/include/commands/publicationcmds.h | 2 + src/include/nodes/parsenodes.h | 2 + src/test/regress/expected/publication.out | 226 +++++++++++++++++++- src/test/regress/sql/publication.sql | 143 ++++++++++++- src/test/subscription/t/037_except.pl | 208 +++++++++++++++++- 14 files changed, 1115 insertions(+), 88 deletions(-) diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index 1ec94c851b2..183f97de502 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -53,7 +53,7 @@ typedef struct * error if not. */ static void -check_publication_add_relation(PublicationRelInfo *pri) +check_publication_add_relation(PublicationRelInfo *pri, Oid pubid) { Relation targetrel = pri->relation; const char *relname; @@ -70,12 +70,42 @@ check_publication_add_relation(PublicationRelInfo *pri) errormsg = gettext_noop("cannot add relation \"%s\" to publication"); } - /* If in EXCEPT clause, must be root partitioned table */ - if (pri->except && targetrel->rd_rel->relispartition) - ereport(ERROR, - (errcode(ERRCODE_INVALID_PARAMETER_VALUE), - errmsg(errormsg, relname), - errdetail("This operation is not supported for individual partitions."))); + if (targetrel->rd_rel->relispartition) + { + Oid relid = RelationGetRelid(targetrel); + Oid root; + bool root_except; + + if (pri->except) + { + /* If in EXCEPT clause, must be root partitioned table */ + ereport(ERROR, + (errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg(errormsg, relname), + errdetail("This operation is not supported for individual partitions."))); + } + + /* + * A partition cannot be added to a publication if its partition root + * is excluded by the publication. We follow the rule that excluding a + * partition root means that the entire partition tree is excluded. + * Thus, check whether the root is in the EXCEPT clause and reject + * adding the individual partition to the publication. + */ + root = llast_oid(get_partition_ancestors(relid)); + + if (CheckPublicationRelEntry(pubid, root, &root_except) && root_except) + ereport(ERROR, + errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("cannot add partition \"%s\" to publication \"%s\"", + RelationGetQualifiedRelationName(targetrel), + get_publication_name(pubid, false)), + errdetail("Partition root \"%s\" is named in the publication's EXCEPT clause for schema \"%s\".", + quote_qualified_identifier(get_namespace_name(get_rel_namespace(root)), + get_rel_name(root)), + get_namespace_name(get_rel_namespace(root))), + errhint("Change the EXCEPT clause using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT.")); + } /* Must be a regular or partitioned table */ if (RelationGetForm(targetrel)->relkind != RELKIND_RELATION && @@ -319,7 +349,7 @@ is_schema_publication(Oid pubid) } /* - * Returns true if the publication has explicitly included relation (i.e., + * Returns true if the publication has an explicitly-included relation (i.e., * not marked as EXCEPT). */ bool @@ -340,19 +370,23 @@ is_table_publication(Oid pubid) scan = systable_beginscan(pubrelsrel, PublicationRelPrpubidIndexId, true, NULL, 1, &scankey); - tup = systable_getnext(scan); - if (HeapTupleIsValid(tup)) - { - Form_pg_publication_rel pubrel; - - pubrel = (Form_pg_publication_rel) GETSTRUCT(tup); - /* - * For any publication, pg_publication_rel contains either only EXCEPT - * entries or only explicitly included tables. Therefore, examining - * the first tuple is sufficient to determine table inclusion. - */ - result = !pubrel->prexcept; + /* + * A publication can have both explicitly included (prexcept = false) and + * EXCEPT (prexcept = true) rows for the same pubid. For example: + * + * CREATE PUBLICATION pub1 FOR TABLE s1.t1, TABLES IN SCHEMA s2 EXCEPT + * (TABLE s2.t1); + * + * Scan until we find an explicitly included row. + */ + while (HeapTupleIsValid(tup = systable_getnext(scan))) + { + if (!((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept) + { + result = true; + break; + } } systable_endscan(scan); @@ -361,6 +395,27 @@ is_table_publication(Oid pubid) return result; } +/* + * Check whether a pg_publication_rel row exists for (pubid, relid); if so, + * set *is_except to its prexcept flag. + */ +bool +CheckPublicationRelEntry(Oid pubid, Oid relid, bool *is_except) +{ + HeapTuple tup; + + tup = SearchSysCache2(PUBLICATIONRELMAP, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (!HeapTupleIsValid(tup)) + return false; + + *is_except = ((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept; + ReleaseSysCache(tup); + + return true; +} + /* * Returns true if the relation has column list associated with the * publication, false otherwise. @@ -456,11 +511,26 @@ GetPubPartitionOptionRelations(List *result, PublicationPartOpt pub_partopt, * ancestor is at the end of the list. */ Oid -GetTopMostAncestorInPublication(Oid puboid, List *ancestors, int *ancestor_level) +GetTopMostAncestorInPublication(Oid puboid, List *ancestors, + int *ancestor_level) { ListCell *lc; Oid topmost_relid = InvalidOid; int level = 0; + bool root_except; + + if (ancestors == NIL) + return InvalidOid; + + /* + * If the partition root is excluded from this publication via an EXCEPT + * clause, the partition is not published through this publication, so + * return InvalidOid. Since only partition roots can appear in an EXCEPT + * clause, the root is the only ancestor worth a catalog lookup. + */ + if (CheckPublicationRelEntry(puboid, llast_oid(ancestors), &root_except) && + root_except) + return InvalidOid; /* * Find the "topmost" ancestor that is in this publication. @@ -547,6 +617,7 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, List *relids = NIL; int i; bool inval_except_table; + bool is_except; rel = table_open(PublicationRelRelationId, RowExclusiveLock); @@ -555,21 +626,29 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, * duplicates, it's here just to provide nicer error message in common * case. The real protection is the unique key on the catalog. */ - if (SearchSysCacheExists2(PUBLICATIONRELMAP, ObjectIdGetDatum(relid), - ObjectIdGetDatum(pubid))) + if (CheckPublicationRelEntry(pubid, relid, &is_except)) { table_close(rel, RowExclusiveLock); if (if_not_exists) return InvalidObjectAddress; - ereport(ERROR, - (errcode(ERRCODE_DUPLICATE_OBJECT), - errmsg("relation \"%s\" is already member of publication \"%s\"", - RelationGetRelationName(targetrel), pub->name))); + if (is_except) + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("cannot add table \"%s\" to publication \"%s\"", + RelationGetQualifiedRelationName(targetrel), + pub->name), + errdetail("The table is currently named in the EXCEPT clause of the publication."), + errhint("Change the EXCEPT clause using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT."))); + else + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("relation \"%s\" is already member of publication \"%s\"", + RelationGetRelationName(targetrel), pub->name))); } - check_publication_add_relation(pri); + check_publication_add_relation(pri, pubid); /* Validate and translate column names into a Bitmapset of attnums. */ attnums = pub_collist_validate(pri->relation, pri->columns); @@ -992,12 +1071,13 @@ GetIncludedPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) * Gets list of table oids that were specified in the EXCEPT clause for a * publication. * - * This should only be used FOR ALL TABLES publications. + * This is used for FOR ALL TABLES and FOR TABLES IN SCHEMA publications, + * both of which support EXCEPT TABLE. */ List * GetExcludedPublicationTables(Oid pubid, PublicationPartOpt pub_partopt) { - Assert(GetPublication(pubid)->alltables); + Assert(GetPublication(pubid)->alltables || is_schema_publication(pubid)); return get_publication_relations(pubid, pub_partopt, true); } @@ -1242,22 +1322,63 @@ GetSchemaPublicationRelations(Oid schemaid, PublicationPartOpt pub_partopt) /* * Gets the list of all relations published by FOR TABLES IN SCHEMA - * publication. + * publication, excluding any tables listed in EXCEPT clauses. */ List * GetAllSchemaPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) { List *result = NIL; List *pubschemalist = GetPublicationSchemas(pubid); + List *except_relids = NIL; ListCell *cell; + /* get the list of tables excluded via EXCEPT TABLE for this publication */ + if (pubschemalist != NIL) + except_relids = GetExcludedPublicationTables(pubid, pub_partopt); + foreach(cell, pubschemalist) { Oid schemaid = lfirst_oid(cell); List *schemaRels = NIL; schemaRels = GetSchemaPublicationRelations(schemaid, pub_partopt); - result = list_concat(result, schemaRels); + + if (except_relids != NIL) + { + /* filter out any tables that appear in the EXCEPT clause */ + foreach_oid(relid, schemaRels) + { + bool excluded = list_member_oid(except_relids, relid); + + /* + * A partition whose root is excluded from the publication is + * also excluded, even if the partition itself lives in a + * different (included) schema. Only the topmost root of a + * partition hierarchy can ever appear in EXCEPT (see + * check_publication_add_relation()), so it's enough to check + * the last element of the ancestors list, rather than walking + * the whole chain. + */ + if (!excluded && get_rel_relispartition(relid)) + { + List *ancestors = get_partition_ancestors(relid); + + if (ancestors != NIL) + { + excluded = list_member_oid(except_relids, + llast_oid(ancestors)); + list_free(ancestors); + } + } + + if (!excluded) + result = lappend_oid(result, relid); + } + + list_free(schemaRels); + } + else + result = list_concat(result, schemaRels); } return result; @@ -1334,6 +1455,7 @@ is_table_publishable_in_publication(Oid relid, Publication *pub) { bool relispartition; List *ancestors = NIL; + bool is_except; /* * For non-pubviaroot publications, a partitioned table is never the @@ -1381,6 +1503,10 @@ is_table_publishable_in_publication(Oid relid, Publication *pub) */ /* + * If the partition root is excluded via the EXCEPT clause, the partition + * is never considered to be published through this publication. Check + * this before checking whether an ancestor is published. + * * If an ancestor is published, the partition's status depends on * publish_via_partition_root value. * @@ -1390,20 +1516,38 @@ is_table_publishable_in_publication(Oid relid, Publication *pub) * If it's false, the partition is covered by its ancestor's presence in * the publication, it should be included (return true). */ - if (relispartition && - OidIsValid(GetTopMostAncestorInPublication(pub->oid, ancestors, NULL))) - return !pub->pubviaroot; + if (relispartition) + { + /* + * ancestors can be NIL for a partition whose DETACH ... CONCURRENTLY + * is pending, in which case there is no ancestor to check. + */ + if (ancestors != NIL && + CheckPublicationRelEntry(pub->oid, llast_oid(ancestors), &is_except) && + is_except) + return false; + + if (OidIsValid(GetTopMostAncestorInPublication(pub->oid, ancestors, NULL))) + return !pub->pubviaroot; + } /* * Check whether the table is explicitly published via pg_publication_rel * or pg_publication_namespace. + * + * A pg_publication_rel row with prexcept=true means the table is + * explicitly excluded via EXCEPT and must not be reported as published, + * even if its schema is otherwise included. A row with prexcept=false + * means it is explicitly included. If no pg_publication_rel row exists, + * the table is published iff its schema appears in + * pg_publication_namespace. */ - return (SearchSysCacheExists2(PUBLICATIONRELMAP, - ObjectIdGetDatum(relid), - ObjectIdGetDatum(pub->oid)) || - SearchSysCacheExists2(PUBLICATIONNAMESPACEMAP, - ObjectIdGetDatum(get_rel_namespace(relid)), - ObjectIdGetDatum(pub->oid))); + if (CheckPublicationRelEntry(pub->oid, relid, &is_except)) + return !is_except; + + return SearchSysCacheExists2(PUBLICATIONNAMESPACEMAP, + ObjectIdGetDatum(get_rel_namespace(relid)), + ObjectIdGetDatum(pub->oid)); } /* diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 440adb356ad..a789aa735c5 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -22,6 +22,7 @@ #include "catalog/namespace.h" #include "catalog/objectaccess.h" #include "catalog/objectaddress.h" +#include "catalog/partition.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" #include "catalog/pg_namespace.h" @@ -71,6 +72,7 @@ static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); static char defGetGeneratedColsOption(DefElem *def); +static void CheckExceptNotInTableList(List *except_rels, List *explicitrelids); static void @@ -181,7 +183,7 @@ parse_publication_options(ParseState *pstate, */ static void ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, - List **rels, List **exceptrels, List **schemas) + List **rels, List **except_pubtables, List **schemas) { ListCell *cell; PublicationObjSpec *pubobj; @@ -200,7 +202,7 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, { case PUBLICATIONOBJ_EXCEPT_TABLE: pubobj->pubtable->except = true; - *exceptrels = lappend(*exceptrels, pubobj->pubtable); + *except_pubtables = lappend(*except_pubtables, pubobj->pubtable); break; case PUBLICATIONOBJ_TABLE: pubobj->pubtable->except = false; @@ -224,6 +226,38 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, /* Filter out duplicates if user specifies "sch1, sch1" */ *schemas = list_append_unique_oid(*schemas, schemaid); + + /* + * Qualify unqualified EXCEPT table names with the resolved + * current schema and reject any explicitly cross-schema + * entries. This mirrors the parse-time handling done for + * TABLES_IN_SCHEMA in preprocess_pubobj_list(), deferred here + * because CURRENT_SCHEMA is not known until execution time. + */ + if (pubobj->except_tables != NIL) + { + char *cur_schema_name = get_namespace_name(schemaid); + + foreach_ptr(PublicationObjSpec, eobj, pubobj->except_tables) + { + const char *eobj_schemaname = + eobj->pubtable->relation->schemaname; + const char *eobj_relname = + eobj->pubtable->relation->relname; + + if (eobj_schemaname == NULL) + eobj->pubtable->relation->schemaname = cur_schema_name; + else if (strcmp(eobj_schemaname, cur_schema_name) != 0) + ereport(ERROR, + errcode(ERRCODE_INVALID_OBJECT_DEFINITION), + errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", + quote_qualified_identifier(eobj_schemaname, eobj_relname), + cur_schema_name)); + + *except_pubtables = lappend(*except_pubtables, + eobj->pubtable); + } + } break; default: /* shouldn't happen */ @@ -770,6 +804,60 @@ TransformPubWhereClauses(List *tables, const char *queryString, } } +/* + * Check that a table is not both excluded and published in the same DDL. + * + * An excluded relation (except_rels) cannot also be present in + * explicitrelids, the list of OIDs added to the publication by the explicit + * TABLE list. + * + * Also reject any relation in explicitrelids whose partition root is in + * except_rels. Otherwise the catalog would be inconsistent (root excluded, + * partition explicitly included), and the ancestor-cascade rule would + * silently override the include at replication time. + */ +static void +CheckExceptNotInTableList(List *except_rels, List *explicitrelids) +{ + foreach_oid(explicitrelid, explicitrelids) + { + Oid root = InvalidOid; + + if (get_rel_relispartition(explicitrelid)) + { + List *ancestors = get_partition_ancestors(explicitrelid); + + /* + * ancestors is NIL for a partition with a pending DETACH + * CONCURRENTLY. + */ + if (ancestors != NIL) + root = llast_oid(ancestors); + list_free(ancestors); + } + + foreach_ptr(PublicationRelInfo, pri, except_rels) + { + Oid exceptrelid = RelationGetRelid(pri->relation); + + if (exceptrelid == explicitrelid) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" cannot be both published and excluded", + RelationGetQualifiedRelationName(pri->relation))); + + if (OidIsValid(root) && exceptrelid == root) + ereport(ERROR, + (errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("partition \"%s\" cannot be both published and excluded", + quote_qualified_identifier(get_namespace_name(get_rel_namespace(explicitrelid)), + get_rel_name(explicitrelid))), + errdetail("Partition root \"%s\" is named in the publication's EXCEPT clause for schema \"%s\".", + RelationGetQualifiedRelationName(pri->relation), + get_namespace_name(RelationGetNamespace(pri->relation))))); + } + } +} /* * Given a list of tables that are going to be added to a publication, @@ -849,7 +937,7 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) char publish_generated_columns; AclResult aclresult; List *relations = NIL; - List *exceptrelations = NIL; + List *except_pubtables = NIL; List *schemaidlist = NIL; /* must have CREATE privilege on database */ @@ -936,16 +1024,16 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) /* Associate objects with the publication. */ ObjectsInPublicationToOids(stmt->pubobjects, pstate, &relations, - &exceptrelations, &schemaidlist); + &except_pubtables, &schemaidlist); if (stmt->for_all_tables) { /* Process EXCEPT table list */ - if (exceptrelations != NIL) + if (except_pubtables != NIL) { List *rels; - rels = OpenTableList(exceptrelations); + rels = OpenTableList(except_pubtables); PublicationAddTables(puboid, rels, true, NULL); CloseTableList(rels); } @@ -959,6 +1047,8 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) } else if (!stmt->for_all_sequences) { + List *explicitrelids = NIL; + /* FOR TABLES IN SCHEMA requires superuser */ if (schemaidlist != NIL && !superuser()) ereport(ERROR, @@ -978,6 +1068,20 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) publish_via_partition_root); PublicationAddTables(puboid, rels, true, NULL); + + /* + * Collect explicit table OIDs now, before we close the relation + * list, so that except-table validation below can check for + * contradictions without relying on a catalog scan that might not + * yet see the just-inserted rows. + */ + if (except_pubtables != NIL) + { + foreach_ptr(PublicationRelInfo, pri, rels) + explicitrelids = lappend_oid(explicitrelids, + RelationGetRelid(pri->relation)); + } + CloseTableList(rels); } @@ -989,6 +1093,22 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) */ LockSchemaList(schemaidlist); PublicationAddSchemas(puboid, schemaidlist, true, NULL); + + if (except_pubtables != NIL) + { + List *except_rels; + + except_rels = OpenTableList(except_pubtables); + + /* + * Validate that a table is not both explicitly included and + * excluded by the schema's EXCEPT clause. + */ + CheckExceptNotInTableList(except_rels, explicitrelids); + + PublicationAddTables(puboid, except_rels, true, NULL); + CloseTableList(except_rels); + } } } @@ -1829,6 +1949,62 @@ RemovePublicationSchemaById(Oid psoid) table_close(rel, RowExclusiveLock); } +/* + * Remove any EXCEPT clause entries for a relation from schema publications. + * Called when a table changes schema (ALTER TABLE ... SET SCHEMA), so that + * a schema-scoped exclusion does not silently follow the table to its new + * schema. + */ +void +RemoveSchemaPubExceptForRel(Oid relid, Oid oldNspOid, Oid newNspOid) +{ + List *pubids; + + /* + * If the table is not actually moving to a different schema (no-op ALTER + * TABLE ... SET SCHEMA <current_schema>), there is nothing to do. + */ + if (oldNspOid == newNspOid) + return; + + pubids = GetRelationExcludedPublications(relid); + + foreach_oid(pubid, pubids) + { + Oid proid; + + /* + * This problem does not apply to FOR ALL TABLES publications, because + * their EXCEPT clause is publication-scoped, not schema-scoped: the + * exclusion should persist regardless of what schema the table is in. + */ + if (!is_schema_publication(pubid)) + continue; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddress obj; + + ObjectAddressSet(obj, PublicationRelRelationId, proid); + + ereport(DEBUG2, + errmsg_internal("auto-remove exclusion of table \"%s.%s\" from publication \"%s\": table moved to schema \"%s\"", + get_namespace_name(oldNspOid), + get_rel_name(relid), + get_publication_name(pubid, false), + get_namespace_name(newNspOid))); + + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + list_free(pubids); +} + /* * Open relations specified by a PublicationTable list. * The returned tables are locked in ShareUpdateExclusiveLock mode in order to diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 6d4c457b820..1112f616c3a 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -49,6 +49,7 @@ #include "catalog/pg_opclass.h" #include "catalog/pg_policy.h" #include "catalog/pg_proc.h" +#include "catalog/pg_publication.h" #include "catalog/pg_publication_rel.h" #include "catalog/pg_rewrite.h" #include "catalog/pg_statistic_ext.h" @@ -63,6 +64,7 @@ #include "commands/event_trigger.h" #include "commands/extension.h" #include "commands/repack.h" +#include "commands/publicationcmds.h" #include "commands/sequence.h" #include "commands/tablecmds.h" #include "commands/tablespace.h" @@ -19745,6 +19747,16 @@ AlterTableNamespaceInternal(Relation rel, Oid oldNspOid, Oid nspOid, AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid, false, objsMoved); + /* + * Remove any EXCEPT clause entries for this relation from schema + * publications. A schema-scoped exclusion is no longer meaningful once + * the table moves to a different schema. + */ + if (rel->rd_rel->relkind == RELKIND_RELATION || + rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE) + RemoveSchemaPubExceptForRel(RelationGetRelid(rel), oldNspOid, + nspOid); + table_close(classRel, RowExclusiveLock); } @@ -21078,6 +21090,7 @@ ATExecAttachPartition(List **wqueue, Relation rel, PartitionCmd *cmd, if (exceptpuboids != NIL) { bool first = true; + bool has_alltables_pub = false; StringInfoData pubnames; initStringInfo(&pubnames); @@ -21091,17 +21104,22 @@ ATExecAttachPartition(List **wqueue, Relation rel, PartitionCmd *cmd, else appendStringInfo(&pubnames, _(", \"%s\""), pubname); first = false; + + if (GetPublication(pubid)->alltables) + has_alltables_pub = true; } ereport(ERROR, errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), - errmsg_plural("cannot attach table \"%s\" as partition because it is referenced in publication %s EXCEPT clause", - "cannot attach table \"%s\" as partition because it is referenced in publications %s EXCEPT clause", + errmsg_plural("cannot attach table \"%s\" as partition because it is named in EXCEPT clause of publication %s", + "cannot attach table \"%s\" as partition because it is named in EXCEPT clause of publications %s", list_length(exceptpuboids), RelationGetRelationName(attachrel), pubnames.data), errdetail("The publication EXCEPT clause cannot contain tables that are partitions."), - errhint("Change the publication's EXCEPT clause using ALTER PUBLICATION ... SET ALL TABLES.")); + errhint("%s", has_alltables_pub ? + _("Change the EXCEPT clause using ALTER PUBLICATION ... SET ALL TABLES ... EXCEPT.") : + _("Change the EXCEPT clause using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT."))); } list_free(exceptpuboids); diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y index 17035fb4d15..18826a74b77 100644 --- a/src/backend/parser/gram.y +++ b/src/backend/parser/gram.y @@ -58,6 +58,7 @@ #include "nodes/makefuncs.h" #include "nodes/nodeFuncs.h" #include "parser/parser.h" +#include "utils/builtins.h" #include "utils/datetime.h" #include "utils/xml.h" @@ -11282,7 +11283,7 @@ AlterOwnerStmt: ALTER AGGREGATE aggregate_with_argtypes OWNER TO RoleSpec * pub_obj is one of: * * TABLE table [, ...] - * TABLES IN SCHEMA schema [, ...] + * TABLES IN SCHEMA schema [EXCEPT (TABLE table [, ...] )] [, ...] * *****************************************************************************/ @@ -11342,23 +11343,26 @@ PublicationObjSpec: $$->pubtable->columns = $3; $$->pubtable->whereClause = $4; } - | TABLES IN_P SCHEMA ColId + | TABLES IN_P SCHEMA ColId opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_SCHEMA; $$->name = $4; + $$->except_tables = $5; $$->location = @4; } - | TABLES IN_P SCHEMA CURRENT_SCHEMA + | TABLES IN_P SCHEMA CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_CUR_SCHEMA; + $$->except_tables = $5; $$->location = @4; } - | ColId opt_column_list OptWhereClause + | ColId opt_column_list OptWhereClause opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $4; /* * If either a row filter or column list is specified, create * a PublicationTable object. @@ -11402,10 +11406,11 @@ PublicationObjSpec: $$->pubtable->columns = $2; $$->pubtable->whereClause = $3; } - | CURRENT_SCHEMA + | CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $2; $$->location = @1; } ; @@ -20867,6 +20872,8 @@ preprocess_pub_all_objtype_list(List *all_objects_list, List **pubobjects, /* * Process pubobjspec_list to check for errors in any of the objects and * convert PUBLICATIONOBJ_CONTINUATION into appropriate PublicationObjSpecType. + * Also flattens except_tables from TABLES IN SCHEMA nodes into the list so + * that ObjectsInPublicationToOids() sees them as top-level EXCEPT_TABLE entries. */ static void preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) @@ -20895,6 +20902,13 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLE) { + /* EXCEPT is not valid for table objects */ + if (pubobj->except_tables != NIL) + ereport(ERROR, + errcode(ERRCODE_SYNTAX_ERROR), + errmsg("EXCEPT is not allowed for TABLE publication objects"), + parser_errposition(pubobj->location)); + /* relation name or pubtable must be set for this type of object */ if (!pubobj->name && !pubobj->pubtable) ereport(ERROR, @@ -20943,6 +20957,36 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) errcode(ERRCODE_SYNTAX_ERROR), errmsg("invalid schema name"), parser_errposition(pubobj->location)); + + /* + * For TABLES_IN_SCHEMA, qualify unqualified EXCEPT table names + * with the parent schema and reject cross-schema entries at parse + * time, then flatten into the top-level list. + * + * For TABLES_IN_CUR_SCHEMA the schema name is not yet known, so + * skip both steps here; ObjectsInPublicationToOids() will + * qualify names and validate schema membership at execution time. + */ + if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLES_IN_SCHEMA) + { + foreach_ptr(PublicationObjSpec, eobj, pubobj->except_tables) + { + const char *eobj_schemaname = eobj->pubtable->relation->schemaname; + const char *eobj_relname = eobj->pubtable->relation->relname; + + if (eobj_schemaname == NULL) + eobj->pubtable->relation->schemaname = pubobj->name; + else if (strcmp(eobj_schemaname, pubobj->name) != 0) + ereport(ERROR, + errcode(ERRCODE_INVALID_OBJECT_DEFINITION), + errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", + quote_qualified_identifier(eobj_schemaname, eobj_relname), + pubobj->name), + parser_errposition(eobj->location)); + } + pubobjspec_list = list_concat(pubobjspec_list, pubobj->except_tables); + pubobj->except_tables = NIL; + } } prevobjtype = pubobj->pubobjtype; diff --git a/src/backend/replication/pgoutput/pgoutput.c b/src/backend/replication/pgoutput/pgoutput.c index 4ecfcbff7ab..1ed55bc7eea 100644 --- a/src/backend/replication/pgoutput/pgoutput.c +++ b/src/backend/replication/pgoutput/pgoutput.c @@ -2280,10 +2280,36 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) } } - if (list_member_oid(pubids, pub->oid) || - list_member_oid(schemaPubids, pub->oid) || - ancestor_published) + if (list_member_oid(pubids, pub->oid) || ancestor_published) publish = true; + else if (list_member_oid(schemaPubids, pub->oid)) + { + Oid root_relid; + bool root_is_except = false; + + /* + * schemaPubids is the list of publications that include + * relid's own schema, independent of the ancestor walk + * above -- a partition can live in a different schema + * than its root. Still need to check for exclusion here, + * using the top-most ancestor since only a root + * (non-partition) table can appear in an EXCEPT clause. + */ + if (am_partition) + { + List *ancestors = get_partition_ancestors(relid); + + root_relid = llast_oid(ancestors); + list_free(ancestors); + } + else + root_relid = relid; + + CheckPublicationRelEntry(pub->oid, root_relid, &root_is_except); + + if (!root_is_except) + publish = true; + } } /* diff --git a/src/backend/utils/cache/relcache.c b/src/backend/utils/cache/relcache.c index 19c4ff6e75e..b14de79d918 100644 --- a/src/backend/utils/cache/relcache.c +++ b/src/backend/utils/cache/relcache.c @@ -5847,16 +5847,32 @@ RelationBuildPublicationDesc(Relation relation, PublicationDesc *pubdesc) /* Fetch the publication membership info. */ puboids = GetRelationIncludedPublications(relid); schemaid = RelationGetNamespace(relation); - puboids = list_concat_unique_oid(puboids, GetSchemaPublications(schemaid)); if (relation->rd_rel->relispartition) { - Oid last_ancestor_relid; - - /* Add publications that the ancestors are in too. */ ancestors = get_partition_ancestors(relid); - last_ancestor_relid = llast_oid(ancestors); + /* ancestors is NIL for a partition with a pending DETACH CONCURRENTLY. */ + if (ancestors != NIL) + exceptpuboids = GetRelationExcludedPublications(llast_oid(ancestors)); + } + else + exceptpuboids = GetRelationExcludedPublications(relid); + + /* + * Subtract exceptpuboids from the schema-publication contribution so that + * a relation EXCEPT'd from a schema publication does not inherit that + * publication's pubactions. Without this filter, + * CheckCmdReplicaIdentity() would demand REPLICA IDENTITY for + * UPDATE/DELETE even on a explicitly excluded table. + */ + puboids = list_concat_unique_oid(puboids, + list_difference_oid(GetSchemaPublications(schemaid), + exceptpuboids)); + + if (relation->rd_rel->relispartition) + { + /* Add publications that the ancestors are in too. */ foreach(lc, ancestors) { Oid ancestor = lfirst_oid(lc); @@ -5865,23 +5881,9 @@ RelationBuildPublicationDesc(Relation relation, PublicationDesc *pubdesc) GetRelationIncludedPublications(ancestor)); schemaid = get_rel_namespace(ancestor); puboids = list_concat_unique_oid(puboids, - GetSchemaPublications(schemaid)); + list_difference_oid(GetSchemaPublications(schemaid), + exceptpuboids)); } - - /* - * Only the top-most ancestor can appear in the EXCEPT clause. - * Therefore, for a partition, exclusion must be evaluated at the - * top-most ancestor. - */ - exceptpuboids = GetRelationExcludedPublications(last_ancestor_relid); - } - else - { - /* - * For a regular table or a root partitioned table, check exclusion on - * table itself. - */ - exceptpuboids = GetRelationExcludedPublications(relid); } alltablespuboids = GetAllTablesPublications(); diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c index a2f09c26369..39886f85e6a 100644 --- a/src/bin/psql/describe.c +++ b/src/bin/psql/describe.c @@ -6838,6 +6838,24 @@ describePublications(const char *pattern) if (!addFooterToPublicationDesc(&buf, _("Tables from schemas:"), true, &cont)) goto error_return; + + if (pset.sversion >= 200000) + { + /* + * Get tables in the EXCEPT clause for this schema + * publication. + */ + printfPQExpBuffer(&buf, + "SELECT concat(c.relnamespace::regnamespace, '.', c.relname)\n" + "FROM pg_catalog.pg_class c\n" + " JOIN pg_catalog.pg_publication_rel pr ON c.oid = pr.prrelid\n" + "WHERE pr.prpubid = '%s'\n" + " AND pr.prexcept\n" + "ORDER BY 1", pubid); + if (!addFooterToPublicationDesc(&buf, _("Except tables:"), + true, &cont)) + goto error_return; + } } } else diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index 1cacc8c3ea2..7d8b4504194 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -1065,6 +1065,24 @@ static const SchemaQuery Query_for_trigger_of_table = { "SELECT nspname FROM pg_catalog.pg_namespace "\ " WHERE nspname LIKE '%s'" +#define Query_for_list_of_tables_in_schema \ +"SELECT n.nspname || '.' || c.relname "\ +" FROM pg_catalog.pg_class c "\ +" JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "\ +" WHERE c.relkind IN (" CppAsString2(RELKIND_RELATION) ", " \ + CppAsString2(RELKIND_PARTITIONED_TABLE) ") "\ +" AND (n.nspname || '.' || c.relname) LIKE '%s' "\ +" AND n.nspname = '%s'" + +#define Query_for_list_of_tables_in_current_schema \ +"SELECT c.relname "\ +" FROM pg_catalog.pg_class c "\ +" JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "\ +" WHERE c.relkind IN (" CppAsString2(RELKIND_RELATION) ", " \ + CppAsString2(RELKIND_PARTITIONED_TABLE) ") "\ +" AND c.relname LIKE '%s' "\ +" AND n.nspname = pg_catalog.current_schema()" + /* Use COMPLETE_WITH_QUERY_VERBATIM with these queries for GUC names: */ #define Query_for_list_of_alter_system_set_vars \ "SELECT pg_catalog.lower(name) FROM pg_catalog.pg_settings "\ @@ -3774,8 +3792,21 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); - else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && (!ends_with(prev_wd, ','))) - COMPLETE_WITH("WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE", "WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* Complete "CREATE PUBLICATION <name> [...] WITH" */ else if (Matches("CREATE", "PUBLICATION", MatchAnyN, "WITH", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/include/catalog/pg_publication.h b/src/include/catalog/pg_publication.h index 89b4bb14f62..d241b781ccc 100644 --- a/src/include/catalog/pg_publication.h +++ b/src/include/catalog/pg_publication.h @@ -192,6 +192,7 @@ extern List *GetPubPartitionOptionRelations(List *result, Oid relid); extern Oid GetTopMostAncestorInPublication(Oid puboid, List *ancestors, int *ancestor_level); +extern bool CheckPublicationRelEntry(Oid pubid, Oid relid, bool *is_except); extern bool is_publishable_relation(Relation rel); extern bool is_schema_publication(Oid pubid); diff --git a/src/include/commands/publicationcmds.h b/src/include/commands/publicationcmds.h index 4cf45c17cc5..fb1703aa675 100644 --- a/src/include/commands/publicationcmds.h +++ b/src/include/commands/publicationcmds.h @@ -27,6 +27,8 @@ extern void AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt); extern void RemovePublicationById(Oid pubid); extern void RemovePublicationRelById(Oid proid); extern void RemovePublicationSchemaById(Oid psoid); +extern void RemoveSchemaPubExceptForRel(Oid relid, Oid oldNspOid, + Oid newNspOid); extern ObjectAddress AlterPublicationOwner(const char *name, Oid newOwnerId); extern void AlterPublicationOwner_oid(Oid pubid, Oid newOwnerId); diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h index 5c8f9a07b62..0cccb4393c2 100644 --- a/src/include/nodes/parsenodes.h +++ b/src/include/nodes/parsenodes.h @@ -4530,6 +4530,8 @@ typedef struct PublicationObjSpec PublicationObjSpecType pubobjtype; /* type of this publication object */ char *name; PublicationTable *pubtable; + List *except_tables; /* tables specified in the EXCEPT clause (for + * TABLES IN SCHEMA) */ ParseLoc location; /* token location, or -1 if unknown */ } PublicationObjSpec; diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 9c6386d518a..11325bf80b9 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -279,6 +279,12 @@ CREATE PUBLICATION testpub_foralltables_excepttable2 FOR ALL TABLES EXCEPT (test ERROR: syntax error at or near "testpub_tbl1" LINE 1: ..._foralltables_excepttable2 FOR ALL TABLES EXCEPT (testpub_tb... ^ +-- fail - EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testpub_tbl3); +ERROR: EXCEPT is not allowed for TABLE publication objects +LINE 2: FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testp... + ^ --------------------------------------------- -- SET ALL TABLES/SEQUENCES --------------------------------------------- @@ -473,13 +479,161 @@ CREATE TABLE tab_main (a int) PARTITION BY RANGE(a); -- Attaching a partition is not allowed if the partitioned table appears in a -- publication's EXCEPT clause. ALTER TABLE tab_main ATTACH PARTITION testpub_root FOR VALUES FROM (0) TO (200); -ERROR: cannot attach table "testpub_root" as partition because it is referenced in publication "testpub8" EXCEPT clause +ERROR: cannot attach table "testpub_root" as partition because it is named in EXCEPT clause of publication "testpub8" DETAIL: The publication EXCEPT clause cannot contain tables that are partitions. -HINT: Change the publication's EXCEPT clause using ALTER PUBLICATION ... SET ALL TABLES. +HINT: Change the EXCEPT clause using ALTER PUBLICATION ... SET ALL TABLES ... EXCEPT. RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Create same-named tables in public to verify unqualified EXCEPT entries +-- are qualified with the named schema, not public +CREATE TABLE testpub_nopk (foo int, bar int); +CREATE TABLE testpub_tbl_s1 (a int primary key, b text); +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + Publication testpub_schema_except1 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- Exclude multiple tables using unqualified names; same-named tables exist in +-- public to confirm unqualified names resolve to pub_test, not public +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + Publication testpub_schema_except2 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_nopk" + "pub_test.testpub_tbl_s1" + +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testp... + ^ +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); +ERROR: table "pub_test.testpub_tbl_s1" in EXCEPT clause does not belong to schema "public" +LINE 2: ...R TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.t... + ^ +-- Multiple schemas each with their own EXCEPT clause +CREATE PUBLICATION testpub_schema_except_multi + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_schema_except_multi + Publication testpub_schema_except_multi + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- ALTER TABLE ... SET SCHEMA on a table excluded by a schema publication: +-- the schema-scoped exclusion is no longer meaningful once the table moves +-- out of its schema, so the exclusion is auto-removed. +CREATE PUBLICATION testpub_schema_except_setsch + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_schema_except_setsch + Publication testpub_schema_except_setsch + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s2" + +ALTER TABLE pub_test.testpub_tbl_s2 SET SCHEMA public; +\dRp+ testpub_schema_except_setsch + Publication testpub_schema_except_setsch + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + +DROP PUBLICATION testpub_schema_except_setsch; +-- Restore for further tests +ALTER TABLE public.testpub_tbl_s2 SET SCHEMA pub_test; +-- fail: table appears in both the explicit table list and the EXCEPT clause +CREATE PUBLICATION testpub_except_conflict + FOR TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot be both published and excluded +-- fail: nonexistent table in EXCEPT clause +CREATE PUBLICATION testpub_except_norel + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- fail: partition cannot appear in EXCEPT clause; only root tables are allowed +CREATE TABLE pub_test.testpub_parted_s (a int) PARTITION BY LIST (a); +CREATE TABLE pub_test.testpub_part_s PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (1); +CREATE PUBLICATION testpub_except_partition + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); +ERROR: cannot specify relation "pub_test.testpub_part_s" in the publication EXCEPT clause +DETAIL: This operation is not supported for individual partitions. +-- fail: TABLE keyword is required for the first entry in the EXCEPT clause +CREATE PUBLICATION testpub_except_nokw + FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +ERROR: syntax error at or near "testpub_nopk" +LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + ^ +-- fail: ADD TABLE for a partition is rejected when a partition ancestor +-- is currently in the publication's EXCEPT list. +CREATE PUBLICATION testpub_except_ancestor + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ALTER PUBLICATION testpub_except_ancestor ADD TABLE pub_test.testpub_part_s; +ERROR: cannot add partition "pub_test.testpub_part_s" to publication "testpub_except_ancestor" +DETAIL: Partition root "pub_test.testpub_parted_s" is named in the publication's EXCEPT clause for schema "pub_test". +HINT: Change the EXCEPT clause using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT. +DROP PUBLICATION testpub_except_ancestor; +-- fail: same contradiction (explicit partition + EXCEPT-ed ancestor), but +-- given in a single statement instead of two separate ones +CREATE PUBLICATION testpub_except_ancestor_same_create + FOR TABLE pub_test.testpub_part_s, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ERROR: partition "pub_test.testpub_part_s" cannot be both published and excluded +DETAIL: Partition root "pub_test.testpub_parted_s" is named in the publication's EXCEPT clause for schema "pub_test". +-- fail: same contradiction as above, but the partition lives in a different +-- schema (public) than its EXCEPT-ed root (pub_test) +CREATE TABLE public.testpub_part_s2 PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (2); +CREATE PUBLICATION testpub_except_ancestor_cross_schema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s), + TABLE public.testpub_part_s2; +ERROR: partition "public.testpub_part_s2" cannot be both published and excluded +DETAIL: Partition root "pub_test.testpub_parted_s" is named in the publication's EXCEPT clause for schema "pub_test". +DROP TABLE public.testpub_part_s2; +-- Cleanup +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP TABLE pub_test.testpub_parted_s CASCADE; +DROP TABLE testpub_nopk, testpub_tbl_s1; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +--------------------------------------------- +-- Tests for publications with SEQUENCES +--------------------------------------------- CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; -- FOR ALL SEQUENCES @@ -1970,6 +2124,27 @@ ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b); ERROR: column specification not allowed for schema LINE 1: ...TION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b)... ^ +-- EXCEPT clause with CURRENT_SCHEMA: cross-schema entry must be rejected +SET search_path = pub_test1; +-- qualified name from wrong schema -> error +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.tbl1); +ERROR: table "pub_test2.tbl1" in EXCEPT clause does not belong to schema "pub_test1" +-- unqualified name implicitly qualified with current schema (pub_test1.tbl) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl); +RESET client_min_messages; +\dRp+ testpub_cursch_except + Publication testpub_cursch_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test1" +Except tables: + "pub_test1.tbl" + +DROP PUBLICATION testpub_cursch_except; +RESET search_path; -- cleanup pub_test1 schema for invalidation tests ALTER PUBLICATION testpub2_forschema DROP TABLES IN SCHEMA pub_test1; DROP PUBLICATION testpub3_forschema, testpub4_forschema, testpub5_forschema, testpub6_forschema, testpub_fortable; @@ -2321,6 +2496,7 @@ DROP ROLE regress_publication_user_dummy; -- Test pg_get_publication_tables(text[], oid) function CREATE SCHEMA gpt_test_sch; CREATE TABLE gpt_test_sch.tbl_sch (id int); +CREATE TABLE gpt_test_sch.tbl_sch2 (id int); CREATE TABLE tbl_normal (id int); CREATE TABLE tbl_parent (id1 int, id2 int, id3 int) PARTITION BY RANGE (id1); CREATE TABLE tbl_part1 PARTITION OF tbl_parent FOR VALUES FROM (1) TO (10); @@ -2331,6 +2507,7 @@ CREATE PUBLICATION pub_all_no_viaroot FOR ALL TABLES WITH (publish_via_partition CREATE PUBLICATION pub_all_except FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = true); CREATE PUBLICATION pub_all_except_no_viaroot FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_schema FOR TABLES IN SCHEMA gpt_test_sch; +CREATE PUBLICATION pub_schema_except FOR TABLES IN SCHEMA gpt_test_sch EXCEPT (TABLE gpt_test_sch.tbl_sch); CREATE PUBLICATION pub_normal FOR TABLE tbl_normal WHERE (id < 10); CREATE PUBLICATION pub_part_leaf FOR TABLE tbl_part1 WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_part_parent FOR TABLE tbl_parent (id1, id2) WHERE (id1 = 10) WITH (publish_via_partition_root = true); @@ -2482,6 +2659,44 @@ SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_part1'); -- no r ---------+---------+-------+------ (0 rows) +-- test for EXCEPT clause with schema publication +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch'); -- no result (excluded) + pubname | relname | attrs | qual +---------+---------+-------+------ +(0 rows) + +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch2'); -- one row (included via schema) + pubname | relname | attrs | qual +-------------------+----------+-------+------ + pub_schema_except | tbl_sch2 | 1 | +(1 row) + +-- test for EXCEPT clause with schema publication, where the excluded root's +-- partition lives in a different schema that is separately, fully included +-- (no EXCEPT) in the same publication. The root's exclusion must cascade to +-- the partition regardless of the partition's own schema membership. +CREATE SCHEMA gpt_cross_sch1; +CREATE SCHEMA gpt_cross_sch2; +CREATE TABLE gpt_cross_sch1.croot (id int) PARTITION BY RANGE (id); +CREATE TABLE gpt_cross_sch2.cpart1 PARTITION OF gpt_cross_sch1.croot FOR VALUES FROM (1) TO (10); +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION pub_cross_schema_except FOR TABLES IN SCHEMA gpt_cross_sch1 EXCEPT (TABLE gpt_cross_sch1.croot), TABLES IN SCHEMA gpt_cross_sch2; +RESET client_min_messages; +SELECT * FROM test_gpt(ARRAY['pub_cross_schema_except'], 'gpt_cross_sch1.croot'); -- no result (excluded) + pubname | relname | attrs | qual +---------+---------+-------+------ +(0 rows) + +-- no result (excluded via cascading root exclusion, even though cpart1's own +-- schema gpt_cross_sch2 is separately, fully included with no EXCEPT) +SELECT * FROM test_gpt(ARRAY['pub_cross_schema_except'], 'gpt_cross_sch2.cpart1'); + pubname | relname | attrs | qual +---------+---------+-------+------ +(0 rows) + +DROP PUBLICATION pub_cross_schema_except; +DROP TABLE gpt_cross_sch2.cpart1, gpt_cross_sch1.croot; +DROP SCHEMA gpt_cross_sch1, gpt_cross_sch2; -- two rows with different row filter SELECT * FROM test_gpt(ARRAY['pub_all', 'pub_normal'], 'tbl_normal'); pubname | relname | attrs | qual @@ -2534,6 +2749,7 @@ DROP PUBLICATION pub_all_no_viaroot; DROP PUBLICATION pub_all_except; DROP PUBLICATION pub_all_except_no_viaroot; DROP PUBLICATION pub_schema; +DROP PUBLICATION pub_schema_except; DROP PUBLICATION pub_normal; DROP PUBLICATION pub_part_leaf; DROP PUBLICATION pub_part_parent; @@ -2542,7 +2758,9 @@ DROP PUBLICATION pub_part_parent_child; DROP VIEW gpt_test_view; DROP TABLE tbl_normal, tbl_parent, tbl_part1; DROP SCHEMA gpt_test_sch CASCADE; -NOTICE: drop cascades to table gpt_test_sch.tbl_sch +NOTICE: drop cascades to 2 other objects +DETAIL: drop cascades to table gpt_test_sch.tbl_sch +drop cascades to table gpt_test_sch.tbl_sch2 -- stage objects for pg_dump tests CREATE SCHEMA pubme CREATE TABLE t0 (c int, d int) CREATE TABLE t1 (c int); CREATE SCHEMA pubme2 CREATE TABLE t0 (c int, d int); diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index fac54b02e27..4a86d699e84 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -125,6 +125,9 @@ CREATE PUBLICATION testpub_foralltables_excepttable1 FOR ALL TABLES EXCEPT (TABL \d testpub_tbl1 -- fail - first table in the EXCEPT list should use TABLE keyword CREATE PUBLICATION testpub_foralltables_excepttable2 FOR ALL TABLES EXCEPT (testpub_tbl1, testpub_tbl2); +-- fail - EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testpub_tbl3); --------------------------------------------- -- SET ALL TABLES/SEQUENCES @@ -222,7 +225,104 @@ RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Create same-named tables in public to verify unqualified EXCEPT entries +-- are qualified with the named schema, not public +CREATE TABLE testpub_nopk (foo int, bar int); +CREATE TABLE testpub_tbl_s1 (a int primary key, b text); + +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + +-- Exclude multiple tables using unqualified names; same-named tables exist in +-- public to confirm unqualified names resolve to pub_test, not public +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); + +-- Multiple schemas each with their own EXCEPT clause +CREATE PUBLICATION testpub_schema_except_multi + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_schema_except_multi + +-- ALTER TABLE ... SET SCHEMA on a table excluded by a schema publication: +-- the schema-scoped exclusion is no longer meaningful once the table moves +-- out of its schema, so the exclusion is auto-removed. +CREATE PUBLICATION testpub_schema_except_setsch + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_schema_except_setsch +ALTER TABLE pub_test.testpub_tbl_s2 SET SCHEMA public; +\dRp+ testpub_schema_except_setsch +DROP PUBLICATION testpub_schema_except_setsch; +-- Restore for further tests +ALTER TABLE public.testpub_tbl_s2 SET SCHEMA pub_test; + +-- fail: table appears in both the explicit table list and the EXCEPT clause +CREATE PUBLICATION testpub_except_conflict + FOR TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: nonexistent table in EXCEPT clause +CREATE PUBLICATION testpub_except_norel + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- fail: partition cannot appear in EXCEPT clause; only root tables are allowed +CREATE TABLE pub_test.testpub_parted_s (a int) PARTITION BY LIST (a); +CREATE TABLE pub_test.testpub_part_s PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (1); +CREATE PUBLICATION testpub_except_partition + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); + +-- fail: TABLE keyword is required for the first entry in the EXCEPT clause +CREATE PUBLICATION testpub_except_nokw + FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + +-- fail: ADD TABLE for a partition is rejected when a partition ancestor +-- is currently in the publication's EXCEPT list. +CREATE PUBLICATION testpub_except_ancestor + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ALTER PUBLICATION testpub_except_ancestor ADD TABLE pub_test.testpub_part_s; +DROP PUBLICATION testpub_except_ancestor; + +-- fail: same contradiction (explicit partition + EXCEPT-ed ancestor), but +-- given in a single statement instead of two separate ones +CREATE PUBLICATION testpub_except_ancestor_same_create + FOR TABLE pub_test.testpub_part_s, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); + +-- fail: same contradiction as above, but the partition lives in a different +-- schema (public) than its EXCEPT-ed root (pub_test) +CREATE TABLE public.testpub_part_s2 PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (2); +CREATE PUBLICATION testpub_except_ancestor_cross_schema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s), + TABLE public.testpub_part_s2; +DROP TABLE public.testpub_part_s2; + +-- Cleanup +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP TABLE pub_test.testpub_parted_s CASCADE; +DROP TABLE testpub_nopk, testpub_tbl_s1; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; + +--------------------------------------------- +-- Tests for publications with SEQUENCES +--------------------------------------------- CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; @@ -1194,6 +1294,18 @@ ALTER PUBLICATION testpub1_forschema SET TABLES IN SCHEMA pub_test1, pub_test1; ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo (a, b); ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b); +-- EXCEPT clause with CURRENT_SCHEMA: cross-schema entry must be rejected +SET search_path = pub_test1; +-- qualified name from wrong schema -> error +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.tbl1); +-- unqualified name implicitly qualified with current schema (pub_test1.tbl) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl); +RESET client_min_messages; +\dRp+ testpub_cursch_except +DROP PUBLICATION testpub_cursch_except; +RESET search_path; + -- cleanup pub_test1 schema for invalidation tests ALTER PUBLICATION testpub2_forschema DROP TABLES IN SCHEMA pub_test1; DROP PUBLICATION testpub3_forschema, testpub4_forschema, testpub5_forschema, testpub6_forschema, testpub_fortable; @@ -1448,6 +1560,7 @@ DROP ROLE regress_publication_user_dummy; -- Test pg_get_publication_tables(text[], oid) function CREATE SCHEMA gpt_test_sch; CREATE TABLE gpt_test_sch.tbl_sch (id int); +CREATE TABLE gpt_test_sch.tbl_sch2 (id int); CREATE TABLE tbl_normal (id int); CREATE TABLE tbl_parent (id1 int, id2 int, id3 int) PARTITION BY RANGE (id1); CREATE TABLE tbl_part1 PARTITION OF tbl_parent FOR VALUES FROM (1) TO (10); @@ -1459,6 +1572,7 @@ CREATE PUBLICATION pub_all_no_viaroot FOR ALL TABLES WITH (publish_via_partition CREATE PUBLICATION pub_all_except FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = true); CREATE PUBLICATION pub_all_except_no_viaroot FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_schema FOR TABLES IN SCHEMA gpt_test_sch; +CREATE PUBLICATION pub_schema_except FOR TABLES IN SCHEMA gpt_test_sch EXCEPT (TABLE gpt_test_sch.tbl_sch); CREATE PUBLICATION pub_normal FOR TABLE tbl_normal WHERE (id < 10); CREATE PUBLICATION pub_part_leaf FOR TABLE tbl_part1 WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_part_parent FOR TABLE tbl_parent (id1, id2) WHERE (id1 = 10) WITH (publish_via_partition_root = true); @@ -1515,6 +1629,32 @@ SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'gpt_test_sch.tbl_sch SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_parent'); -- no result (excluded) SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_part1'); -- no result +-- test for EXCEPT clause with schema publication +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch'); -- no result (excluded) +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch2'); -- one row (included via schema) + +-- test for EXCEPT clause with schema publication, where the excluded root's +-- partition lives in a different schema that is separately, fully included +-- (no EXCEPT) in the same publication. The root's exclusion must cascade to +-- the partition regardless of the partition's own schema membership. +CREATE SCHEMA gpt_cross_sch1; +CREATE SCHEMA gpt_cross_sch2; +CREATE TABLE gpt_cross_sch1.croot (id int) PARTITION BY RANGE (id); +CREATE TABLE gpt_cross_sch2.cpart1 PARTITION OF gpt_cross_sch1.croot FOR VALUES FROM (1) TO (10); + +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION pub_cross_schema_except FOR TABLES IN SCHEMA gpt_cross_sch1 EXCEPT (TABLE gpt_cross_sch1.croot), TABLES IN SCHEMA gpt_cross_sch2; +RESET client_min_messages; + +SELECT * FROM test_gpt(ARRAY['pub_cross_schema_except'], 'gpt_cross_sch1.croot'); -- no result (excluded) +-- no result (excluded via cascading root exclusion, even though cpart1's own +-- schema gpt_cross_sch2 is separately, fully included with no EXCEPT) +SELECT * FROM test_gpt(ARRAY['pub_cross_schema_except'], 'gpt_cross_sch2.cpart1'); + +DROP PUBLICATION pub_cross_schema_except; +DROP TABLE gpt_cross_sch2.cpart1, gpt_cross_sch1.croot; +DROP SCHEMA gpt_cross_sch1, gpt_cross_sch2; + -- two rows with different row filter SELECT * FROM test_gpt(ARRAY['pub_all', 'pub_normal'], 'tbl_normal'); @@ -1543,6 +1683,7 @@ DROP PUBLICATION pub_all_no_viaroot; DROP PUBLICATION pub_all_except; DROP PUBLICATION pub_all_except_no_viaroot; DROP PUBLICATION pub_schema; +DROP PUBLICATION pub_schema_except; DROP PUBLICATION pub_normal; DROP PUBLICATION pub_part_leaf; DROP PUBLICATION pub_part_parent; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 8c58d282eee..c4e4efafec8 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -24,14 +24,17 @@ my $result; sub test_except_root_partition { - my ($pubviaroot) = @_; + my ($pubviaroot, $pubsql) = @_; + $pubsql //= + "CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1)"; + $pubsql .= " WITH (publish_via_partition_root = $pubviaroot)"; # If the root partitioned table is in the EXCEPT clause, all its # partitions are excluded from publication, regardless of the # publish_via_partition_root setting. $node_publisher->safe_psql( 'postgres', qq( - CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1) WITH (publish_via_partition_root = $pubviaroot); + $pubsql; INSERT INTO root1 VALUES (1), (101); )); $node_subscriber->safe_psql('postgres', @@ -223,6 +226,206 @@ $node_subscriber->safe_psql( test_except_root_partition('false'); test_except_root_partition('true'); +# Same validation using TABLES IN SCHEMA instead of FOR ALL TABLES. +my $schema_pub = + "CREATE PUBLICATION tap_pub_part FOR TABLES IN SCHEMA public EXCEPT (TABLE public.root1)"; +test_except_root_partition('false', $schema_pub); +test_except_root_partition('true', $schema_pub); + +# ============================================ +# EXCEPT test cases for TABLES IN SCHEMA +# ============================================ + +# Create a dedicated schema with two tables: one to be published and one to be +# excluded. Also create inherited tables to verify ONLY semantics. +$node_publisher->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_published AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.tab_excluded AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.parent (a int); + CREATE TABLE sch1.child (b int) INHERITS (sch1.parent); +)); + +$node_subscriber->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_published (a int); + CREATE TABLE sch1.tab_excluded (a int); + CREATE TABLE sch1.parent (a int); + CREATE TABLE sch1.child (b int) INHERITS (sch1.parent); +)); + +# Basic test: initial sync respects EXCEPT. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_excluded)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: initial sync copies included table'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: initial sync skips excluded table'); + +# DML: only the included table should be replicated. +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (6); + INSERT INTO sch1.tab_excluded VALUES (6); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(6), + 'TABLES IN SCHEMA EXCEPT: DML on included table is replicated'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: DML on excluded table is not replicated'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Inherited tables: excluding the parent (without ONLY) also excludes the child. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.parent)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.child VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.child"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: excluding parent (without ONLY) also excludes child' +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Test that EXCEPT (TABLE ONLY parent) excludes only the parent itself, not its +# child. Truncate child first so rows from the previous test are not copied by +# the initial table sync of the next subscription. +$node_publisher->safe_psql('postgres', 'TRUNCATE sch1.child'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE sch1.child'); +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE ONLY sch1.parent)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.child VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.child"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: ONLY parent in EXCEPT does not exclude child'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Cleanup schema tables before the multi-publication section. +$node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); +$node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); + +# ============================================ +# EXCEPT test cases for TABLES IN SCHEMA with a cross-schema partition +# ============================================ + +# A partition can live in a different schema than its partitioned root. If +# the root is excluded via EXCEPT under its own schema's clause, the +# exclusion must cascade to all its partitions, even when the partition's +# own schema is separately, fully included (no EXCEPT) in the same +# publication. +$node_publisher->safe_psql( + 'postgres', qq( + CREATE SCHEMA csch1; + CREATE SCHEMA csch2; + CREATE TABLE csch1.croot(a int) PARTITION BY RANGE(a); + CREATE TABLE csch2.cpart1 PARTITION OF csch1.croot FOR VALUES FROM (0) TO (100); + INSERT INTO csch1.croot VALUES (generate_series(1,5)); +)); + +$node_subscriber->safe_psql( + 'postgres', qq( + CREATE SCHEMA csch1; + CREATE SCHEMA csch2; + CREATE TABLE csch1.croot(a int); + CREATE TABLE csch2.cpart1(a int); +)); + +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION cross_sch_pub FOR TABLES IN SCHEMA csch1 EXCEPT (TABLE csch1.croot), TABLES IN SCHEMA csch2 WITH (publish_via_partition_root = false)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION cross_sch_sub CONNECTION '$publisher_connstr' PUBLICATION cross_sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'cross_sch_sub'); + +# Baseline: the root itself, pre-populated with rows before the subscription +# was created, is excluded by its own schema's EXCEPT clause -- initial sync +# must not have copied it. +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM csch1.croot"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: cross-schema partition root is excluded by initial sync' +); + +# Regression case: the partition's own schema (csch2) is separately, fully +# included with no EXCEPT, but the root's exclusion must still cascade to it +# -- initial sync must not have copied the pre-existing rows routed into this +# partition via the root. +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM csch2.cpart1"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: cross-schema partition is excluded by initial sync via cascading root exclusion' +); + +# Insert distinct, identifiable data directly into the partition and verify +# it is not replicated either. +$node_publisher->safe_psql('postgres', + "INSERT INTO csch2.cpart1 VALUES (generate_series(1,5))"); +$node_publisher->wait_for_catchup('cross_sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM csch1.croot"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: cross-schema partition root remains excluded after DML' +); +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM csch2.cpart1"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: cross-schema partition remains excluded after DML via cascading root exclusion' +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION cross_sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION cross_sch_pub'); +$node_publisher->safe_psql('postgres', 'DROP SCHEMA csch1, csch2 CASCADE'); +$node_subscriber->safe_psql('postgres', 'DROP SCHEMA csch1, csch2 CASCADE'); + # ============================================ # Test when a subscription is subscribing to multiple publications # ============================================ @@ -254,6 +457,7 @@ $node_publisher->safe_psql( DROP PUBLICATION tap_pub2; TRUNCATE tab1; )); +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_subscriber->safe_psql('postgres', qq(TRUNCATE tab1)); # OK when a table is excluded by pub1 EXCEPT clause, but it is included by pub2 -- 2.50.1 (Apple Git-155)
v23-0002-Restrict-conflicting-EXCEPT-lists-in-multi-schem.patch (application/octet-stream, 14.8K) download From 484b60f84fbd82719b274cf5f58bfbae542f36a5 Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Wed, 15 Jul 2026 21:18:51 +0530 Subject: [PATCH v23 2/5] Restrict conflicting EXCEPT lists in multi-schema publications Add ProcessSchemaExceptTables(), which errors if the same schema is mentioned more than once with EXCEPT, or both with and without EXCEPT. It also checks that a schema's EXCEPT clause only lists tables from that same schema. --- src/backend/commands/publicationcmds.c | 117 +++++++++++++++------- src/backend/parser/gram.y | 37 +------ src/test/regress/expected/publication.out | 38 +++++++ src/test/regress/sql/publication.sql | 31 ++++++ 4 files changed, 155 insertions(+), 68 deletions(-) diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index a789aa735c5..fe0c670c368 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -73,6 +73,10 @@ static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); static char defGetGeneratedColsOption(DefElem *def); static void CheckExceptNotInTableList(List *except_rels, List *explicitrelids); +static void ProcessSchemaExceptTables(Oid schemaid, List *except_tables, + ParseState *pstate, List **schemas, + List **schemas_with_except, + List **except_pubtables); static void @@ -177,6 +181,74 @@ parse_publication_options(ParseState *pstate, } } +/* + * Qualify unqualified EXCEPT table names with the given schema (rejecting + * any explicitly qualified with a different schema), and append them to + * *except_pubtables. + * + * Also rejects a schema being mentioned more than once with an EXCEPT + * clause, even if the EXCEPT clauses are identical — much like + * OpenTableList() rejects "FOR TABLE t1(a), t1(a)" despite the column + * lists matching. A schema can still be mentioned multiple times, just + * not more than once with EXCEPT. + * + * schemaid: OID of the schema for this TABLES IN SCHEMA mention. + * except_tables: the EXCEPT list (or NIL) attached to this mention. + * *schemas: accumulates all schema OIDs seen so far in this statement. + * *schemas_with_except: This is a subset of *schemas. Tracks which of + * the seen schemas of this statement had an EXCEPT clause. + * *except_pubtables: accumulates the (now schema-qualified) EXCEPT table + * entries across the whole statement. + */ +static void +ProcessSchemaExceptTables(Oid schemaid, List *except_tables, + ParseState *pstate, List **schemas, + List **schemas_with_except, List **except_pubtables) +{ + char *schema_name = get_namespace_name(schemaid); + bool schema_has_except = (except_tables != NIL); + + /* + * A repeating schema is only a problem if this mention has EXCEPT, or an + * earlier mention of the same schema did. + */ + if (list_member_oid(*schemas, schemaid)) + { + if (schema_has_except || + list_member_oid(*schemas_with_except, schemaid)) + ereport(ERROR, + errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("conflicting or redundant EXCEPT clauses for schema \"%s\"", + schema_name)); + } + + if (schema_has_except) + *schemas_with_except = lappend_oid(*schemas_with_except, schemaid); + + /* Filter out duplicates if the user specifies "sch1, sch1" */ + *schemas = list_append_unique_oid(*schemas, schemaid); + + if (!schema_has_except) + return; + + foreach_ptr(PublicationObjSpec, eobj, except_tables) + { + RangeVar *relation = eobj->pubtable->relation; + + if (relation->schemaname == NULL) + relation->schemaname = schema_name; + else if (strcmp(relation->schemaname, schema_name) != 0) + ereport(ERROR, + errcode(ERRCODE_INVALID_OBJECT_DEFINITION), + errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", + quote_qualified_identifier(relation->schemaname, relation->relname), + schema_name), + parser_errposition(pstate, eobj->location)); + + *except_pubtables = lappend(*except_pubtables, eobj->pubtable); + } +} + /* * Convert the PublicationObjSpecType list into schema oid list and * PublicationTable list. @@ -187,6 +259,7 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, { ListCell *cell; PublicationObjSpec *pubobj; + List *schemas_with_except = NIL; if (!pubobjspec_list) return; @@ -211,8 +284,10 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, case PUBLICATIONOBJ_TABLES_IN_SCHEMA: schemaid = get_namespace_oid(pubobj->name, false); - /* Filter out duplicates if user specifies "sch1, sch1" */ - *schemas = list_append_unique_oid(*schemas, schemaid); + ProcessSchemaExceptTables(schemaid, pubobj->except_tables, + pstate, schemas, + &schemas_with_except, + except_pubtables); break; case PUBLICATIONOBJ_TABLES_IN_CUR_SCHEMA: search_path = fetch_search_path(false); @@ -224,40 +299,10 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, schemaid = linitial_oid(search_path); list_free(search_path); - /* Filter out duplicates if user specifies "sch1, sch1" */ - *schemas = list_append_unique_oid(*schemas, schemaid); - - /* - * Qualify unqualified EXCEPT table names with the resolved - * current schema and reject any explicitly cross-schema - * entries. This mirrors the parse-time handling done for - * TABLES_IN_SCHEMA in preprocess_pubobj_list(), deferred here - * because CURRENT_SCHEMA is not known until execution time. - */ - if (pubobj->except_tables != NIL) - { - char *cur_schema_name = get_namespace_name(schemaid); - - foreach_ptr(PublicationObjSpec, eobj, pubobj->except_tables) - { - const char *eobj_schemaname = - eobj->pubtable->relation->schemaname; - const char *eobj_relname = - eobj->pubtable->relation->relname; - - if (eobj_schemaname == NULL) - eobj->pubtable->relation->schemaname = cur_schema_name; - else if (strcmp(eobj_schemaname, cur_schema_name) != 0) - ereport(ERROR, - errcode(ERRCODE_INVALID_OBJECT_DEFINITION), - errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", - quote_qualified_identifier(eobj_schemaname, eobj_relname), - cur_schema_name)); - - *except_pubtables = lappend(*except_pubtables, - eobj->pubtable); - } - } + ProcessSchemaExceptTables(schemaid, pubobj->except_tables, + pstate, schemas, + &schemas_with_except, + except_pubtables); break; default: /* shouldn't happen */ diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y index 18826a74b77..14520a5ccab 100644 --- a/src/backend/parser/gram.y +++ b/src/backend/parser/gram.y @@ -20872,8 +20872,11 @@ preprocess_pub_all_objtype_list(List *all_objects_list, List **pubobjects, /* * Process pubobjspec_list to check for errors in any of the objects and * convert PUBLICATIONOBJ_CONTINUATION into appropriate PublicationObjSpecType. - * Also flattens except_tables from TABLES IN SCHEMA nodes into the list so - * that ObjectsInPublicationToOids() sees them as top-level EXCEPT_TABLE entries. + * + * The except_tables attached to TABLES IN SCHEMA nodes are left in place here; + * ObjectsInPublicationToOids() qualifies their names, validates schema + * membership, and merges the qualified tables into its except_pubtables + * output list once the schema OID is known. */ static void preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) @@ -20957,36 +20960,6 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) errcode(ERRCODE_SYNTAX_ERROR), errmsg("invalid schema name"), parser_errposition(pubobj->location)); - - /* - * For TABLES_IN_SCHEMA, qualify unqualified EXCEPT table names - * with the parent schema and reject cross-schema entries at parse - * time, then flatten into the top-level list. - * - * For TABLES_IN_CUR_SCHEMA the schema name is not yet known, so - * skip both steps here; ObjectsInPublicationToOids() will - * qualify names and validate schema membership at execution time. - */ - if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLES_IN_SCHEMA) - { - foreach_ptr(PublicationObjSpec, eobj, pubobj->except_tables) - { - const char *eobj_schemaname = eobj->pubtable->relation->schemaname; - const char *eobj_relname = eobj->pubtable->relation->relname; - - if (eobj_schemaname == NULL) - eobj->pubtable->relation->schemaname = pubobj->name; - else if (strcmp(eobj_schemaname, pubobj->name) != 0) - ereport(ERROR, - errcode(ERRCODE_INVALID_OBJECT_DEFINITION), - errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", - quote_qualified_identifier(eobj_schemaname, eobj_relname), - pubobj->name), - parser_errposition(eobj->location)); - } - pubobjspec_list = list_concat(pubobjspec_list, pubobj->except_tables); - pubobj->except_tables = NIL; - } } prevobjtype = pubobj->pubobjtype; diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 11325bf80b9..2c92186068f 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -552,6 +552,17 @@ Except tables: "pub_test.testpub_tbl_s1" "public.testpub_tbl1" +-- fail: same schema repeated with same EXCEPT clauses +CREATE PUBLICATION testpub_schema_except_conflict + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: conflicting or redundant EXCEPT clauses for schema "pub_test" +-- fail: same schema repeated with conflicting or no EXCEPT clauses +CREATE PUBLICATION testpub_schema_except_conflict2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2), + pub_test; +ERROR: conflicting or redundant EXCEPT clauses for schema "pub_test" -- ALTER TABLE ... SET SCHEMA on a table excluded by a schema publication: -- the schema-scoped exclusion is no longer meaningful once the table moves -- out of its schema, so the exclusion is auto-removed. @@ -2129,6 +2140,8 @@ SET search_path = pub_test1; -- qualified name from wrong schema -> error CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.tbl1); ERROR: table "pub_test2.tbl1" in EXCEPT clause does not belong to schema "pub_test1" +LINE 1: ...FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.... + ^ -- unqualified name implicitly qualified with current schema (pub_test1.tbl) SET client_min_messages = 'ERROR'; CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl); @@ -2144,6 +2157,31 @@ Except tables: "pub_test1.tbl" DROP PUBLICATION testpub_cursch_except; +-- succeeds: CURRENT_SCHEMA and pub_test1 (same schema) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_named_same + FOR TABLES IN SCHEMA CURRENT_SCHEMA, pub_test1; +RESET client_min_messages; +\dRp+ testpub_cursch_named_same + Publication testpub_cursch_named_same + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test1" + +DROP PUBLICATION testpub_cursch_named_same; +-- fail: CURRENT_SCHEMA and pub_test1 (same schema) have +-- conflicting EXCEPT clauses +CREATE PUBLICATION testpub_cursch_named_conflict + FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl), + pub_test1 EXCEPT (TABLE tbl1); +ERROR: conflicting or redundant EXCEPT clauses for schema "pub_test1" +-- fail: two CURRENT_SCHEMA mentions with conflicting EXCEPT clauses +CREATE PUBLICATION testpub_cursch_cursch_conflict + FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl), + CURRENT_SCHEMA EXCEPT (TABLE tbl1); +ERROR: conflicting or redundant EXCEPT clauses for schema "pub_test1" RESET search_path; -- cleanup pub_test1 schema for invalidation tests ALTER PUBLICATION testpub2_forschema DROP TABLES IN SCHEMA pub_test1; diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 4a86d699e84..f84b7883bcc 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -262,6 +262,17 @@ CREATE PUBLICATION testpub_schema_except_multi public EXCEPT (TABLE testpub_tbl1); \dRp+ testpub_schema_except_multi +-- fail: same schema repeated with same EXCEPT clauses +CREATE PUBLICATION testpub_schema_except_conflict + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: same schema repeated with conflicting or no EXCEPT clauses +CREATE PUBLICATION testpub_schema_except_conflict2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2), + pub_test; + -- ALTER TABLE ... SET SCHEMA on a table excluded by a schema publication: -- the schema-scoped exclusion is no longer meaningful once the table moves -- out of its schema, so the exclusion is auto-removed. @@ -1304,6 +1315,26 @@ CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXC RESET client_min_messages; \dRp+ testpub_cursch_except DROP PUBLICATION testpub_cursch_except; + +-- succeeds: CURRENT_SCHEMA and pub_test1 (same schema) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_named_same + FOR TABLES IN SCHEMA CURRENT_SCHEMA, pub_test1; +RESET client_min_messages; +\dRp+ testpub_cursch_named_same +DROP PUBLICATION testpub_cursch_named_same; + +-- fail: CURRENT_SCHEMA and pub_test1 (same schema) have +-- conflicting EXCEPT clauses +CREATE PUBLICATION testpub_cursch_named_conflict + FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl), + pub_test1 EXCEPT (TABLE tbl1); + +-- fail: two CURRENT_SCHEMA mentions with conflicting EXCEPT clauses +CREATE PUBLICATION testpub_cursch_cursch_conflict + FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl), + CURRENT_SCHEMA EXCEPT (TABLE tbl1); + RESET search_path; -- cleanup pub_test1 schema for invalidation tests -- 2.50.1 (Apple Git-155)
v23-0003-Add-EXCEPT-support-to-ALTER-PUBLICATION-ADD-TABL.patch (application/octet-stream, 22.3K) download From 56d55669d3bdbcd47f358d96c4d8fa07ac5179a1 Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Thu, 23 Jul 2026 12:31:51 +0530 Subject: [PATCH v23 3/5] Add EXCEPT support to ALTER PUBLICATION ADD TABLES IN SCHEMA Extend the EXCEPT clause support to allow tables to be excluded when adding a schema to a publication via ALTER PUBLICATION ... ADD. Syntax: ALTER PUBLICATION pub ADD TABLES IN SCHEMA s EXCEPT (TABLE s.t1); Since pg_dump uses ALTER PUBLICATION ... ADD, support for it is included in this patch. --- src/backend/catalog/pg_publication.c | 19 ++-- src/backend/commands/publicationcmds.c | 102 ++++++++++++++++++++-- src/bin/pg_dump/pg_dump.c | 30 ++++++- src/bin/pg_dump/t/002_pg_dump.pl | 24 +++++ src/bin/psql/tab-complete.in.c | 17 ++++ src/test/regress/expected/publication.out | 60 ++++++++++++- src/test/regress/sql/publication.sql | 45 +++++++++- src/test/subscription/t/037_except.pl | 32 +++++++ 8 files changed, 313 insertions(+), 16 deletions(-) diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index 183f97de502..68a061588e7 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -720,15 +720,18 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, * here, as CreatePublication() function invalidates all relations as part * of defining a FOR ALL TABLES publication. * - * For ALTER PUBLICATION, invalidation is needed only when adding an - * EXCEPT table to a publication already marked as ALL TABLES. For - * publications that were originally empty or defined as ALL SEQUENCES and - * are being converted to ALL TABLES, invalidation is skipped here, as - * AlterPublicationAllFlags() function invalidates all relations while - * marking the publication as ALL TABLES publication. + * For ALTER PUBLICATION, invalidation is needed when adding an EXCEPT + * table to either a FOR ALL TABLES publication (pub->alltables is true) + * or a FOR TABLES IN SCHEMA publication (is_schema_publication is true). + * The exception: when a publication is being converted to FOR ALL TABLES + * (pub->alltables is still false at this point), + * AlterPublicationAllFlags() will perform a full invalidation, so we skip + * it here. */ - inval_except_table = (alter_stmt != NULL) && pub->alltables && - (alter_stmt->for_all_tables && pri->except); + inval_except_table = (alter_stmt != NULL) && pri->except && + (pub->alltables + ? alter_stmt->for_all_tables + : is_schema_publication(pubid)); if (!pri->except || inval_except_table) { diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index fe0c670c368..2c79d2423e8 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -71,6 +71,13 @@ static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok); static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); +static void AlterPublicationSchemas(AlterPublicationStmt *stmt, + HeapTuple tup, List *schemaidlist, + List *except_pubtables); +static void AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, + List *except_pubtables, + List *schemaidlist); static char defGetGeneratedColsOption(DefElem *def); static void CheckExceptNotInTableList(List *except_rels, List *explicitrelids); static void ProcessSchemaExceptTables(Oid schemaid, List *except_tables, @@ -1590,7 +1597,8 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, */ static void AlterPublicationSchemas(AlterPublicationStmt *stmt, - HeapTuple tup, List *schemaidlist) + HeapTuple tup, List *schemaidlist, + List *except_pubtables) { Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); @@ -1667,6 +1675,88 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, */ PublicationAddSchemas(pubform->oid, schemaidlist, true, stmt); } + + /* + * Increment the command counter so that is_schema_publication() in + * GetExcludedPublicationTables() can see the just-inserted schema + * rows when AlterPublicationSchemaExceptTables runs next. + */ + if (stmt->action == AP_AddObjects || stmt->action == AP_SetObjects) + CommandCounterIncrement(); + + AlterPublicationSchemaExceptTables(stmt, tup, except_pubtables, schemaidlist); +} + +/* + * Alter the EXCEPT list of a schema-level publication. + * + * Adds, removes, or replaces except-table entries in pg_publication_rel + * (rows with prexcept = true). These entries suppress publication of the + * named tables that would otherwise be covered by a FOR TABLES IN SCHEMA + * clause. + */ +static void +AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, List *except_pubtables, + List *schemaidlist) +{ + Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); + Oid pubid = pubform->oid; + + /* + * Nothing to do if no EXCEPT entries. + */ + if (!except_pubtables) + return; + + /* + * This function handles EXCEPT entries for schema-level publications + * only. For FOR ALL TABLES publications, EXCEPT entries are already + * processed by AlterPublicationTables(). + */ + if (schemaidlist == NIL && !is_schema_publication(pubid)) + return; + + /* + * Dropping a schema from a publication removes all its EXCEPT entries via + * cascade. The concept of "drop all schema tables from the publication + * EXCEPT these ones" is not supported. + */ + if (stmt->action == AP_DropObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); + + /* + * XXX EXCEPT with SET is not currently implemented. Workaround: DROP and + * re-ADD the schema with the desired EXCEPT list. + */ + if (stmt->action == AP_SetObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"), + errhint("Drop and re-add the schema with the desired EXCEPT list."))); + + if (stmt->action == AP_AddObjects) + { + List *rels; + List *explicitrelids; + + rels = OpenTableList(except_pubtables); + + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + /* + * Validate that each excluded table is not also in the explicit table + * list (which would be contradictory). + */ + CheckExceptNotInTableList(rels, explicitrelids); + + PublicationAddTables(pubid, rels, false, stmt); + + CloseTableList(rels); + } } /* @@ -1848,12 +1938,12 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) else { List *relations = NIL; - List *exceptrelations = NIL; + List *except_pubtables = NIL; List *schemaidlist = NIL; Oid pubid = pubform->oid; ObjectsInPublicationToOids(stmt->pubobjects, pstate, &relations, - &exceptrelations, &schemaidlist); + &except_pubtables, &schemaidlist); CheckAlterPublication(stmt, tup, relations, schemaidlist); @@ -1876,10 +1966,12 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) errmsg("publication \"%s\" does not exist", stmt->pubname)); - relations = list_concat(relations, exceptrelations); + if (stmt->for_all_tables) + relations = list_concat(relations, except_pubtables); + AlterPublicationTables(stmt, tup, relations, pstate->p_sourcetext, schemaidlist != NIL); - AlterPublicationSchemas(stmt, tup, schemaidlist); + AlterPublicationSchemas(stmt, tup, schemaidlist, except_pubtables); AlterPublicationAllFlags(stmt, rel, tup); } diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c index 4948e6d80c7..ecd518af02c 100644 --- a/src/bin/pg_dump/pg_dump.c +++ b/src/bin/pg_dump/pg_dump.c @@ -4973,6 +4973,7 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) PublicationInfo *pubinfo = pubsinfo->publication; PQExpBuffer query; char *tag; + bool has_except = false; /* Do nothing if not dumping schema */ if (!dopt->dumpSchema) @@ -4983,7 +4984,34 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) query = createPQExpBuffer(); appendPQExpBuffer(query, "ALTER PUBLICATION %s ", fmtId(pubinfo->dobj.name)); - appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s;\n", fmtId(schemainfo->dobj.name)); + appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s", fmtId(schemainfo->dobj.name)); + + /* + * Append EXCEPT clause for any tables that belong to this schema + * and are excluded from the publication. + */ + for (SimplePtrListCell *cell = pubinfo->except_tables.head; cell; cell = cell->next) + { + TableInfo *tbinfo = (TableInfo *) cell->ptr; + + if (strcmp(tbinfo->dobj.namespace->dobj.name, schemainfo->dobj.name) == 0) + { + if (!has_except) + { + appendPQExpBufferStr(query, " EXCEPT ("); + has_except = true; + } + else + appendPQExpBufferStr(query, ", "); + + appendPQExpBuffer(query, "TABLE ONLY %s", fmtId(tbinfo->dobj.name)); + } + } + + if (has_except) + appendPQExpBufferStr(query, ")"); + + appendPQExpBufferStr(query, ";\n"); /* * There is no point in creating drop query as the drop is done by schema diff --git a/src/bin/pg_dump/t/002_pg_dump.pl b/src/bin/pg_dump/t/002_pg_dump.pl index 9258948b583..d18b3b0d7b9 100644 --- a/src/bin/pg_dump/t/002_pg_dump.pl +++ b/src/bin/pg_dump/t/002_pg_dump.pl @@ -3283,6 +3283,30 @@ my %tests = ( like => { %full_runs, section_post_data => 1, }, }, + 'CREATE PUBLICATION pub11' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub11 FOR TABLES IN SCHEMA dump_test EXCEPT (TABLE test_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub11 WITH (publish = 'insert, update, delete, truncate');\E + .*? + \QALTER PUBLICATION pub11 ADD TABLES IN SCHEMA dump_test EXCEPT (TABLE ONLY test_table);\E + /xms, + like => { %full_runs, section_post_data => 1, }, + }, + + 'CREATE PUBLICATION pub12' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub12 FOR TABLES IN SCHEMA dump_test EXCEPT (TABLE test_table, dump_test.test_second_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub12 WITH (publish = 'insert, update, delete, truncate');\E + .*? + \QALTER PUBLICATION pub12 ADD TABLES IN SCHEMA dump_test EXCEPT (TABLE ONLY test_table, TABLE ONLY test_second_table);\E + /xms, + like => { %full_runs, section_post_data => 1, }, + }, + 'CREATE SUBSCRIPTION sub1' => { create_order => 50, create_sql => 'CREATE SUBSCRIPTION sub1 diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index 7d8b4504194..bf206aa6210 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2359,6 +2359,23 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); + /* After a single schema name in ADD context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 2c92186068f..21499caef70 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -636,12 +636,70 @@ CREATE PUBLICATION testpub_except_ancestor_cross_schema ERROR: partition "public.testpub_part_s2" cannot be both published and excluded DETAIL: Partition root "pub_test.testpub_parted_s" is named in the publication's EXCEPT clause for schema "pub_test". DROP TABLE public.testpub_part_s2; +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; +-- fail: non-existing table in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- fail: EXCEPT table belongs to a different schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 1: ...xcept ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.tes... + ^ +-- fail: TABLE keyword is required for the first entry in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +ERROR: syntax error at or near "testpub_nopk" +LINE 1: ...lter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_no... + ^ +-- fail: exact same table given as both explicitly published and excluded +-- in a single ALTER ... ADD +ALTER PUBLICATION testpub_alter_except + ADD TABLE pub_test.testpub_tbl_s1, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot be both published and excluded +-- fail: add explicit partition and EXCEPT ancestor, given in a +-- single ALTER ... ADD statement +ALTER PUBLICATION testpub_alter_except + ADD TABLE pub_test.testpub_part_s, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ERROR: partition "pub_test.testpub_part_s" cannot be both published and excluded +DETAIL: Partition root "pub_test.testpub_parted_s" is named in the publication's EXCEPT clause for schema "pub_test". +-- fail: partition already explicitly published, then its root is EXCEPT-ed +-- via a later, separate ALTER ... ADD +ALTER PUBLICATION testpub_alter_except ADD TABLE pub_test.testpub_part_s; +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ERROR: partition "pub_test.testpub_part_s" cannot be both published and excluded +DETAIL: Partition root "pub_test.testpub_parted_s" is named in the publication's EXCEPT clause for schema "pub_test". +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_part_s; +-- fail: root already explicitly published, then its partition is rejected +-- from EXCEPT via a later, separate ALTER ... ADD (partitions can never +-- appear in EXCEPT, independent of the root's state) +ALTER PUBLICATION testpub_alter_except ADD TABLE pub_test.testpub_parted_s; +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); +ERROR: cannot specify relation "pub_test.testpub_part_s" in the publication EXCEPT clause +DETAIL: This operation is not supported for individual partitions. +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_parted_s; +-- ADD: qualified and unqualified names; unqualified is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + "pub_test.testpub_tbl_s2" + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP TABLE pub_test.testpub_parted_s CASCADE; DROP TABLE testpub_nopk, testpub_tbl_s1; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi, testpub_alter_except; --------------------------------------------- -- Tests for publications with SEQUENCES --------------------------------------------- diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index f84b7883bcc..e471bb1e4b1 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -324,12 +324,55 @@ CREATE PUBLICATION testpub_except_ancestor_cross_schema TABLE public.testpub_part_s2; DROP TABLE public.testpub_part_s2; +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; + +-- fail: non-existing table in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- fail: EXCEPT table belongs to a different schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- fail: TABLE keyword is required for the first entry in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + +-- fail: exact same table given as both explicitly published and excluded +-- in a single ALTER ... ADD +ALTER PUBLICATION testpub_alter_except + ADD TABLE pub_test.testpub_tbl_s1, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: add explicit partition and EXCEPT ancestor, given in a +-- single ALTER ... ADD statement +ALTER PUBLICATION testpub_alter_except + ADD TABLE pub_test.testpub_part_s, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); + +-- fail: partition already explicitly published, then its root is EXCEPT-ed +-- via a later, separate ALTER ... ADD +ALTER PUBLICATION testpub_alter_except ADD TABLE pub_test.testpub_part_s; +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_part_s; + +-- fail: root already explicitly published, then its partition is rejected +-- from EXCEPT via a later, separate ALTER ... ADD (partitions can never +-- appear in EXCEPT, independent of the root's state) +ALTER PUBLICATION testpub_alter_except ADD TABLE pub_test.testpub_parted_s; +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_parted_s; + +-- ADD: qualified and unqualified names; unqualified is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); +\dRp+ testpub_alter_except + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP TABLE pub_test.testpub_parted_s CASCADE; DROP TABLE testpub_nopk, testpub_tbl_s1; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi, testpub_alter_except; --------------------------------------------- -- Tests for publications with SEQUENCES diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index c4e4efafec8..d69b43c14b5 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -347,6 +347,38 @@ is($result, qq(5), $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); +# ============================================ +# ALTER PUBLICATION EXCEPT for TABLES IN SCHEMA +# ============================================ + +# Truncate subscriber tables to remove data accumulated from previous tests. +$node_subscriber->safe_psql('postgres', + 'TRUNCATE sch1.tab_published, sch1.tab_excluded, sch1.parent, sch1.child'); + +# ADD: add a schema with an excepted table; verify the except entry takes effect. +$node_publisher->safe_psql('postgres', "CREATE PUBLICATION sch_pub"); +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub ADD TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_excluded)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(6), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: included table synced'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + # Cleanup schema tables before the multi-publication section. $node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); $node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); -- 2.50.1 (Apple Git-155)
v23-0004-Add-EXCEPT-support-to-ALTER-PUBLICATION-SET-TABL.patch (application/octet-stream, 27.7K) download From 46d42ff158a29befaed7167031a4b89c64b472d7 Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Thu, 18 Jun 2026 11:32:32 +0530 Subject: [PATCH v23 4/5] Add EXCEPT support to ALTER PUBLICATION SET TABLES IN SCHEMA Extend AlterPublicationExceptTables() with the AP_SetObjects case, which redefines the publication and replaces the entire EXCEPT list. Syntax: ALTER PUBLICATION pub SET TABLES IN SCHEMA s EXCEPT (TABLE t1); This patch also cleans up EXCEPT entries when a schema is dropped from the publication. --- src/backend/commands/publicationcmds.c | 179 ++++++++++++++++++---- src/bin/psql/tab-complete.in.c | 17 ++ src/test/regress/expected/publication.out | 109 +++++++++++++ src/test/regress/sql/publication.sql | 47 ++++++ src/test/subscription/t/037_except.pl | 85 ++++++++++ 5 files changed, 411 insertions(+), 26 deletions(-) diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 2c79d2423e8..75c159028c8 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -67,7 +67,8 @@ static void CloseTableList(List *rels); static void LockSchemaList(List *schemalist); static void PublicationAddTables(Oid pubid, List *rels, bool if_not_exists, AlterPublicationStmt *stmt); -static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok); +static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok, + bool delete_excluded); static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); @@ -1441,7 +1442,7 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, PublicationAddTables(pubid, rels, false, stmt); } else if (stmt->action == AP_DropObjects) - PublicationDropTables(pubid, rels, false); + PublicationDropTables(pubid, rels, false, false); else /* AP_SetObjects */ { List *oldrelids = NIL; @@ -1576,7 +1577,7 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, } /* And drop them. */ - PublicationDropTables(pubid, delrels, true); + PublicationDropTables(pubid, delrels, true, true); /* * Don't bother calculating the difference for adding, we'll catch and @@ -1678,8 +1679,8 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, /* * Increment the command counter so that is_schema_publication() in - * GetExcludedPublicationTables() can see the just-inserted schema - * rows when AlterPublicationSchemaExceptTables runs next. + * GetExcludedPublicationTables() can see the just-inserted schema rows + * when AlterPublicationSchemaExceptTables runs next. */ if (stmt->action == AP_AddObjects || stmt->action == AP_SetObjects) CommandCounterIncrement(); @@ -1688,7 +1689,7 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, } /* - * Alter the EXCEPT list of a schema-level publication. + * Alter the EXCEPT clause of a schema-level publication. * * Adds, removes, or replaces except-table entries in pg_publication_rel * (rows with prexcept = true). These entries suppress publication of the @@ -1697,16 +1698,18 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, */ static void AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, - HeapTuple tup, List *except_pubtables, - List *schemaidlist) + HeapTuple tup, List *except_pubtables, + List *schemaidlist) { Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); Oid pubid = pubform->oid; /* - * Nothing to do if no EXCEPT entries. + * Nothing to do if there are no EXCEPT entries, unless handling the SET + * command, because if the user has removed all exceptions we need to drop + * any existing ones. */ - if (!except_pubtables) + if (!except_pubtables && stmt->action != AP_SetObjects) return; /* @@ -1727,16 +1730,6 @@ AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); - /* - * XXX EXCEPT with SET is not currently implemented. Workaround: DROP and - * re-ADD the schema with the desired EXCEPT list. - */ - if (stmt->action == AP_SetObjects) - ereport(ERROR, - (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"), - errhint("Drop and re-add the schema with the desired EXCEPT list."))); - if (stmt->action == AP_AddObjects) { List *rels; @@ -1755,6 +1748,72 @@ AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, PublicationAddTables(pubid, rels, false, stmt); + CloseTableList(rels); + } + else /* AP_SetObjects */ + { + List *oldexceptrelids = NIL; + List *newexceptrelids = NIL; + List *delrelids = NIL; + List *rels; + List *explicitrelids; + + rels = OpenTableList(except_pubtables); + + /* Collect OIDs of the desired new EXCEPT clause. */ + foreach_ptr(PublicationRelInfo, pri, rels) + newexceptrelids = lappend_oid(newexceptrelids, + RelationGetRelid(pri->relation)); + + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + /* Check that there is no clash between included and excluded tables. */ + CheckExceptNotInTableList(rels, explicitrelids); + + /* + * Get the current set of EXCEPT entries. Only FOR ALL TABLES and + * schema-level publications can have EXCEPT entries; for any other + * publication type oldexceptrelids stays NIL. + * + * Note: we check is_schema_publication() against the current catalog + * state (before AlterPublicationSchemas has run), so if the caller is + * doing SET TABLE t1 to convert a schema publication into a plain + * table publication, is_schema_publication() still returns true here. + * That is intentional: it lets us discover and clean up any stale + * EXCEPT entries that belong to the old schema definition. + */ + if (GetPublication(pubid)->alltables || is_schema_publication(pubid)) + oldexceptrelids = GetExcludedPublicationTables(pubid, + PUBLICATION_PART_ROOT); + + /* Build a list of old EXCEPT entries not present in the new list. */ + foreach_oid(oldrelid, oldexceptrelids) + { + if (!list_member_oid(newexceptrelids, oldrelid)) + delrelids = lappend_oid(delrelids, oldrelid); + } + + /* Drop old EXCEPT entries not present in the new list. */ + foreach_oid(relid, delrelids) + { + Oid proid; + ObjectAddress obj; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + /* Add new EXCEPT entries, skipping any already present. */ + PublicationAddTables(pubid, rels, true, stmt); + CloseTableList(rels); } } @@ -2378,33 +2437,68 @@ PublicationAddTables(Oid pubid, List *rels, bool if_not_exists, /* * Remove listed tables from the publication. + * + * delete_excluded controls how EXCEPT (prexcept=true) rows are handled: + * true - delete them silently. Used by the SET path to clear stale + * EXCEPT rows that are being replaced by a new EXCEPT clause. + * false - treat them as "not a member". Used by ALTER ... DROP TABLE: an + * EXCEPT entry is not something DROP TABLE is expected to remove. */ static void -PublicationDropTables(Oid pubid, List *rels, bool missing_ok) +PublicationDropTables(Oid pubid, List *rels, bool missing_ok, + bool delete_excluded) { ObjectAddress obj; ListCell *lc; - Oid prid; foreach(lc, rels) { PublicationRelInfo *pubrel = (PublicationRelInfo *) lfirst(lc); Relation rel = pubrel->relation; Oid relid = RelationGetRelid(rel); + HeapTuple tup; + Form_pg_publication_rel pubrelform; + Oid prid = InvalidOid; + bool is_except = false; if (pubrel->columns) ereport(ERROR, errcode(ERRCODE_SYNTAX_ERROR), errmsg("column list must not be specified in ALTER PUBLICATION ... DROP")); - prid = GetSysCacheOid2(PUBLICATIONRELMAP, Anum_pg_publication_rel_oid, - ObjectIdGetDatum(relid), - ObjectIdGetDatum(pubid)); - if (!OidIsValid(prid)) + tup = SearchSysCache2(PUBLICATIONRELMAP, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (HeapTupleIsValid(tup)) + { + pubrelform = (Form_pg_publication_rel) GETSTRUCT(tup); + is_except = pubrelform->prexcept; + prid = pubrelform->oid; + ReleaseSysCache(tup); + } + + /* + * DROP TABLE operates only on regular member rows. A missing row + * and an EXCEPT row both mean the table isn't currently published, + * but we distinguish them so the EXCEPT case can carry a hint + * pointing the user at the EXCEPT clause. The SET-cleanup caller + * (delete_excluded = true) intends to remove EXCEPT rows and so + * bypasses the EXCEPT half of this check. + */ + if (!OidIsValid(prid) || (is_except && !delete_excluded)) { if (missing_ok) continue; + if (is_except) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("cannot drop table \"%s\" from publication \"%s\"", + RelationGetQualifiedRelationName(rel), + get_publication_name(pubid, false)), + errdetail("The table is currently named in an EXCEPT clause of the publication."), + errhint("Change the EXCEPT clause using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT."))); + ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("relation \"%s\" is not part of the publication", @@ -2460,6 +2554,7 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) foreach(lc, schemas) { Oid schemaid = lfirst_oid(lc); + List *except_relids; psid = GetSysCacheOid2(PUBLICATIONNAMESPACEMAP, Anum_pg_publication_namespace_oid, @@ -2476,8 +2571,40 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) get_namespace_name(schemaid)))); } + /* + * Collect EXCEPT entries for tables belonging to this schema before + * removing the schema entry. + */ + except_relids = GetExcludedPublicationTables(pubid, PUBLICATION_PART_ROOT); + ObjectAddressSet(obj, PublicationNamespaceRelationId, psid); performDeletion(&obj, DROP_CASCADE, 0); + + /* + * Drop any prexcept rows for tables belonging to this schema. These + * rows have no pg_depend entry pointing at the + * pg_publication_namespace row, so they are not cascaded by the + * performDeletion() call above and must be cleaned up explicitly. + */ + foreach_oid(relid, except_relids) + { + Oid proid; + + if (get_rel_namespace(relid) != schemaid) + continue; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + list_free(except_relids); } } diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index bf206aa6210..e67b9c63a5a 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2376,6 +2376,23 @@ match_previous_words(int pattern_id, } else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) COMPLETE_WITH(")"); + /* After a single schema name in SET context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 21499caef70..fbfa0a7a5cb 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -694,6 +694,115 @@ Except tables: "pub_test.testpub_tbl_s1" "pub_test.testpub_tbl_s2" +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s2" + +-- fail: table in EXCEPT clause also appears in the explicit table list +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot be both published and excluded +-- fail: explicit partition + EXCEPT-ed root, given in a single SET statement +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_part_s, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ERROR: partition "pub_test.testpub_part_s" cannot be both published and excluded +DETAIL: Partition root "pub_test.testpub_parted_s" is named in the publication's EXCEPT clause for schema "pub_test". +-- fail: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 1: ...xcept SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.tes... + ^ +-- SET: unqualified name in EXCEPT is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- SET without EXCEPT clears the existing except list +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + +-- SET to a different schema removes old schema's EXCEPT entries +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA public; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "public" + +-- fail: nonexistent table in EXCEPT clause (SET path) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- SET: multiple schemas each with their own EXCEPT clause +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- fail: ALTER PUBLICATION ... DROP TABLE on an excluded table is rejected +-- with an EXCEPT-specific error. +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_tbl_s1; +ERROR: cannot drop table "pub_test.testpub_tbl_s1" from publication "testpub_alter_except" +DETAIL: The table is currently named in an EXCEPT clause of the publication. +HINT: Change the EXCEPT clause using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT. +-- the EXCEPT entry is still present after the rejected DROP TABLE +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- fail: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +ERROR: EXCEPT clause is not supported with DROP in ALTER PUBLICATION +-- DROP TABLES IN SCHEMA removes associated EXCEPT entries +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "public" +Except tables: + "public.testpub_tbl1" + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index e471bb1e4b1..9cd78bd983e 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -367,6 +367,53 @@ ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_parted_s; ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); \dRp+ testpub_alter_except +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + +-- fail: table in EXCEPT clause also appears in the explicit table list +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: explicit partition + EXCEPT-ed root, given in a single SET statement +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_part_s, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); + +-- fail: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- SET: unqualified name in EXCEPT is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +\dRp+ testpub_alter_except + +-- SET without EXCEPT clears the existing except list +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + +-- SET to a different schema removes old schema's EXCEPT entries +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA public; +\dRp+ testpub_alter_except + +-- fail: nonexistent table in EXCEPT clause (SET path) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- SET: multiple schemas each with their own EXCEPT clause +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_alter_except + +-- fail: ALTER PUBLICATION ... DROP TABLE on an excluded table is rejected +-- with an EXCEPT-specific error. +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_tbl_s1; +-- the EXCEPT entry is still present after the rejected DROP TABLE +\dRp+ testpub_alter_except + +-- fail: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); + +-- DROP TABLES IN SCHEMA removes associated EXCEPT entries +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index d69b43c14b5..bcd8ac7bc1f 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -376,6 +376,61 @@ $result = is($result, qq(0), 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); +# SET: replace the except list; tab_excluded is now included and tab_published is excluded. +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_published)" +); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (7); + INSERT INTO sch1.tab_excluded VALUES (7); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded WHERE a = 7"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: newly included table is replicated' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published WHERE a = 7"); +is($result, qq(0), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: now-excluded table is not replicated' +); + +# SET without EXCEPT: clears the except list; both tables are now published. +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1"); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (8); + INSERT INTO sch1.tab_excluded VALUES (8); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published WHERE a = 8"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_published replicated after except list cleared' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded WHERE a = 8"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_excluded replicated after except list cleared' +); + $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); @@ -518,6 +573,36 @@ $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); +# OK when a table is excluded by a TABLES IN SCHEMA EXCEPT publication, +# but is included by another publication. +$node_publisher->safe_psql('postgres', 'TRUNCATE tab1'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE tab1'); + +$node_publisher->safe_psql( + 'postgres', qq( + CREATE PUBLICATION tap_pub1 FOR TABLES IN SCHEMA public EXCEPT (TABLE public.tab1); + CREATE PUBLICATION tap_pub2 FOR TABLE tab1; + INSERT INTO tab1 VALUES(1); +)); +$node_subscriber->psql('postgres', + "CREATE SUBSCRIPTION tap_sub CONNECTION '$publisher_connstr' PUBLICATION tap_pub1, tap_pub2" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'tap_sub'); + +$node_publisher->safe_psql('postgres', qq(INSERT INTO tab1 VALUES(2))); +$node_publisher->wait_for_catchup('tap_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT * FROM tab1 ORDER BY a"); +is( $result, qq(1 +2), + "TABLES IN SCHEMA EXCEPT: table excluded in schema pub but included by another pub is replicated" +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); + $node_publisher->stop('fast'); done_testing(); -- 2.50.1 (Apple Git-155)
v23-0005-Documentation-Patch.patch (application/octet-stream, 11.6K) download From 27e5486e8ae87a02788efeb124db17b7338b8fc3 Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Thu, 18 Jun 2026 09:03:08 +0530 Subject: [PATCH v23 5/5] Documentation Patch --- doc/src/sgml/logical-replication.sgml | 3 +- doc/src/sgml/ref/alter_publication.sgml | 58 +++++++++++++++++++++++- doc/src/sgml/ref/create_publication.sgml | 42 +++++++++++++---- 3 files changed, 91 insertions(+), 12 deletions(-) diff --git a/doc/src/sgml/logical-replication.sgml b/doc/src/sgml/logical-replication.sgml index 36298cacb75..03f12986b12 100644 --- a/doc/src/sgml/logical-replication.sgml +++ b/doc/src/sgml/logical-replication.sgml @@ -117,7 +117,8 @@ or <literal>FOR ALL SEQUENCES</literal>. Unlike tables, sequences can be synchronized at any time. For more information, see <xref linkend="logical-replication-sequences"/>. When a publication is - created with <literal>FOR ALL TABLES</literal>, a table or set of tables can + created with <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal>, a table or set of tables can be explicitly excluded from publication using the <link linkend="sql-createpublication-params-for-except-table"><literal>EXCEPT</literal></link> clause. diff --git a/doc/src/sgml/ref/alter_publication.sgml b/doc/src/sgml/ref/alter_publication.sgml index 52114a16a39..037ddfa9404 100644 --- a/doc/src/sgml/ref/alter_publication.sgml +++ b/doc/src/sgml/ref/alter_publication.sgml @@ -31,7 +31,7 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA <replaceable class="parameter">tables_in_schema</replaceable> [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -47,6 +47,10 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <replaceable class="parameter">table_object</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] [ WHERE ( <replaceable class="parameter">expression</replaceable> ) ] +<phrase>and <replaceable class="parameter">tables_in_schema</replaceable> is:</phrase> + + { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] + <phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> TABLE <replaceable class="parameter">table_object</replaceable> [, ... ] @@ -69,6 +73,9 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r The first two variants modify which tables/schemas are part of the publication. The <literal>ADD</literal> and <literal>DROP</literal> clauses will add and remove one or more tables/schemas from the publication. + The <literal>EXCEPT</literal> clause can be used with + <literal>ADD TABLES IN SCHEMA</literal> to exclude specific tables from a + schema-level publication. </para> <para> @@ -93,7 +100,11 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r used with a publication defined with <literal>FOR TABLE</literal> or <literal>FOR TABLES IN SCHEMA</literal>, replaces the list of tables/schemas in the publication with the specified list; the existing tables or schemas - that were present in the publication will be removed. + that were present in the publication will be removed. When + <literal>SET TABLES IN SCHEMA</literal> is used with an + <literal>EXCEPT</literal> clause, the excluded tables for each schema are + replaced with the specified list; if <literal>EXCEPT</literal> is omitted + for a schema, any existing exclusions for that schema are cleared. </para> <para> @@ -198,6 +209,27 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r </listitem> </varlistentry> + <varlistentry> + <term><literal>EXCEPT</literal></term> + <listitem> + <para> + When used with <literal>ADD TABLES IN SCHEMA</literal> + or <literal>SET TABLES IN SCHEMA</literal>, specifies + tables to be excluded from the publication. Each named + table must belong to the schema specified in the same + <literal>TABLES IN SCHEMA</literal> clause. Table names may be + schema-qualified or unqualified; unqualified names are implicitly + qualified with the schema named in the same clause. See + <xref linkend="sql-createpublication"/> for further details on the + semantics of <literal>EXCEPT</literal>. + </para> + <para> + Dropping a table always removes it from the <literal>EXCEPT</literal> + clause. + </para> + </listitem> + </varlistentry> + <varlistentry> <term><literal>SET ( <replaceable class="parameter">publication_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] )</literal></term> <listitem> @@ -288,6 +320,28 @@ ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA marketing, sales; </programlisting> </para> + <para> + Add schema <structname>sales</structname> to the publication + <structname>sales_publication</structname>, excluding the + <structname>sales.internal</structname> and + <structname>sales.drafts</structname> tables: +<programlisting> +ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA sales EXCEPT (TABLE internal, drafts); +</programlisting> + </para> + + <para> + Replace the schema list of <structname>sales_publication</structname> with + <structname>sales</structname>, excluding only + <structname>sales.drafts</structname>. Other than + <structname>sales.drafts</structname>, any previously excluded tables for schema + <structname>sales</structname> are no longer excluded. Any schemas previously in + <structname>sales_publication</structname> are removed: +<programlisting> +ALTER PUBLICATION sales_publication SET TABLES IN SCHEMA sales EXCEPT (TABLE drafts); +</programlisting> + </para> + <para> Add tables <structname>users</structname>, <structname>departments</structname> and schema diff --git a/doc/src/sgml/ref/create_publication.sgml b/doc/src/sgml/ref/create_publication.sgml index 85cfcaddafa..d16b4067fe6 100644 --- a/doc/src/sgml/ref/create_publication.sgml +++ b/doc/src/sgml/ref/create_publication.sgml @@ -28,7 +28,7 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA <replaceable class="parameter">tables_in_schema</replaceable> [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -39,6 +39,10 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <replaceable class="parameter">table_object</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] [ WHERE ( <replaceable class="parameter">expression</replaceable> ) ] +<phrase>and <replaceable class="parameter">tables_in_schema</replaceable> is:</phrase> + + { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] + <phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> TABLE <replaceable class="parameter">table_object</replaceable> [, ... ] @@ -142,6 +146,8 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <para> Marks the publication as one that replicates changes for all tables in the specified list of schemas, including tables created in the future. + Tables listed in the <literal>EXCEPT</literal> clause for a given schema + are excluded from the publication. </para> <para> @@ -173,7 +179,7 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <para> Marks the publication as one that replicates changes for all tables in the database, including tables created in the future. Tables listed in - <literal>EXCEPT</literal> clause are excluded from the publication. + the <literal>EXCEPT</literal> clause are excluded from the publication. </para> </listitem> </varlistentry> @@ -198,13 +204,21 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <listitem> <para> This clause specifies a list of tables to be excluded from the - publication. + publication. It can be used with <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal>. For <literal>FOR TABLES IN + SCHEMA</literal>, the exclusion applies only to tables in the schema + associated with the <literal>EXCEPT</literal>. </para> <para> - Once a table is excluded, the exclusion applies to that table - regardless of its name or schema. Renaming the table or moving it to - another schema using <command>ALTER TABLE ... SET SCHEMA</command> does - not remove the exclusion. + Once a table is excluded under <literal>FOR ALL TABLES</literal>, the + exclusion applies to that table regardless of its name or schema. + Renaming the table or moving it to another schema using + <command>ALTER TABLE ... SET SCHEMA</command> does not remove the + exclusion. However, for <literal>FOR TABLES IN SCHEMA</literal>, because + the <literal>EXCEPT</literal> is schema-scoped, moving a schema-excluded + table to another schema does remove the exclusion; if the table is later + moved back, the exclusion is not restored and must be re-established + with <command>ALTER PUBLICATION</command>. </para> <para> For inherited tables, if <literal>ONLY</literal> is specified before the @@ -216,8 +230,9 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> </para> <para> For partitioned tables, only the root partitioned table may be specified - in <literal>EXCEPT</literal>. Doing so excludes the root table and - all of its partitions from replication. The optional + in <literal>EXCEPT</literal>. Excluding the root table automatically + excludes all of its partitions from replication, even those in + schemas that are otherwise included in the publication. The optional <literal>ONLY</literal> and <literal>*</literal> has no effect for partitioned tables. </para> @@ -521,6 +536,15 @@ CREATE PUBLICATION production_publication FOR TABLE users, departments, TABLES I CREATE PUBLICATION sales_publication FOR TABLES IN SCHEMA marketing, sales; </programlisting></para> + <para> + Create a publication that publishes all changes for all the tables present in + the schema <structname>sales</structname>, except + <structname>internal</structname> and <structname>drafts</structname>: +<programlisting> +CREATE PUBLICATION sales_filtered FOR TABLES IN SCHEMA sales EXCEPT (TABLE internal, drafts); +</programlisting> + </para> + <para> Create a publication that publishes all changes for table <structname>users</structname>, but replicates only columns <structname>user_id</structname> and -- 2.50.1 (Apple Git-155)
^ permalink raw reply [nested|flat] 196+ messages in thread

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-23 11:56  Nisha Moond <nisha.moond412@gmail.com>
  parent: Peter Smith <smithpb2250@gmail.com>
  0 siblings, 0 replies; 196+ messages in thread

From: Nisha Moond @ 2026-07-23 11:56 UTC (permalink / raw)
  To: Peter Smith <smithpb2250@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Tue, Jul 21, 2026 at 11:23 AM Peter Smith <smithpb2250@gmail.com> wrote:
>
> Some review comments for v22*
>
> ======
>
> 1. GENERAL -- Consistent wording in messages
>
> I found some examples of error messages that could be made more similar:
>
> 1a.
> "modify" versus "change"
>
> modify...
>
> + errhint("Use ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT
> to modify the EXCEPT list.")));
>
> versus (Change)
>
> + errhint("Change the EXCEPT clause using ALTER PUBLICATION ... SET
> TABLES IN SCHEMA ... EXCEPT."));
> + errhint("Change the EXCEPT clause using ALTER PUBLICATION ... SET
> TABLES IN SCHEMA ... EXCEPT.")));
>
> + errhint("%s", has_alltables_pub ?
> + _("Change the EXCEPT clause using ALTER PUBLICATION ... SET ALL
> TABLES ... EXCEPT.") :
> + _("Change the EXCEPT clause using ALTER PUBLICATION ... SET TABLES
> IN SCHEMA ... EXCEPT.")));
>
> ~
>
> Shouldn't 1st one (from patch v22-0004) be identical to the others? e.g.:
> Change the EXCEPT clause using ALTER PUBLICATION ... SET TABLES IN
> SCHEMA ... EXCEPT.
>
> ~~~
>
> 1b.
> "referenced" versus "named" versus "listed"
>
> referenced...
>
> + errmsg_plural("cannot attach table \"%s\" as partition because it is
> referenced in EXCEPT clause of publication %s",
> +   "cannot attach table \"%s\" as partition because it is referenced
> in EXCEPT clause of publications %s",
>
> versus (named)
>
> + errdetail("Partition root \"%s\" is named in the publication's
> EXCEPT clause for schema \"%s\".",
> +   quote_qualified_identifier(get_namespace_name(get_rel_namespace(root)),
> + get_rel_name(root)),
>
> + errdetail("Partition root \"%s\" is named in the publication's
> EXCEPT clause for schema \"%s\".",
> +    RelationGetQualifiedRelationName(pri->relation),
> +    get_namespace_name(RelationGetNamespace(pri->relation)))));
>
> versus (listed)
>
> + errdetail("Ancestor \"%s\" of partition \"%s\" is currently listed
> in the EXCEPT clause of the publication.",
> +   quote_qualified_identifier(get_namespace_name(get_rel_namespace(root)),
> + get_rel_name(root)),
>
> + errdetail("The table is currently listed in the EXCEPT clause of the
> publication."),
>
> + * publication, excluding any tables listed in the EXCEPT clause.
>
> + errdetail("Ancestor \"%s\" of partition \"%s\" is currently listed
> in the EXCEPT clause of this command.",
> +    RelationGetQualifiedRelationName(pri->relation),
> +    quote_qualified_identifier(get_namespace_name(get_rel_namespace(explicitrelid)),
>
> ~
>
> IMO there is no real difference here in saying "referenced" v "named"
> v "listed", so why not make them all "named" so they are alike.
>
> ~~~
>
> 1c.
> "EXCEPT list" versus "EXCEPT clause"
>
> EXCEPT list:
>
> + errhint("Use ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT
> to modify the EXCEPT list.")));
>
> + * A partition cannot be included when its partition root is in the
> + * same publication's EXCEPT list.  Doing so would leave the catalog
>
> + errhint("Change EXCEPT list using ALTER PUBLICATION ... SET TABLES
> IN SCHEMA ... EXCEPT."));
>
> + errhint("Change EXCEPT list using ALTER PUBLICATION ... SET TABLES
> IN SCHEMA ... EXCEPT.")));
>
> + /* filter out any tables that appear in the EXCEPT list */
>
> + * A partition whose root is in the publication's EXCEPT list
> + * is also excluded, even if the partition itself lives in a
>
> + * Validate that each excluded table is not also in the
> + * explicit table list (which would be contradictory), and
> + * that no explicit partition's root is in the except list.
>
> etc.
>
> I don't recognise the reasons for the difference -- it all seems a bit
> random. There are a lot more "EXCEPT clause" than there are "EXCEPT
> list".
>
> EXCEPT list makes sense for some comments and parameters, but for
> user-facing messages maybe those should consistently say "EXCEPT
> clause"?
>

Thanks, agreed on all three.
Standardized the user-facing messages using "clause" and updated the
comments to use "EXCEPT clause", keeping "list" only where it refers
to the actual List variable.
I'll keep an eye on the next iterations and correct in case I missed any.

> ======
> src/backend/catalog/pg_publication.c
>
> 2.
> publication_add_relation:
> On Mon, Jul 20, 2026 at 6:22 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
> >
> > On Thu, Jul 16, 2026 at 2:04 PM Peter Smith <smithpb2250@gmail.com> wrote:
> > >
> >
> > > 7.
> > > + errdetail("Ancestor \"%s\" of partition \"%s\" is currently listed
> > > in the EXCEPT clause of the publication.",
> > > +   quote_qualified_identifier(get_namespace_name(get_rel_namespace(root)),
> > >
> > > Similar (singular) comment to before.
> > >
> > > /in the EXCEPT clause/in an EXCEPT clause/
> > >
> >
> > It looks like comment #4 is repeated here. In any case, I addressed
> > both occurrences of the errdetail (in check_publication_add_relation()
> > and CheckExceptNotInTableList()):
> >   "Ancestor \"%s\" of partition \"%s\" is curre..".
> >
>
> Looks like a previous review comment #7 was missed despite saying it
> was addressed. It still says:
> + errdetail("The table is currently listed in the EXCEPT clause of the
> publication."),
>

Sorry, I misread the comment; it's corrected now.

> ======
> src/backend/commands/publicationcmds.c
>
> ProcessSchemaExceptTables
>
> 3.
> (patch 0002)
>
> + * *schemas: accumulates all schema OIDs seen so far in this statement.
> + * *schemas_with_except: tracks which schema OIDs have already been seen
> + * with an EXCEPT clause in this statement.
>
> Maybe this can clarify that `*schemas_with_except` OIDs will be a
> subset of `*schemas`.OIDs
>
> SUGGESTION
> *schemas_with_except: This is a subset of *schemas. Tracks which of
> the seen schemas of this statement had an EXCEPT clause.
>

Done.
~~~

--
Thanks,
Nisha





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-23 11:56  Nisha Moond <nisha.moond412@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  0 siblings, 0 replies; 196+ messages in thread

From: Nisha Moond @ 2026-07-23 11:56 UTC (permalink / raw)
  To: shveta malik <shveta.malik@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Tue, Jul 21, 2026 at 11:12 AM shveta malik <shveta.malik@gmail.com> wrote:
>
>
> A few more comments:
>
> 8)
> CreatePublication:
> + /*
> + * Collect explicit table OIDs now, before we close the relation
> + * list, so that except-table validation below can check for
> + * contradictions without relying on a catalog scan that might not
> + * yet see the just-inserted rows.
> + */
> + if (except_pubtables != NIL)
> + {
> + foreach_ptr(PublicationRelInfo, pri, rels)
> + explicitrelids = lappend_oid(explicitrelids,
> + RelationGetRelid(pri->relation));
> + }
> +
>   PublicationAddTables(puboid, rels, true, NULL);
>
> Shall we make the explicitrelids collection after
> 'PublicationAddTables', as PublicationAddTables may error out too
> while doing 'check_publication_add_relation'.
>

make sense. Updated.

> 9)
> In the check above, IIUC, except_pubtables can be there even for ALL
> TABLES, but we want this handling only for schema-except list, so
> shall we have the check as:
>
> if (schemaidlist != NIL && except_pubtables != NIL)
>

Here FOR ALL TABLES EXCEPT is already handled in the for_all_tables
branch, so it can't reach this code.

The only possible cases here are FOR TABLE and FOR TABLES IN SCHEMA.
Since EXCEPT is not supported with plain FOR TABLE, except_pubtables
!= NIL already implies the schema case.

That said, should we add an assertion here, e.g.:

if (except_pubtables != NIL)
{
    /* EXCEPT is only accepted with TABLES IN SCHEMA */
    Assert(schemaidlist != NIL);
...

Or please correct me if I've misunderstood something.

--
Thanks,
Nisha






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-24 06:24  Peter Smith <smithpb2250@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  1 sibling, 1 reply; 196+ messages in thread

From: Peter Smith @ 2026-07-24 06:24 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

Some review comments for the v23* patches

//////////
Patch 0001
//////////

src/backend/catalog/pg_publication.c

check_publication_add_relation:

1.
+ if (targetrel->rd_rel->relispartition)
+ {
+ Oid relid = RelationGetRelid(targetrel);
+ Oid root;
+ bool root_except;
+
+ if (pri->except)
+ {
+ /* If in EXCEPT clause, must be root partitioned table */
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg(errormsg, relname),
+ errdetail("This operation is not supported for individual partitions.")));
+ }
+
+ /*
+ * A partition cannot be added to a publication if its partition root
+ * is excluded by the publication. We follow the rule that excluding a
+ * partition root means that the entire partition tree is excluded.
+ * Thus, check whether the root is in the EXCEPT clause and reject
+ * adding the individual partition to the publication.
+ */

The comment says "Thus, check whether the root is in the EXCEPT clause
and reject", but in fact that has already been done in the code before
this comment.

The comment is good, but IMO it belongs atop the outer `if
(targetrel->rd_rel->relispartition)`

~~~

is_table_publication:

2.
 /*
- * Returns true if the publication has explicitly included relation (i.e.,
+ * Returns true if the publication has an explicitly-included relation (i.e.,
  * not marked as EXCEPT).
  */

In hindsight, the function comment seems a bit odd. It doesn't need to
mention EXCEPT -- those are more like logic details about *how* it
works, nothing to do with the purpose of the function.

SUGGESTION
Returns true if the publication has a FOR TABLE clause.

~

Similarly, the `is_schema_publication` function comment could simply say:
Returns true if the publication has a FOR TABLES IN SCHEMA clause.

~~~

GetAllSchemaPublicationRelations:

3.
+ if (except_relids != NIL)
+ {
+ /* filter out any tables that appear in the EXCEPT clause */

But `except_relids` really is a List so I think the comment saying
"EXCEPT list" was probably fine here.

~~~

is_table_publishable_in_publication:

5.
  /*
  * Check whether the table is explicitly published via pg_publication_rel
  * or pg_publication_namespace.
+ *
+ * A pg_publication_rel row with prexcept=true means the table is
+ * explicitly excluded via EXCEPT and must not be reported as published,
+ * even if its schema is otherwise included.  A row with prexcept=false
+ * means it is explicitly included.  If no pg_publication_rel row exists,
+ * the table is published iff its schema appears in
+ * pg_publication_namespace.
  */
- return (SearchSysCacheExists2(PUBLICATIONRELMAP,
-   ObjectIdGetDatum(relid),
-   ObjectIdGetDatum(pub->oid)) ||
- SearchSysCacheExists2(PUBLICATIONNAMESPACEMAP,
-   ObjectIdGetDatum(get_rel_namespace(relid)),
-   ObjectIdGetDatum(pub->oid)));
+ if (CheckPublicationRelEntry(pub->oid, relid, &is_except))
+ return !is_except;
+
+ return SearchSysCacheExists2(PUBLICATIONNAMESPACEMAP,
+ ObjectIdGetDatum(get_rel_namespace(relid)),
+ ObjectIdGetDatum(pub->oid));

I think that the last `if` would be better written as if/else. That's
because your big comment applies to *both* of those returns, but it is
not immediately obvious due to the blank line.

======
src/backend/commands/publicationcmds.c

AlterPublication:

6.
Code was moved out of patch 0001.

TBH, I thought this could've stayed in patch 0001 -- Although code was
in the AlterPublication function, AFAICT it had nothing really to do
with "alter" patch -- Isn't it more related just to the signature
change of `ObjectsInPublicationToOids` which is elsewhere in here
patch 0001?

//////////
Patch 0002
//////////

No comments.

//////////
Patch 0003
//////////

src/backend/commands/publicationcmds.c

1.
- List    *exceptrelations = NIL;
+ List    *except_pubtables = NIL;
  List    *schemaidlist = NIL;
  Oid pubid = pubform->oid;

  ObjectsInPublicationToOids(stmt->pubobjects, pstate, &relations,
-    &exceptrelations, &schemaidlist);
+    &except_pubtables, &schemaidlist);


(same as patch 0001 review comment #6)

Wondering if this change belonged in patch 0001, which is where
ObjectsInPublicationToOids signature was modified.

//////////
Patch 0004
//////////

src/backend/commands/publicationcmds.c

AlterPublicationSchemas:

1.
 /*
- * Alter the EXCEPT list of a schema-level publication.
+ * Alter the EXCEPT clause of a schema-level publication.
  *
  * Adds, removes, or replaces except-table entries in pg_publication_rel
  * (rows with prexcept = true).  These entries suppress publication of the

Maybe "EXCEPT list" might have been fine terminology for this one --
The "clause" is just a piece of the grammar, whereas this is mostly
about modifying the list of excluded tables within that clause. So no
change needed here?

~~~

AlterPublicationSchemaExceptTables:

2.
+ /* Collect OIDs of the desired new EXCEPT clause. */
+ foreach_ptr(PublicationRelInfo, pri, rels)
+ newexceptrelids = lappend_oid(newexceptrelids,
+   RelationGetRelid(pri->relation));

Perhaps "EXCEPT list" instead of EXCEPT clause was fine for this one
too. e.g. It really is building a list here.

~~~

Publication DropTables:

3.
+ *   true  - delete them silently.  Used by the SET path to clear stale
+ *           EXCEPT rows that are being replaced by a new EXCEPT clause.

I can't decide if it always makes sense to say the EXCEPT clause is
being "replaced". It may be getting removed entirely. Perhaps some
rewording helps?

SUGGESTION
Clears stale EXCEPT rows when ALTER PUBLICATION ... SET replaces or
removes the EXCEPT clause.


//////////
Patch 0005
//////////

There's a couple of threads [1][2] which might get pushed soon. Those
are going to mean a rebase will be needed, so watch out for them.

doc/src/sgml/logical-replication.sgml
======
doc/src/sgml/ref/alter_publication.sgml

1.
+   <varlistentry>
+    <term><literal>EXCEPT</literal></term>
+    <listitem>
+     <para>
+      When used with <literal>ADD TABLES IN SCHEMA</literal>
+      or <literal>SET TABLES IN SCHEMA</literal>, specifies
+      tables to be excluded from the publication.  Each named
+      table must belong to the schema specified in the same
+      <literal>TABLES IN SCHEMA</literal> clause.  Table names may be
+      schema-qualified or unqualified; unqualified names are implicitly
+      qualified with the schema named in the same clause.  See
+      <xref linkend="sql-createpublication"/> for further details on the
+      semantics of <literal>EXCEPT</literal>.
+     </para>
+     <para>
+      Dropping a table always removes it from the <literal>EXCEPT</literal>
+      clause.
+     </para>
+    </listitem>
+   </varlistentry>

Curiously, this does not mention FOR ALL TABLES EXCEPT?

I felt there was a missing earlier paragraph "When used with ALL TABLES ..."?

======
[1] https://www.postgresql.org/message-id/flat/CAHGQGwG2VA0iW8S%3DPDn34Ytx07F0TCH0vOP9y8jtPwDO5Tn7Qw%40m...
[2] https://www.postgresql.org/message-id/flat/CAHGQGwFJQNmiGX8tsmuCsv1yRWkS_sZkWA%2BZ8Hq6O2efstR3oA%40m...

Kind Regards,
Peter Smith.
Fujitsu Australia






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-28 08:48  shveta malik <shveta.malik@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  1 sibling, 2 replies; 196+ messages in thread

From: shveta malik @ 2026-07-28 08:48 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; shveta malik <shveta.malik@gmail.com>

On Thu, Jul 23, 2026 at 5:26 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
>
>
> Attached v23 patch set addressing all of the above comments, as well
> as the comments in [1] and [2].
>

A few comments on v23-001:

1)
+ if (CheckPublicationRelEntry(pubid, root, &root_except) && root_except)
+ ereport(ERROR,
+ errcode(ERRCODE_DUPLICATE_OBJECT),
+ errmsg("cannot add partition \"%s\" to publication \"%s\"",
+    RelationGetQualifiedRelationName(targetrel),

Is the errorcode "ERRCODE_DUPLICATE_OBJECT" intentional? To me it does
not look duplicate object as ROOT was in EXCEPT while this
we are trying to add to inclusion list. Other similar places have
different error, see:

+ if (exceptrelid == explicitrelid)
+ ereport(ERROR,
+ errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("table \"%s\" cannot be both published and excluded",
+    RelationGetQualifiedRelationName(pri->relation)));


2)
+ * Also reject any relation in explicitrelids whose partition root is in
+ * except_rels.  Otherwise the catalog would be inconsistent (root excluded,
+ * partition explicitly included), and the ancestor-cascade rule would
+ * silently override the include at replication time.

Shall we simply say:
/*
 * Also reject any relation in explicitrelids whose partition root is in
 * except_rels. Excluding a partition root means that the entire partition
 * tree is excluded, so a partition cannot be explicitly added to the
 * publication if its partition root is excluded.
 */

3)
Shall we change this too
+ errdetail("The table is currently named in the EXCEPT clause of the
publication."),
similar to:
+ errdetail("Partition root \"%s\" is named in the publication's
EXCEPT clause for schema \"%s\".",


4)
+
+ /*
+ * ancestors is NIL for a partition with a pending DETACH
+ * CONCURRENTLY.
+ */
+ if (ancestors != NIL)
+ root = llast_oid(ancestors);

I see non-null ancestors check at some places while other places do it
directly, see:
+ root = llast_oid(get_partition_ancestors(relid));

is it intentional?

5)
+ list_free(ancestors);

This is also done at some places, while missed at other places.

thanks
Shveta





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-28 09:08  shveta malik <shveta.malik@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  1 sibling, 1 reply; 196+ messages in thread

From: shveta malik @ 2026-07-28 09:08 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; shveta malik <shveta.malik@gmail.com>

On Tue, Jul 28, 2026 at 2:18 PM shveta malik <shveta.malik@gmail.com> wrote:
>
> On Thu, Jul 23, 2026 at 5:26 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
> >
> >
> > Attached v23 patch set addressing all of the above comments, as well
> > as the comments in [1] and [2].
> >
>
> A few comments on v23-001:
>
> 1)
> + if (CheckPublicationRelEntry(pubid, root, &root_except) && root_except)
> + ereport(ERROR,
> + errcode(ERRCODE_DUPLICATE_OBJECT),
> + errmsg("cannot add partition \"%s\" to publication \"%s\"",
> +    RelationGetQualifiedRelationName(targetrel),
>
> Is the errorcode "ERRCODE_DUPLICATE_OBJECT" intentional? To me it does
> not look duplicate object as ROOT was in EXCEPT while this
> we are trying to add to inclusion list. Other similar places have
> different error, see:
>
> + if (exceptrelid == explicitrelid)
> + ereport(ERROR,
> + errcode(ERRCODE_INVALID_PARAMETER_VALUE),
> + errmsg("table \"%s\" cannot be both published and excluded",
> +    RelationGetQualifiedRelationName(pri->relation)));
>
>
> 2)
> + * Also reject any relation in explicitrelids whose partition root is in
> + * except_rels.  Otherwise the catalog would be inconsistent (root excluded,
> + * partition explicitly included), and the ancestor-cascade rule would
> + * silently override the include at replication time.
>
> Shall we simply say:
> /*
>  * Also reject any relation in explicitrelids whose partition root is in
>  * except_rels. Excluding a partition root means that the entire partition
>  * tree is excluded, so a partition cannot be explicitly added to the
>  * publication if its partition root is excluded.
>  */
>
> 3)
> Shall we change this too
> + errdetail("The table is currently named in the EXCEPT clause of the
> publication."),
> similar to:
> + errdetail("Partition root \"%s\" is named in the publication's
> EXCEPT clause for schema \"%s\".",
>
>
> 4)
> +
> + /*
> + * ancestors is NIL for a partition with a pending DETACH
> + * CONCURRENTLY.
> + */
> + if (ancestors != NIL)
> + root = llast_oid(ancestors);
>
> I see non-null ancestors check at some places while other places do it
> directly, see:
> + root = llast_oid(get_partition_ancestors(relid));
>
> is it intentional?
>
> 5)
> + list_free(ancestors);
>
> This is also done at some places, while missed at other places.
>


Nisha, the changes in RelationBuildPublicationDesc() looks quite
tricky now. We are doing 'list_difference_oid' thrice:

--for schema-pub
--for schmea-pubs on complete ancestor tree
--for all-tables pub

Ultimately we are concatenating all individual pubids after
subtracting 'exceptpuboids' from each individual 'puboids' list. The
'exceptpuboids' is computed only once and doesn't change with each
computation. Why don't we uncondiitonally do list_concat_unique_oid
for all pub-ids
and only minus 'exceptpuboids' once at the end? Won't it work? Let me
know if I am missing something.

~~

I think, we can now merge 002 to 001, it will help in combined review
by placing except-validation logic where it should ultimately be.

thanks
Shveta






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-30 03:45  shveta malik <shveta.malik@gmail.com>
  parent: Peter Smith <smithpb2250@gmail.com>
  1 sibling, 1 reply; 196+ messages in thread

From: shveta malik @ 2026-07-30 03:45 UTC (permalink / raw)
  To: Peter Smith <smithpb2250@gmail.com>; Nisha Moond <nisha.moond412@gmail.com>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; shveta malik <shveta.malik@gmail.com>

On Fri, Jul 17, 2026 at 9:50 AM Peter Smith <smithpb2250@gmail.com> wrote:
>
> Hi Nisha.
>
> I noticed multiple places where these patches want to discover the
> root partition table OID, but they are not interested in the ancestor
> tree.
>
> I've created another thread/patch [1] to introduce a
> `get_partition_root` C function. I think this could simplify some of
> your code by removing the requirement to declare and free the unwanted
> ancestor lists.
>
> Please take a look and give your +1 there if you think it would be useful.
>
> ======
> [1] https://www.postgresql.org/message-id/CAHut%2BPtc73UpWSn4teMyMxQoHwGJjRwhWiu%3DhGJqAj5k2AOXEw%40mail...
>

Nisha, Peter,

Do you think we should make get_partition_root's patch as 0001 in this
thread and rebase rest of patches atop it? That way duplicated code in
many places will be removed. Another idea is to make
get_partition_root's patch as last patch here, but I prefer it as
first patch. Thoughts?

thanks
Shveta





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-30 04:23  Peter Smith <smithpb2250@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  0 siblings, 0 replies; 196+ messages in thread

From: Peter Smith @ 2026-07-30 04:23 UTC (permalink / raw)
  To: shveta malik <shveta.malik@gmail.com>; +Cc: Nisha Moond <nisha.moond412@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Thu, Jul 30, 2026 at 1:45 PM shveta malik <shveta.malik@gmail.com> wrote:
>
> On Fri, Jul 17, 2026 at 9:50 AM Peter Smith <smithpb2250@gmail.com> wrote:
> >
> > Hi Nisha.
> >
> > I noticed multiple places where these patches want to discover the
> > root partition table OID, but they are not interested in the ancestor
> > tree.
> >
> > I've created another thread/patch [1] to introduce a
> > `get_partition_root` C function. I think this could simplify some of
> > your code by removing the requirement to declare and free the unwanted
> > ancestor lists.
> >
> > Please take a look and give your +1 there if you think it would be useful.
> >
> > ======
> > [1] https://www.postgresql.org/message-id/CAHut%2BPtc73UpWSn4teMyMxQoHwGJjRwhWiu%3DhGJqAj5k2AOXEw%40mail...
> >
>
> Nisha, Peter,
>
> Do you think we should make get_partition_root's patch as 0001 in this
> thread and rebase rest of patches atop it? That way duplicated code in
> many places will be removed. Another idea is to make
> get_partition_root's patch as last patch here, but I prefer it as
> first patch. Thoughts?
>

FWIW, I don't think anything needs to be shuffled around -- we just
need things to happen in the right order.

The other patch was deliberately separated because it includes some
changes which IMO if put into patch 0001 of this thread would've just
received complaints like "these changes are not in scope".

Meanwhile, AFAIK that other patch is already completed (can you please
mark the CF entry as "ready-for-committer"). So, it can be
independently pushed any time -- the sooner the better.

Then, this EXCEPT code can be rebased to remove some duplicated code.

So,
1. Yes, the get_partition_root patch should come first
2. No, don't make it patch 0001 of this thread; Just try to get it pushed first

======
Kind Regards,
Peter Smith.
Fujitsu Australia





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-30 06:03  Nisha Moond <nisha.moond412@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  0 siblings, 3 replies; 196+ messages in thread

From: Nisha Moond @ 2026-07-30 06:03 UTC (permalink / raw)
  To: shveta malik <shveta.malik@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Tue, Jul 28, 2026 at 2:38 PM shveta malik <shveta.malik@gmail.com> wrote:
>
> Nisha, the changes in RelationBuildPublicationDesc() looks quite
> tricky now. We are doing 'list_difference_oid' thrice:
>
> --for schema-pub
> --for schmea-pubs on complete ancestor tree
> --for all-tables pub
>
> Ultimately we are concatenating all individual pubids after
> subtracting 'exceptpuboids' from each individual 'puboids' list. The
> 'exceptpuboids' is computed only once and doesn't change with each
> computation. Why don't we uncondiitonally do list_concat_unique_oid
> for all pub-ids
> and only minus 'exceptpuboids' once at the end? Won't it work? Let me
> know if I am missing something.
>

Done as suggested. The change modifies the existing code slightly, but
the function now seems simpler and easier to read overall. It works
well based on my testing. I'll do a deeper analysis to ensure it
doesn't change any existing behavior.

> ~~
>
> I think, we can now merge 002 to 001, it will help in combined review
> by placing except-validation logic where it should ultimately be.
>

Merged both into v24-0001.
~~~

Attached v24 patch set.

--
Thanks,
Nisha

Attachments: download all (4 files, .tar.gz)

v24-0001-Support-EXCEPT-clause-for-schema-level-publicati.patch (application/octet-stream, 84.0K) download From 40105e97e2726ed0fccec668a8096417582317c6 Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Tue, 16 Jun 2026 10:58:49 +0530 Subject: [PATCH v24 1/4] Support EXCEPT clause for schema-level publications Extend table exclusion support in publications to allow specific tables to be excluded from schema-level publications using an EXCEPT clause in CREATE PUBLICATION. Supported syntax: CREATE PUBLICATION <pub> FOR TABLES IN SCHEMA s EXCEPT (TABLE t1,...); --- src/backend/catalog/pg_publication.c | 237 ++++++++++++++--- src/backend/commands/publicationcmds.c | 241 ++++++++++++++++- src/backend/commands/tablecmds.c | 24 +- src/backend/parser/gram.y | 27 +- src/backend/replication/pgoutput/pgoutput.c | 37 ++- src/backend/utils/cache/relcache.c | 38 ++- src/bin/psql/describe.c | 44 +++- src/bin/psql/tab-complete.in.c | 35 ++- src/include/catalog/pg_publication.h | 1 + src/include/commands/publicationcmds.h | 2 + src/include/nodes/parsenodes.h | 2 + src/test/regress/expected/publication.out | 278 +++++++++++++++++++- src/test/regress/sql/publication.sql | 178 ++++++++++++- src/test/subscription/t/037_except.pl | 208 ++++++++++++++- 14 files changed, 1256 insertions(+), 96 deletions(-) diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index ea28ec319c5..b1c5b48c294 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -53,7 +53,7 @@ typedef struct * error if not. */ static void -check_publication_add_relation(PublicationRelInfo *pri) +check_publication_add_relation(PublicationRelInfo *pri, Oid pubid) { Relation targetrel = pri->relation; const char *relname; @@ -70,12 +70,51 @@ check_publication_add_relation(PublicationRelInfo *pri) errormsg = gettext_noop("cannot add relation \"%s\" to publication"); } - /* If in EXCEPT clause, must be root partitioned table */ - if (pri->except && targetrel->rd_rel->relispartition) - ereport(ERROR, - (errcode(ERRCODE_INVALID_PARAMETER_VALUE), - errmsg(errormsg, relname), - errdetail("This operation is not supported for individual partitions."))); + /* + * A partition cannot be added to a publication if its partition root is + * excluded by the publication. We follow the rule that excluding a + * partition root means that the entire partition tree is excluded. Thus, + * check whether the root is in the EXCEPT clause and reject adding the + * individual partition to the publication. + */ + if (targetrel->rd_rel->relispartition) + { + List *ancestors; + + if (pri->except) + { + /* If in EXCEPT clause, must be root partitioned table */ + ereport(ERROR, + (errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg(errormsg, relname), + errdetail("This operation is not supported for individual partitions."))); + } + + /* + * ancestors is NIL for a partition with a pending DETACH + * CONCURRENTLY, in which case there is no root to check. + */ + ancestors = get_partition_ancestors(RelationGetRelid(targetrel)); + if (ancestors != NIL) + { + Oid root = llast_oid(ancestors); + bool root_except; + + if (CheckPublicationRelEntry(pubid, root, &root_except) && root_except) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("cannot add partition \"%s\" to publication \"%s\"", + RelationGetQualifiedRelationName(targetrel), + get_publication_name(pubid, false)), + errdetail("Partition root \"%s\" is named in the publication's EXCEPT clause for schema \"%s\".", + quote_qualified_identifier(get_namespace_name(get_rel_namespace(root)), + get_rel_name(root)), + get_namespace_name(get_rel_namespace(root))), + errhint("Change the EXCEPT clause using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT.")); + } + + list_free(ancestors); + } /* Must be a regular or partitioned table */ if (RelationGetForm(targetrel)->relkind != RELKIND_RELATION && @@ -319,8 +358,7 @@ is_schema_publication(Oid pubid) } /* - * Returns true if the publication has explicitly included relation (i.e., - * not marked as EXCEPT). + * Returns true if the publication has a FOR TABLE clause. */ bool is_table_publication(Oid pubid) @@ -340,19 +378,23 @@ is_table_publication(Oid pubid) scan = systable_beginscan(pubrelsrel, PublicationRelPrpubidIndexId, true, NULL, 1, &scankey); - tup = systable_getnext(scan); - if (HeapTupleIsValid(tup)) - { - Form_pg_publication_rel pubrel; - pubrel = (Form_pg_publication_rel) GETSTRUCT(tup); - - /* - * For any publication, pg_publication_rel contains either only EXCEPT - * entries or only explicitly included tables. Therefore, examining - * the first tuple is sufficient to determine table inclusion. - */ - result = !pubrel->prexcept; + /* + * A publication can have both explicitly included (prexcept = false) and + * EXCEPT (prexcept = true) rows for the same pubid. For example: + * + * CREATE PUBLICATION pub1 FOR TABLE s1.t1, TABLES IN SCHEMA s2 EXCEPT + * (TABLE s2.t1); + * + * Scan until we find an explicitly included row. + */ + while (HeapTupleIsValid(tup = systable_getnext(scan))) + { + if (!((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept) + { + result = true; + break; + } } systable_endscan(scan); @@ -361,6 +403,27 @@ is_table_publication(Oid pubid) return result; } +/* + * Check whether a pg_publication_rel row exists for (pubid, relid); if so, + * set *is_except to its prexcept flag. + */ +bool +CheckPublicationRelEntry(Oid pubid, Oid relid, bool *is_except) +{ + HeapTuple tup; + + tup = SearchSysCache2(PUBLICATIONRELMAP, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (!HeapTupleIsValid(tup)) + return false; + + *is_except = ((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept; + ReleaseSysCache(tup); + + return true; +} + /* * Returns true if the relation has column list associated with the * publication, false otherwise. @@ -456,11 +519,26 @@ GetPubPartitionOptionRelations(List *result, PublicationPartOpt pub_partopt, * ancestor is at the end of the list. */ Oid -GetTopMostAncestorInPublication(Oid puboid, List *ancestors, int *ancestor_level) +GetTopMostAncestorInPublication(Oid puboid, List *ancestors, + int *ancestor_level) { ListCell *lc; Oid topmost_relid = InvalidOid; int level = 0; + bool root_except; + + if (ancestors == NIL) + return InvalidOid; + + /* + * If the partition root is excluded from this publication via an EXCEPT + * clause, the partition is not published through this publication, so + * return InvalidOid. Since only partition roots can appear in an EXCEPT + * clause, the root is the only ancestor worth a catalog lookup. + */ + if (CheckPublicationRelEntry(puboid, llast_oid(ancestors), &root_except) && + root_except) + return InvalidOid; /* * Find the "topmost" ancestor that is in this publication. @@ -547,6 +625,7 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, List *relids = NIL; int i; bool inval_except_table; + bool is_except; rel = table_open(PublicationRelRelationId, RowExclusiveLock); @@ -555,21 +634,30 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, * duplicates, it's here just to provide nicer error message in common * case. The real protection is the unique key on the catalog. */ - if (SearchSysCacheExists2(PUBLICATIONRELMAP, ObjectIdGetDatum(relid), - ObjectIdGetDatum(pubid))) + if (CheckPublicationRelEntry(pubid, relid, &is_except)) { table_close(rel, RowExclusiveLock); if (if_not_exists) return InvalidObjectAddress; - ereport(ERROR, - (errcode(ERRCODE_DUPLICATE_OBJECT), - errmsg("relation \"%s\" is already member of publication \"%s\"", - RelationGetRelationName(targetrel), pub->name))); + if (is_except) + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("cannot add table \"%s\" to publication \"%s\"", + RelationGetQualifiedRelationName(targetrel), + pub->name), + errdetail("The table is named in the publication's EXCEPT clause for schema \"%s\".", + get_namespace_name(RelationGetNamespace(targetrel))), + errhint("Change the EXCEPT clause using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT."))); + else + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("relation \"%s\" is already member of publication \"%s\"", + RelationGetRelationName(targetrel), pub->name))); } - check_publication_add_relation(pri); + check_publication_add_relation(pri, pubid); /* Validate and translate column names into a Bitmapset of attnums. */ attnums = pub_collist_validate(pri->relation, pri->columns); @@ -992,12 +1080,13 @@ GetIncludedPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) * Gets list of table oids that were specified in the EXCEPT clause for a * publication. * - * This should only be used FOR ALL TABLES publications. + * This is used for FOR ALL TABLES and FOR TABLES IN SCHEMA publications, + * both of which support EXCEPT TABLE. */ List * GetExcludedPublicationTables(Oid pubid, PublicationPartOpt pub_partopt) { - Assert(GetPublication(pubid)->alltables); + Assert(GetPublication(pubid)->alltables || is_schema_publication(pubid)); return get_publication_relations(pubid, pub_partopt, true); } @@ -1242,22 +1331,63 @@ GetSchemaPublicationRelations(Oid schemaid, PublicationPartOpt pub_partopt) /* * Gets the list of all relations published by FOR TABLES IN SCHEMA - * publication. + * publication, excluding any tables listed in EXCEPT clauses. */ List * GetAllSchemaPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) { List *result = NIL; List *pubschemalist = GetPublicationSchemas(pubid); + List *except_relids = NIL; ListCell *cell; + /* get the list of tables excluded via EXCEPT TABLE for this publication */ + if (pubschemalist != NIL) + except_relids = GetExcludedPublicationTables(pubid, pub_partopt); + foreach(cell, pubschemalist) { Oid schemaid = lfirst_oid(cell); List *schemaRels = NIL; schemaRels = GetSchemaPublicationRelations(schemaid, pub_partopt); - result = list_concat(result, schemaRels); + + if (except_relids != NIL) + { + /* filter out any tables that appear in the EXCEPT list */ + foreach_oid(relid, schemaRels) + { + bool excluded = list_member_oid(except_relids, relid); + + /* + * A partition whose root is excluded from the publication is + * also excluded, even if the partition itself lives in a + * different (included) schema. Only the topmost root of a + * partition hierarchy can ever appear in EXCEPT (see + * check_publication_add_relation()), so it's enough to check + * the last element of the ancestors list, rather than walking + * the whole chain. + */ + if (!excluded && get_rel_relispartition(relid)) + { + List *ancestors = get_partition_ancestors(relid); + + if (ancestors != NIL) + { + excluded = list_member_oid(except_relids, + llast_oid(ancestors)); + list_free(ancestors); + } + } + + if (!excluded) + result = lappend_oid(result, relid); + } + + list_free(schemaRels); + } + else + result = list_concat(result, schemaRels); } return result; @@ -1334,6 +1464,7 @@ is_table_publishable_in_publication(Oid relid, Publication *pub) { bool relispartition; List *ancestors = NIL; + bool is_except; /* * For non-pubviaroot publications, a partitioned table is never the @@ -1381,6 +1512,10 @@ is_table_publishable_in_publication(Oid relid, Publication *pub) */ /* + * If the partition root is excluded via the EXCEPT clause, the partition + * is never considered to be published through this publication. Check + * this before checking whether an ancestor is published. + * * If an ancestor is published, the partition's status depends on * publish_via_partition_root value. * @@ -1390,20 +1525,38 @@ is_table_publishable_in_publication(Oid relid, Publication *pub) * If it's false, the partition is covered by its ancestor's presence in * the publication, it should be included (return true). */ - if (relispartition && - OidIsValid(GetTopMostAncestorInPublication(pub->oid, ancestors, NULL))) - return !pub->pubviaroot; + if (relispartition) + { + /* + * ancestors can be NIL for a partition whose DETACH ... CONCURRENTLY + * is pending, in which case there is no ancestor to check. + */ + if (ancestors != NIL && + CheckPublicationRelEntry(pub->oid, llast_oid(ancestors), &is_except) && + is_except) + return false; + + if (OidIsValid(GetTopMostAncestorInPublication(pub->oid, ancestors, NULL))) + return !pub->pubviaroot; + } /* * Check whether the table is explicitly published via pg_publication_rel * or pg_publication_namespace. + * + * A pg_publication_rel row with prexcept=true means the table is + * explicitly excluded via EXCEPT and must not be reported as published, + * even if its schema is otherwise included. A row with prexcept=false + * means it is explicitly included. If no pg_publication_rel row exists, + * the table is published iff its schema appears in + * pg_publication_namespace. */ - return (SearchSysCacheExists2(PUBLICATIONRELMAP, - ObjectIdGetDatum(relid), - ObjectIdGetDatum(pub->oid)) || - SearchSysCacheExists2(PUBLICATIONNAMESPACEMAP, - ObjectIdGetDatum(get_rel_namespace(relid)), - ObjectIdGetDatum(pub->oid))); + if (CheckPublicationRelEntry(pub->oid, relid, &is_except)) + return !is_except; + else + return SearchSysCacheExists2(PUBLICATIONNAMESPACEMAP, + ObjectIdGetDatum(get_rel_namespace(relid)), + ObjectIdGetDatum(pub->oid)); } /* diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 440adb356ad..44a5599549d 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -22,6 +22,7 @@ #include "catalog/namespace.h" #include "catalog/objectaccess.h" #include "catalog/objectaddress.h" +#include "catalog/partition.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" #include "catalog/pg_namespace.h" @@ -71,6 +72,11 @@ static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); static char defGetGeneratedColsOption(DefElem *def); +static void CheckExceptNotInTableList(List *except_rels, List *explicitrelids); +static void ProcessSchemaExceptTables(Oid schemaid, List *except_tables, + ParseState *pstate, List **schemas, + List **schemas_with_except, + List **except_pubtables); static void @@ -175,16 +181,85 @@ parse_publication_options(ParseState *pstate, } } +/* + * Qualify unqualified EXCEPT table names with the given schema (rejecting + * any explicitly qualified with a different schema), and append them to + * *except_pubtables. + * + * Also rejects a schema being mentioned more than once with an EXCEPT + * clause, even if the EXCEPT clauses are identical — much like + * OpenTableList() rejects "FOR TABLE t1(a), t1(a)" despite the column + * lists matching. A schema can still be mentioned multiple times, just + * not more than once with EXCEPT. + * + * schemaid: OID of the schema for this TABLES IN SCHEMA mention. + * except_tables: the EXCEPT list (or NIL) attached to this mention. + * *schemas: accumulates all schema OIDs seen so far in this statement. + * *schemas_with_except: This is a subset of *schemas. Tracks which of + * the seen schemas of this statement had an EXCEPT clause. + * *except_pubtables: accumulates the (now schema-qualified) EXCEPT table + * entries across the whole statement. + */ +static void +ProcessSchemaExceptTables(Oid schemaid, List *except_tables, + ParseState *pstate, List **schemas, + List **schemas_with_except, List **except_pubtables) +{ + char *schema_name = get_namespace_name(schemaid); + bool schema_has_except = (except_tables != NIL); + + /* + * A repeating schema is only a problem if this mention has EXCEPT, or an + * earlier mention of the same schema did. + */ + if (list_member_oid(*schemas, schemaid)) + { + if (schema_has_except || + list_member_oid(*schemas_with_except, schemaid)) + ereport(ERROR, + errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("conflicting or redundant EXCEPT clauses for schema \"%s\"", + schema_name)); + } + + if (schema_has_except) + *schemas_with_except = lappend_oid(*schemas_with_except, schemaid); + + /* Filter out duplicates if the user specifies "sch1, sch1" */ + *schemas = list_append_unique_oid(*schemas, schemaid); + + if (!schema_has_except) + return; + + foreach_ptr(PublicationObjSpec, eobj, except_tables) + { + RangeVar *relation = eobj->pubtable->relation; + + if (relation->schemaname == NULL) + relation->schemaname = schema_name; + else if (strcmp(relation->schemaname, schema_name) != 0) + ereport(ERROR, + errcode(ERRCODE_INVALID_OBJECT_DEFINITION), + errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", + quote_qualified_identifier(relation->schemaname, relation->relname), + schema_name), + parser_errposition(pstate, eobj->location)); + + *except_pubtables = lappend(*except_pubtables, eobj->pubtable); + } +} + /* * Convert the PublicationObjSpecType list into schema oid list and * PublicationTable list. */ static void ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, - List **rels, List **exceptrels, List **schemas) + List **rels, List **except_pubtables, List **schemas) { ListCell *cell; PublicationObjSpec *pubobj; + List *schemas_with_except = NIL; if (!pubobjspec_list) return; @@ -200,7 +275,7 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, { case PUBLICATIONOBJ_EXCEPT_TABLE: pubobj->pubtable->except = true; - *exceptrels = lappend(*exceptrels, pubobj->pubtable); + *except_pubtables = lappend(*except_pubtables, pubobj->pubtable); break; case PUBLICATIONOBJ_TABLE: pubobj->pubtable->except = false; @@ -209,8 +284,10 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, case PUBLICATIONOBJ_TABLES_IN_SCHEMA: schemaid = get_namespace_oid(pubobj->name, false); - /* Filter out duplicates if user specifies "sch1, sch1" */ - *schemas = list_append_unique_oid(*schemas, schemaid); + ProcessSchemaExceptTables(schemaid, pubobj->except_tables, + pstate, schemas, + &schemas_with_except, + except_pubtables); break; case PUBLICATIONOBJ_TABLES_IN_CUR_SCHEMA: search_path = fetch_search_path(false); @@ -222,8 +299,10 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, schemaid = linitial_oid(search_path); list_free(search_path); - /* Filter out duplicates if user specifies "sch1, sch1" */ - *schemas = list_append_unique_oid(*schemas, schemaid); + ProcessSchemaExceptTables(schemaid, pubobj->except_tables, + pstate, schemas, + &schemas_with_except, + except_pubtables); break; default: /* shouldn't happen */ @@ -770,6 +849,60 @@ TransformPubWhereClauses(List *tables, const char *queryString, } } +/* + * Check that a table is not both excluded and published in the same DDL. + * + * An excluded relation (except_rels) cannot also be present in + * explicitrelids, the list of OIDs added to the publication by the explicit + * TABLE list. + * + * Also reject any relation in explicitrelids whose partition root is in + * except_rels. Excluding a partition root means that the entire partition + * tree is excluded, so a partition cannot be explicitly added to the + * publication if its partition root is excluded. + */ +static void +CheckExceptNotInTableList(List *except_rels, List *explicitrelids) +{ + foreach_oid(explicitrelid, explicitrelids) + { + Oid root = InvalidOid; + + if (get_rel_relispartition(explicitrelid)) + { + List *ancestors = get_partition_ancestors(explicitrelid); + + /* + * ancestors is NIL for a partition with a pending DETACH + * CONCURRENTLY. + */ + if (ancestors != NIL) + root = llast_oid(ancestors); + list_free(ancestors); + } + + foreach_ptr(PublicationRelInfo, pri, except_rels) + { + Oid exceptrelid = RelationGetRelid(pri->relation); + + if (exceptrelid == explicitrelid) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" cannot be both published and excluded", + RelationGetQualifiedRelationName(pri->relation))); + + if (OidIsValid(root) && exceptrelid == root) + ereport(ERROR, + (errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("partition \"%s\" cannot be both published and excluded", + quote_qualified_identifier(get_namespace_name(get_rel_namespace(explicitrelid)), + get_rel_name(explicitrelid))), + errdetail("Partition root \"%s\" is named in the publication's EXCEPT clause for schema \"%s\".", + RelationGetQualifiedRelationName(pri->relation), + get_namespace_name(RelationGetNamespace(pri->relation))))); + } + } +} /* * Given a list of tables that are going to be added to a publication, @@ -849,7 +982,7 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) char publish_generated_columns; AclResult aclresult; List *relations = NIL; - List *exceptrelations = NIL; + List *except_pubtables = NIL; List *schemaidlist = NIL; /* must have CREATE privilege on database */ @@ -936,16 +1069,16 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) /* Associate objects with the publication. */ ObjectsInPublicationToOids(stmt->pubobjects, pstate, &relations, - &exceptrelations, &schemaidlist); + &except_pubtables, &schemaidlist); if (stmt->for_all_tables) { /* Process EXCEPT table list */ - if (exceptrelations != NIL) + if (except_pubtables != NIL) { List *rels; - rels = OpenTableList(exceptrelations); + rels = OpenTableList(except_pubtables); PublicationAddTables(puboid, rels, true, NULL); CloseTableList(rels); } @@ -959,6 +1092,8 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) } else if (!stmt->for_all_sequences) { + List *explicitrelids = NIL; + /* FOR TABLES IN SCHEMA requires superuser */ if (schemaidlist != NIL && !superuser()) ereport(ERROR, @@ -978,6 +1113,20 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) publish_via_partition_root); PublicationAddTables(puboid, rels, true, NULL); + + /* + * Collect explicit table OIDs now, before we close the relation + * list, so that except-table validation below can check for + * contradictions without relying on a catalog scan that might not + * yet see the just-inserted rows. + */ + if (except_pubtables != NIL) + { + foreach_ptr(PublicationRelInfo, pri, rels) + explicitrelids = lappend_oid(explicitrelids, + RelationGetRelid(pri->relation)); + } + CloseTableList(rels); } @@ -989,6 +1138,22 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) */ LockSchemaList(schemaidlist); PublicationAddSchemas(puboid, schemaidlist, true, NULL); + + if (except_pubtables != NIL) + { + List *except_rels; + + except_rels = OpenTableList(except_pubtables); + + /* + * Validate that a table is not both explicitly included and + * excluded by the schema's EXCEPT clause. + */ + CheckExceptNotInTableList(except_rels, explicitrelids); + + PublicationAddTables(puboid, except_rels, true, NULL); + CloseTableList(except_rels); + } } } @@ -1829,6 +1994,62 @@ RemovePublicationSchemaById(Oid psoid) table_close(rel, RowExclusiveLock); } +/* + * Remove any EXCEPT clause entries for a relation from schema publications. + * Called when a table changes schema (ALTER TABLE ... SET SCHEMA), so that + * a schema-scoped exclusion does not silently follow the table to its new + * schema. + */ +void +RemoveSchemaPubExceptForRel(Oid relid, Oid oldNspOid, Oid newNspOid) +{ + List *pubids; + + /* + * If the table is not actually moving to a different schema (no-op ALTER + * TABLE ... SET SCHEMA <current_schema>), there is nothing to do. + */ + if (oldNspOid == newNspOid) + return; + + pubids = GetRelationExcludedPublications(relid); + + foreach_oid(pubid, pubids) + { + Oid proid; + + /* + * This problem does not apply to FOR ALL TABLES publications, because + * their EXCEPT clause is publication-scoped, not schema-scoped: the + * exclusion should persist regardless of what schema the table is in. + */ + if (!is_schema_publication(pubid)) + continue; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddress obj; + + ObjectAddressSet(obj, PublicationRelRelationId, proid); + + ereport(DEBUG2, + errmsg_internal("auto-remove exclusion of table \"%s.%s\" from publication \"%s\": table moved to schema \"%s\"", + get_namespace_name(oldNspOid), + get_rel_name(relid), + get_publication_name(pubid, false), + get_namespace_name(newNspOid))); + + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + list_free(pubids); +} + /* * Open relations specified by a PublicationTable list. * The returned tables are locked in ShareUpdateExclusiveLock mode in order to diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 6d4c457b820..1112f616c3a 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -49,6 +49,7 @@ #include "catalog/pg_opclass.h" #include "catalog/pg_policy.h" #include "catalog/pg_proc.h" +#include "catalog/pg_publication.h" #include "catalog/pg_publication_rel.h" #include "catalog/pg_rewrite.h" #include "catalog/pg_statistic_ext.h" @@ -63,6 +64,7 @@ #include "commands/event_trigger.h" #include "commands/extension.h" #include "commands/repack.h" +#include "commands/publicationcmds.h" #include "commands/sequence.h" #include "commands/tablecmds.h" #include "commands/tablespace.h" @@ -19745,6 +19747,16 @@ AlterTableNamespaceInternal(Relation rel, Oid oldNspOid, Oid nspOid, AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid, false, objsMoved); + /* + * Remove any EXCEPT clause entries for this relation from schema + * publications. A schema-scoped exclusion is no longer meaningful once + * the table moves to a different schema. + */ + if (rel->rd_rel->relkind == RELKIND_RELATION || + rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE) + RemoveSchemaPubExceptForRel(RelationGetRelid(rel), oldNspOid, + nspOid); + table_close(classRel, RowExclusiveLock); } @@ -21078,6 +21090,7 @@ ATExecAttachPartition(List **wqueue, Relation rel, PartitionCmd *cmd, if (exceptpuboids != NIL) { bool first = true; + bool has_alltables_pub = false; StringInfoData pubnames; initStringInfo(&pubnames); @@ -21091,17 +21104,22 @@ ATExecAttachPartition(List **wqueue, Relation rel, PartitionCmd *cmd, else appendStringInfo(&pubnames, _(", \"%s\""), pubname); first = false; + + if (GetPublication(pubid)->alltables) + has_alltables_pub = true; } ereport(ERROR, errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), - errmsg_plural("cannot attach table \"%s\" as partition because it is referenced in publication %s EXCEPT clause", - "cannot attach table \"%s\" as partition because it is referenced in publications %s EXCEPT clause", + errmsg_plural("cannot attach table \"%s\" as partition because it is named in EXCEPT clause of publication %s", + "cannot attach table \"%s\" as partition because it is named in EXCEPT clause of publications %s", list_length(exceptpuboids), RelationGetRelationName(attachrel), pubnames.data), errdetail("The publication EXCEPT clause cannot contain tables that are partitions."), - errhint("Change the publication's EXCEPT clause using ALTER PUBLICATION ... SET ALL TABLES.")); + errhint("%s", has_alltables_pub ? + _("Change the EXCEPT clause using ALTER PUBLICATION ... SET ALL TABLES ... EXCEPT.") : + _("Change the EXCEPT clause using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT."))); } list_free(exceptpuboids); diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y index 17035fb4d15..14520a5ccab 100644 --- a/src/backend/parser/gram.y +++ b/src/backend/parser/gram.y @@ -58,6 +58,7 @@ #include "nodes/makefuncs.h" #include "nodes/nodeFuncs.h" #include "parser/parser.h" +#include "utils/builtins.h" #include "utils/datetime.h" #include "utils/xml.h" @@ -11282,7 +11283,7 @@ AlterOwnerStmt: ALTER AGGREGATE aggregate_with_argtypes OWNER TO RoleSpec * pub_obj is one of: * * TABLE table [, ...] - * TABLES IN SCHEMA schema [, ...] + * TABLES IN SCHEMA schema [EXCEPT (TABLE table [, ...] )] [, ...] * *****************************************************************************/ @@ -11342,23 +11343,26 @@ PublicationObjSpec: $$->pubtable->columns = $3; $$->pubtable->whereClause = $4; } - | TABLES IN_P SCHEMA ColId + | TABLES IN_P SCHEMA ColId opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_SCHEMA; $$->name = $4; + $$->except_tables = $5; $$->location = @4; } - | TABLES IN_P SCHEMA CURRENT_SCHEMA + | TABLES IN_P SCHEMA CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_CUR_SCHEMA; + $$->except_tables = $5; $$->location = @4; } - | ColId opt_column_list OptWhereClause + | ColId opt_column_list OptWhereClause opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $4; /* * If either a row filter or column list is specified, create * a PublicationTable object. @@ -11402,10 +11406,11 @@ PublicationObjSpec: $$->pubtable->columns = $2; $$->pubtable->whereClause = $3; } - | CURRENT_SCHEMA + | CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $2; $$->location = @1; } ; @@ -20867,6 +20872,11 @@ preprocess_pub_all_objtype_list(List *all_objects_list, List **pubobjects, /* * Process pubobjspec_list to check for errors in any of the objects and * convert PUBLICATIONOBJ_CONTINUATION into appropriate PublicationObjSpecType. + * + * The except_tables attached to TABLES IN SCHEMA nodes are left in place here; + * ObjectsInPublicationToOids() qualifies their names, validates schema + * membership, and merges the qualified tables into its except_pubtables + * output list once the schema OID is known. */ static void preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) @@ -20895,6 +20905,13 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLE) { + /* EXCEPT is not valid for table objects */ + if (pubobj->except_tables != NIL) + ereport(ERROR, + errcode(ERRCODE_SYNTAX_ERROR), + errmsg("EXCEPT is not allowed for TABLE publication objects"), + parser_errposition(pubobj->location)); + /* relation name or pubtable must be set for this type of object */ if (!pubobj->name && !pubobj->pubtable) ereport(ERROR, diff --git a/src/backend/replication/pgoutput/pgoutput.c b/src/backend/replication/pgoutput/pgoutput.c index 4ecfcbff7ab..a1ca56e06ee 100644 --- a/src/backend/replication/pgoutput/pgoutput.c +++ b/src/backend/replication/pgoutput/pgoutput.c @@ -2280,10 +2280,41 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) } } - if (list_member_oid(pubids, pub->oid) || - list_member_oid(schemaPubids, pub->oid) || - ancestor_published) + if (list_member_oid(pubids, pub->oid) || ancestor_published) publish = true; + else if (list_member_oid(schemaPubids, pub->oid)) + { + Oid root_relid; + bool root_is_except = false; + + /* + * schemaPubids is the list of publications that include + * relid's own schema, independent of the ancestor walk + * above -- a partition can live in a different schema + * than its root. Still need to check for exclusion here, + * using the top-most ancestor since only a root + * (non-partition) table can appear in an EXCEPT clause. + */ + if (am_partition) + { + List *ancestors = get_partition_ancestors(relid); + + /* + * ancestors is NIL for a partition with a pending + * DETACH CONCURRENTLY; + */ + root_relid = (ancestors == NIL) ? relid : + llast_oid(ancestors); + list_free(ancestors); + } + else + root_relid = relid; + + CheckPublicationRelEntry(pub->oid, root_relid, &root_is_except); + + if (!root_is_except) + publish = true; + } } /* diff --git a/src/backend/utils/cache/relcache.c b/src/backend/utils/cache/relcache.c index 19c4ff6e75e..9ab97b9e8b4 100644 --- a/src/backend/utils/cache/relcache.c +++ b/src/backend/utils/cache/relcache.c @@ -5807,7 +5807,6 @@ RelationBuildPublicationDesc(Relation relation, PublicationDesc *pubdesc) { List *puboids = NIL; List *exceptpuboids = NIL; - List *alltablespuboids; ListCell *lc; MemoryContext oldcxt; Oid schemaid; @@ -5851,12 +5850,18 @@ RelationBuildPublicationDesc(Relation relation, PublicationDesc *pubdesc) if (relation->rd_rel->relispartition) { - Oid last_ancestor_relid; - - /* Add publications that the ancestors are in too. */ ancestors = get_partition_ancestors(relid); - last_ancestor_relid = llast_oid(ancestors); + /* + * Only the topmost root of a partition hierarchy can appear in an + * EXCEPT clause, so that is where exclusion has to be evaluated. + * ancestors is NIL for a partition with a pending DETACH + * CONCURRENTLY, in which case there is no root to consult. + */ + if (ancestors != NIL) + exceptpuboids = GetRelationExcludedPublications(llast_oid(ancestors)); + + /* Add publications that the ancestors are in too. */ foreach(lc, ancestors) { Oid ancestor = lfirst_oid(lc); @@ -5867,27 +5872,16 @@ RelationBuildPublicationDesc(Relation relation, PublicationDesc *pubdesc) puboids = list_concat_unique_oid(puboids, GetSchemaPublications(schemaid)); } - - /* - * Only the top-most ancestor can appear in the EXCEPT clause. - * Therefore, for a partition, exclusion must be evaluated at the - * top-most ancestor. - */ - exceptpuboids = GetRelationExcludedPublications(last_ancestor_relid); } else - { - /* - * For a regular table or a root partitioned table, check exclusion on - * table itself. - */ exceptpuboids = GetRelationExcludedPublications(relid); - } - alltablespuboids = GetAllTablesPublications(); - puboids = list_concat_unique_oid(puboids, - list_difference_oid(alltablespuboids, - exceptpuboids)); + puboids = list_concat_unique_oid(puboids, GetAllTablesPublications()); + + /* Drop the publications that exclude this relation. */ + if (exceptpuboids != NIL) + puboids = list_difference_oid(puboids, exceptpuboids); + foreach(lc, puboids) { Oid pubid = lfirst_oid(lc); diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c index ad9c8affb4f..bb980fc1c91 100644 --- a/src/bin/psql/describe.c +++ b/src/bin/psql/describe.c @@ -3036,7 +3036,29 @@ describeOneTableDetails(const char *schemaname, "FROM pg_catalog.pg_publication p\n" " JOIN pg_catalog.pg_publication_namespace pn ON p.oid = pn.pnpubid\n" " JOIN pg_catalog.pg_class pc ON pc.relnamespace = pn.pnnspid\n" - "WHERE pc.oid ='%s' and pg_catalog.pg_relation_is_publishable('%s')\n" + "WHERE pc.oid ='%s' and pg_catalog.pg_relation_is_publishable('%s')\n", + oid, oid); + + if (pset.sversion >= 200000) + { + /* + * Publishing the schema does not publish a table named in the + * publication's EXCEPT clause, nor a partition whose root is + * named there, since excluding a root excludes the whole + * partition tree. Unlike the FOR ALL TABLES case below, a + * schema publication can have both kinds of + * pg_publication_rel row, so prexcept has to be tested. + */ + appendPQExpBuffer(&buf, + " AND NOT EXISTS (\n" + " SELECT 1\n" + " FROM pg_catalog.pg_publication_rel pr\n" + " WHERE pr.prpubid = p.oid AND pr.prexcept AND\n" + " (pr.prrelid = '%s' OR pr.prrelid = pg_catalog.pg_partition_root('%s')))\n", + oid, oid); + } + + appendPQExpBuffer(&buf, "UNION\n" "SELECT pubname\n" " , pg_catalog.pg_get_expr(pr.prqual, c.oid)\n" @@ -3060,7 +3082,7 @@ describeOneTableDetails(const char *schemaname, " FROM pg_catalog.pg_publication_namespace pn\n" " WHERE pn.pnpubid = p.oid\n" " AND pn.pnnspid = c.relnamespace)\n", - oid, oid, oid); + oid); if (pset.sversion >= 190000) { @@ -6839,6 +6861,24 @@ describePublications(const char *pattern) if (!addFooterToPublicationDesc(&buf, _("Tables from schemas:"), true, &cont)) goto error_return; + + if (pset.sversion >= 200000) + { + /* + * Get tables in the EXCEPT clause for this schema + * publication. + */ + printfPQExpBuffer(&buf, + "SELECT concat(c.relnamespace::regnamespace, '.', c.relname)\n" + "FROM pg_catalog.pg_class c\n" + " JOIN pg_catalog.pg_publication_rel pr ON c.oid = pr.prrelid\n" + "WHERE pr.prpubid = '%s'\n" + " AND pr.prexcept\n" + "ORDER BY 1", pubid); + if (!addFooterToPublicationDesc(&buf, _("Except tables:"), + true, &cont)) + goto error_return; + } } } else diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index 17dcabe755f..04f2b63535f 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -1065,6 +1065,24 @@ static const SchemaQuery Query_for_trigger_of_table = { "SELECT nspname FROM pg_catalog.pg_namespace "\ " WHERE nspname LIKE '%s'" +#define Query_for_list_of_tables_in_schema \ +"SELECT n.nspname || '.' || c.relname "\ +" FROM pg_catalog.pg_class c "\ +" JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "\ +" WHERE c.relkind IN (" CppAsString2(RELKIND_RELATION) ", " \ + CppAsString2(RELKIND_PARTITIONED_TABLE) ") "\ +" AND (n.nspname || '.' || c.relname) LIKE '%s' "\ +" AND n.nspname = '%s'" + +#define Query_for_list_of_tables_in_current_schema \ +"SELECT c.relname "\ +" FROM pg_catalog.pg_class c "\ +" JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "\ +" WHERE c.relkind IN (" CppAsString2(RELKIND_RELATION) ", " \ + CppAsString2(RELKIND_PARTITIONED_TABLE) ") "\ +" AND c.relname LIKE '%s' "\ +" AND n.nspname = pg_catalog.current_schema()" + /* Use COMPLETE_WITH_QUERY_VERBATIM with these queries for GUC names: */ #define Query_for_list_of_alter_system_set_vars \ "SELECT pg_catalog.lower(name) FROM pg_catalog.pg_settings "\ @@ -3777,8 +3795,21 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); - else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && (!ends_with(prev_wd, ','))) - COMPLETE_WITH("WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE", "WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* Complete "CREATE PUBLICATION <name> [...] WITH" */ else if (Matches("CREATE", "PUBLICATION", MatchAnyN, "WITH", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/include/catalog/pg_publication.h b/src/include/catalog/pg_publication.h index 89b4bb14f62..d241b781ccc 100644 --- a/src/include/catalog/pg_publication.h +++ b/src/include/catalog/pg_publication.h @@ -192,6 +192,7 @@ extern List *GetPubPartitionOptionRelations(List *result, Oid relid); extern Oid GetTopMostAncestorInPublication(Oid puboid, List *ancestors, int *ancestor_level); +extern bool CheckPublicationRelEntry(Oid pubid, Oid relid, bool *is_except); extern bool is_publishable_relation(Relation rel); extern bool is_schema_publication(Oid pubid); diff --git a/src/include/commands/publicationcmds.h b/src/include/commands/publicationcmds.h index 4cf45c17cc5..fb1703aa675 100644 --- a/src/include/commands/publicationcmds.h +++ b/src/include/commands/publicationcmds.h @@ -27,6 +27,8 @@ extern void AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt); extern void RemovePublicationById(Oid pubid); extern void RemovePublicationRelById(Oid proid); extern void RemovePublicationSchemaById(Oid psoid); +extern void RemoveSchemaPubExceptForRel(Oid relid, Oid oldNspOid, + Oid newNspOid); extern ObjectAddress AlterPublicationOwner(const char *name, Oid newOwnerId); extern void AlterPublicationOwner_oid(Oid pubid, Oid newOwnerId); diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h index 5c8f9a07b62..0cccb4393c2 100644 --- a/src/include/nodes/parsenodes.h +++ b/src/include/nodes/parsenodes.h @@ -4530,6 +4530,8 @@ typedef struct PublicationObjSpec PublicationObjSpecType pubobjtype; /* type of this publication object */ char *name; PublicationTable *pubtable; + List *except_tables; /* tables specified in the EXCEPT clause (for + * TABLES IN SCHEMA) */ ParseLoc location; /* token location, or -1 if unknown */ } PublicationObjSpec; diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 9c6386d518a..f8f4b187c0a 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -279,6 +279,12 @@ CREATE PUBLICATION testpub_foralltables_excepttable2 FOR ALL TABLES EXCEPT (test ERROR: syntax error at or near "testpub_tbl1" LINE 1: ..._foralltables_excepttable2 FOR ALL TABLES EXCEPT (testpub_tb... ^ +-- fail - EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testpub_tbl3); +ERROR: EXCEPT is not allowed for TABLE publication objects +LINE 2: FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testp... + ^ --------------------------------------------- -- SET ALL TABLES/SEQUENCES --------------------------------------------- @@ -473,13 +479,186 @@ CREATE TABLE tab_main (a int) PARTITION BY RANGE(a); -- Attaching a partition is not allowed if the partitioned table appears in a -- publication's EXCEPT clause. ALTER TABLE tab_main ATTACH PARTITION testpub_root FOR VALUES FROM (0) TO (200); -ERROR: cannot attach table "testpub_root" as partition because it is referenced in publication "testpub8" EXCEPT clause +ERROR: cannot attach table "testpub_root" as partition because it is named in EXCEPT clause of publication "testpub8" DETAIL: The publication EXCEPT clause cannot contain tables that are partitions. -HINT: Change the publication's EXCEPT clause using ALTER PUBLICATION ... SET ALL TABLES. +HINT: Change the EXCEPT clause using ALTER PUBLICATION ... SET ALL TABLES ... EXCEPT. RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Create same-named tables in public to verify unqualified EXCEPT entries +-- are qualified with the named schema, not public +CREATE TABLE testpub_nopk (foo int, bar int); +CREATE TABLE testpub_tbl_s1 (a int primary key, b text); +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + Publication testpub_schema_except1 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- Exclude multiple tables using unqualified names; same-named tables exist in +-- public to confirm unqualified names resolve to pub_test, not public +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + Publication testpub_schema_except2 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_nopk" + "pub_test.testpub_tbl_s1" + +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testp... + ^ +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); +ERROR: table "pub_test.testpub_tbl_s1" in EXCEPT clause does not belong to schema "public" +LINE 2: ...R TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.t... + ^ +-- Multiple schemas each with their own EXCEPT clause +CREATE PUBLICATION testpub_schema_except_multi + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_schema_except_multi + Publication testpub_schema_except_multi + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- fail: same schema repeated with same EXCEPT clauses +CREATE PUBLICATION testpub_schema_except_conflict + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: conflicting or redundant EXCEPT clauses for schema "pub_test" +-- fail: same schema repeated with conflicting or no EXCEPT clauses +CREATE PUBLICATION testpub_schema_except_conflict2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2), + pub_test; +ERROR: conflicting or redundant EXCEPT clauses for schema "pub_test" +-- ALTER TABLE ... SET SCHEMA on a table excluded by a schema publication: +-- the schema-scoped exclusion is no longer meaningful once the table moves +-- out of its schema, so the exclusion is auto-removed. +CREATE PUBLICATION testpub_schema_except_setsch + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_schema_except_setsch + Publication testpub_schema_except_setsch + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s2" + +ALTER TABLE pub_test.testpub_tbl_s2 SET SCHEMA public; +\dRp+ testpub_schema_except_setsch + Publication testpub_schema_except_setsch + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + +DROP PUBLICATION testpub_schema_except_setsch; +-- Restore for further tests +ALTER TABLE public.testpub_tbl_s2 SET SCHEMA pub_test; +-- fail: table appears in both the explicit table list and the EXCEPT clause +CREATE PUBLICATION testpub_except_conflict + FOR TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot be both published and excluded +-- fail: nonexistent table in EXCEPT clause +CREATE PUBLICATION testpub_except_norel + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- fail: partition cannot appear in EXCEPT clause; only root tables are allowed +CREATE TABLE pub_test.testpub_parted_s (a int) PARTITION BY LIST (a); +CREATE TABLE pub_test.testpub_part_s PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (1); +CREATE PUBLICATION testpub_except_partition + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); +ERROR: cannot specify relation "pub_test.testpub_part_s" in the publication EXCEPT clause +DETAIL: This operation is not supported for individual partitions. +-- fail: TABLE keyword is required for the first entry in the EXCEPT clause +CREATE PUBLICATION testpub_except_nokw + FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +ERROR: syntax error at or near "testpub_nopk" +LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + ^ +-- Check that a table excluded from a schema publication is reported only as +-- excluded and not as published. +\d pub_test.testpub_nopk + Table "pub_test.testpub_nopk" + Column | Type | Collation | Nullable | Default +--------+---------+-----------+----------+--------- + foo | integer | | | + bar | integer | | | +Included in publications: + "testpub_schema_except1" + "testpub_schema_except_multi" +Excluded from publications: + "testpub_schema_except2" + +-- fail: ADD TABLE for a partition is rejected when a partition ancestor +-- is currently in the publication's EXCEPT list. +CREATE PUBLICATION testpub_except_ancestor + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ALTER PUBLICATION testpub_except_ancestor ADD TABLE pub_test.testpub_part_s; +ERROR: cannot add partition "pub_test.testpub_part_s" to publication "testpub_except_ancestor" +DETAIL: Partition root "pub_test.testpub_parted_s" is named in the publication's EXCEPT clause for schema "pub_test". +HINT: Change the EXCEPT clause using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT. +DROP PUBLICATION testpub_except_ancestor; +-- fail: same contradiction (explicit partition + EXCEPT-ed ancestor), but +-- given in a single statement instead of two separate ones +CREATE PUBLICATION testpub_except_ancestor_same_create + FOR TABLE pub_test.testpub_part_s, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ERROR: partition "pub_test.testpub_part_s" cannot be both published and excluded +DETAIL: Partition root "pub_test.testpub_parted_s" is named in the publication's EXCEPT clause for schema "pub_test". +-- fail: same contradiction as above, but the partition lives in a different +-- schema (public) than its EXCEPT-ed root (pub_test) +CREATE TABLE public.testpub_part_s2 PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (2); +CREATE PUBLICATION testpub_except_ancestor_cross_schema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s), + TABLE public.testpub_part_s2; +ERROR: partition "public.testpub_part_s2" cannot be both published and excluded +DETAIL: Partition root "pub_test.testpub_parted_s" is named in the publication's EXCEPT clause for schema "pub_test". +DROP TABLE public.testpub_part_s2; +-- Cleanup +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP TABLE pub_test.testpub_parted_s CASCADE; +DROP TABLE testpub_nopk, testpub_tbl_s1; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +--------------------------------------------- +-- Tests for publications with SEQUENCES +--------------------------------------------- CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; -- FOR ALL SEQUENCES @@ -1970,6 +2149,54 @@ ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b); ERROR: column specification not allowed for schema LINE 1: ...TION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b)... ^ +-- EXCEPT clause with CURRENT_SCHEMA: cross-schema entry must be rejected +SET search_path = pub_test1; +-- qualified name from wrong schema -> error +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.tbl1); +ERROR: table "pub_test2.tbl1" in EXCEPT clause does not belong to schema "pub_test1" +LINE 1: ...FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.... + ^ +-- unqualified name implicitly qualified with current schema (pub_test1.tbl) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl); +RESET client_min_messages; +\dRp+ testpub_cursch_except + Publication testpub_cursch_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test1" +Except tables: + "pub_test1.tbl" + +DROP PUBLICATION testpub_cursch_except; +-- succeeds: CURRENT_SCHEMA and pub_test1 (same schema) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_named_same + FOR TABLES IN SCHEMA CURRENT_SCHEMA, pub_test1; +RESET client_min_messages; +\dRp+ testpub_cursch_named_same + Publication testpub_cursch_named_same + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test1" + +DROP PUBLICATION testpub_cursch_named_same; +-- fail: CURRENT_SCHEMA and pub_test1 (same schema) have +-- conflicting EXCEPT clauses +CREATE PUBLICATION testpub_cursch_named_conflict + FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl), + pub_test1 EXCEPT (TABLE tbl1); +ERROR: conflicting or redundant EXCEPT clauses for schema "pub_test1" +-- fail: two CURRENT_SCHEMA mentions with conflicting EXCEPT clauses +CREATE PUBLICATION testpub_cursch_cursch_conflict + FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl), + CURRENT_SCHEMA EXCEPT (TABLE tbl1); +ERROR: conflicting or redundant EXCEPT clauses for schema "pub_test1" +RESET search_path; -- cleanup pub_test1 schema for invalidation tests ALTER PUBLICATION testpub2_forschema DROP TABLES IN SCHEMA pub_test1; DROP PUBLICATION testpub3_forschema, testpub4_forschema, testpub5_forschema, testpub6_forschema, testpub_fortable; @@ -2321,6 +2548,7 @@ DROP ROLE regress_publication_user_dummy; -- Test pg_get_publication_tables(text[], oid) function CREATE SCHEMA gpt_test_sch; CREATE TABLE gpt_test_sch.tbl_sch (id int); +CREATE TABLE gpt_test_sch.tbl_sch2 (id int); CREATE TABLE tbl_normal (id int); CREATE TABLE tbl_parent (id1 int, id2 int, id3 int) PARTITION BY RANGE (id1); CREATE TABLE tbl_part1 PARTITION OF tbl_parent FOR VALUES FROM (1) TO (10); @@ -2331,6 +2559,7 @@ CREATE PUBLICATION pub_all_no_viaroot FOR ALL TABLES WITH (publish_via_partition CREATE PUBLICATION pub_all_except FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = true); CREATE PUBLICATION pub_all_except_no_viaroot FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_schema FOR TABLES IN SCHEMA gpt_test_sch; +CREATE PUBLICATION pub_schema_except FOR TABLES IN SCHEMA gpt_test_sch EXCEPT (TABLE gpt_test_sch.tbl_sch); CREATE PUBLICATION pub_normal FOR TABLE tbl_normal WHERE (id < 10); CREATE PUBLICATION pub_part_leaf FOR TABLE tbl_part1 WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_part_parent FOR TABLE tbl_parent (id1, id2) WHERE (id1 = 10) WITH (publish_via_partition_root = true); @@ -2482,6 +2711,44 @@ SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_part1'); -- no r ---------+---------+-------+------ (0 rows) +-- test for EXCEPT clause with schema publication +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch'); -- no result (excluded) + pubname | relname | attrs | qual +---------+---------+-------+------ +(0 rows) + +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch2'); -- one row (included via schema) + pubname | relname | attrs | qual +-------------------+----------+-------+------ + pub_schema_except | tbl_sch2 | 1 | +(1 row) + +-- test for EXCEPT clause with schema publication, where the excluded root's +-- partition lives in a different schema that is separately, fully included +-- (no EXCEPT) in the same publication. The root's exclusion must cascade to +-- the partition regardless of the partition's own schema membership. +CREATE SCHEMA gpt_cross_sch1; +CREATE SCHEMA gpt_cross_sch2; +CREATE TABLE gpt_cross_sch1.croot (id int) PARTITION BY RANGE (id); +CREATE TABLE gpt_cross_sch2.cpart1 PARTITION OF gpt_cross_sch1.croot FOR VALUES FROM (1) TO (10); +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION pub_cross_schema_except FOR TABLES IN SCHEMA gpt_cross_sch1 EXCEPT (TABLE gpt_cross_sch1.croot), TABLES IN SCHEMA gpt_cross_sch2; +RESET client_min_messages; +SELECT * FROM test_gpt(ARRAY['pub_cross_schema_except'], 'gpt_cross_sch1.croot'); -- no result (excluded) + pubname | relname | attrs | qual +---------+---------+-------+------ +(0 rows) + +-- no result (excluded via cascading root exclusion, even though cpart1's own +-- schema gpt_cross_sch2 is separately, fully included with no EXCEPT) +SELECT * FROM test_gpt(ARRAY['pub_cross_schema_except'], 'gpt_cross_sch2.cpart1'); + pubname | relname | attrs | qual +---------+---------+-------+------ +(0 rows) + +DROP PUBLICATION pub_cross_schema_except; +DROP TABLE gpt_cross_sch2.cpart1, gpt_cross_sch1.croot; +DROP SCHEMA gpt_cross_sch1, gpt_cross_sch2; -- two rows with different row filter SELECT * FROM test_gpt(ARRAY['pub_all', 'pub_normal'], 'tbl_normal'); pubname | relname | attrs | qual @@ -2534,6 +2801,7 @@ DROP PUBLICATION pub_all_no_viaroot; DROP PUBLICATION pub_all_except; DROP PUBLICATION pub_all_except_no_viaroot; DROP PUBLICATION pub_schema; +DROP PUBLICATION pub_schema_except; DROP PUBLICATION pub_normal; DROP PUBLICATION pub_part_leaf; DROP PUBLICATION pub_part_parent; @@ -2542,7 +2810,9 @@ DROP PUBLICATION pub_part_parent_child; DROP VIEW gpt_test_view; DROP TABLE tbl_normal, tbl_parent, tbl_part1; DROP SCHEMA gpt_test_sch CASCADE; -NOTICE: drop cascades to table gpt_test_sch.tbl_sch +NOTICE: drop cascades to 2 other objects +DETAIL: drop cascades to table gpt_test_sch.tbl_sch +drop cascades to table gpt_test_sch.tbl_sch2 -- stage objects for pg_dump tests CREATE SCHEMA pubme CREATE TABLE t0 (c int, d int) CREATE TABLE t1 (c int); CREATE SCHEMA pubme2 CREATE TABLE t0 (c int, d int); diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index fac54b02e27..dcdc1eb5df9 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -125,6 +125,9 @@ CREATE PUBLICATION testpub_foralltables_excepttable1 FOR ALL TABLES EXCEPT (TABL \d testpub_tbl1 -- fail - first table in the EXCEPT list should use TABLE keyword CREATE PUBLICATION testpub_foralltables_excepttable2 FOR ALL TABLES EXCEPT (testpub_tbl1, testpub_tbl2); +-- fail - EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testpub_tbl3); --------------------------------------------- -- SET ALL TABLES/SEQUENCES @@ -222,7 +225,119 @@ RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Create same-named tables in public to verify unqualified EXCEPT entries +-- are qualified with the named schema, not public +CREATE TABLE testpub_nopk (foo int, bar int); +CREATE TABLE testpub_tbl_s1 (a int primary key, b text); + +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + +-- Exclude multiple tables using unqualified names; same-named tables exist in +-- public to confirm unqualified names resolve to pub_test, not public +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); + +-- Multiple schemas each with their own EXCEPT clause +CREATE PUBLICATION testpub_schema_except_multi + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_schema_except_multi + +-- fail: same schema repeated with same EXCEPT clauses +CREATE PUBLICATION testpub_schema_except_conflict + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: same schema repeated with conflicting or no EXCEPT clauses +CREATE PUBLICATION testpub_schema_except_conflict2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2), + pub_test; + +-- ALTER TABLE ... SET SCHEMA on a table excluded by a schema publication: +-- the schema-scoped exclusion is no longer meaningful once the table moves +-- out of its schema, so the exclusion is auto-removed. +CREATE PUBLICATION testpub_schema_except_setsch + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_schema_except_setsch +ALTER TABLE pub_test.testpub_tbl_s2 SET SCHEMA public; +\dRp+ testpub_schema_except_setsch +DROP PUBLICATION testpub_schema_except_setsch; +-- Restore for further tests +ALTER TABLE public.testpub_tbl_s2 SET SCHEMA pub_test; + +-- fail: table appears in both the explicit table list and the EXCEPT clause +CREATE PUBLICATION testpub_except_conflict + FOR TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: nonexistent table in EXCEPT clause +CREATE PUBLICATION testpub_except_norel + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- fail: partition cannot appear in EXCEPT clause; only root tables are allowed +CREATE TABLE pub_test.testpub_parted_s (a int) PARTITION BY LIST (a); +CREATE TABLE pub_test.testpub_part_s PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (1); +CREATE PUBLICATION testpub_except_partition + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); + +-- fail: TABLE keyword is required for the first entry in the EXCEPT clause +CREATE PUBLICATION testpub_except_nokw + FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + +-- Check that a table excluded from a schema publication is reported only as +-- excluded and not as published. +\d pub_test.testpub_nopk + +-- fail: ADD TABLE for a partition is rejected when a partition ancestor +-- is currently in the publication's EXCEPT list. +CREATE PUBLICATION testpub_except_ancestor + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ALTER PUBLICATION testpub_except_ancestor ADD TABLE pub_test.testpub_part_s; +DROP PUBLICATION testpub_except_ancestor; + +-- fail: same contradiction (explicit partition + EXCEPT-ed ancestor), but +-- given in a single statement instead of two separate ones +CREATE PUBLICATION testpub_except_ancestor_same_create + FOR TABLE pub_test.testpub_part_s, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); + +-- fail: same contradiction as above, but the partition lives in a different +-- schema (public) than its EXCEPT-ed root (pub_test) +CREATE TABLE public.testpub_part_s2 PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (2); +CREATE PUBLICATION testpub_except_ancestor_cross_schema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s), + TABLE public.testpub_part_s2; +DROP TABLE public.testpub_part_s2; + +-- Cleanup +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP TABLE pub_test.testpub_parted_s CASCADE; +DROP TABLE testpub_nopk, testpub_tbl_s1; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; + +--------------------------------------------- +-- Tests for publications with SEQUENCES +--------------------------------------------- CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; @@ -1194,6 +1309,38 @@ ALTER PUBLICATION testpub1_forschema SET TABLES IN SCHEMA pub_test1, pub_test1; ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo (a, b); ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b); +-- EXCEPT clause with CURRENT_SCHEMA: cross-schema entry must be rejected +SET search_path = pub_test1; +-- qualified name from wrong schema -> error +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.tbl1); +-- unqualified name implicitly qualified with current schema (pub_test1.tbl) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl); +RESET client_min_messages; +\dRp+ testpub_cursch_except +DROP PUBLICATION testpub_cursch_except; + +-- succeeds: CURRENT_SCHEMA and pub_test1 (same schema) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_named_same + FOR TABLES IN SCHEMA CURRENT_SCHEMA, pub_test1; +RESET client_min_messages; +\dRp+ testpub_cursch_named_same +DROP PUBLICATION testpub_cursch_named_same; + +-- fail: CURRENT_SCHEMA and pub_test1 (same schema) have +-- conflicting EXCEPT clauses +CREATE PUBLICATION testpub_cursch_named_conflict + FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl), + pub_test1 EXCEPT (TABLE tbl1); + +-- fail: two CURRENT_SCHEMA mentions with conflicting EXCEPT clauses +CREATE PUBLICATION testpub_cursch_cursch_conflict + FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl), + CURRENT_SCHEMA EXCEPT (TABLE tbl1); + +RESET search_path; + -- cleanup pub_test1 schema for invalidation tests ALTER PUBLICATION testpub2_forschema DROP TABLES IN SCHEMA pub_test1; DROP PUBLICATION testpub3_forschema, testpub4_forschema, testpub5_forschema, testpub6_forschema, testpub_fortable; @@ -1448,6 +1595,7 @@ DROP ROLE regress_publication_user_dummy; -- Test pg_get_publication_tables(text[], oid) function CREATE SCHEMA gpt_test_sch; CREATE TABLE gpt_test_sch.tbl_sch (id int); +CREATE TABLE gpt_test_sch.tbl_sch2 (id int); CREATE TABLE tbl_normal (id int); CREATE TABLE tbl_parent (id1 int, id2 int, id3 int) PARTITION BY RANGE (id1); CREATE TABLE tbl_part1 PARTITION OF tbl_parent FOR VALUES FROM (1) TO (10); @@ -1459,6 +1607,7 @@ CREATE PUBLICATION pub_all_no_viaroot FOR ALL TABLES WITH (publish_via_partition CREATE PUBLICATION pub_all_except FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = true); CREATE PUBLICATION pub_all_except_no_viaroot FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_schema FOR TABLES IN SCHEMA gpt_test_sch; +CREATE PUBLICATION pub_schema_except FOR TABLES IN SCHEMA gpt_test_sch EXCEPT (TABLE gpt_test_sch.tbl_sch); CREATE PUBLICATION pub_normal FOR TABLE tbl_normal WHERE (id < 10); CREATE PUBLICATION pub_part_leaf FOR TABLE tbl_part1 WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_part_parent FOR TABLE tbl_parent (id1, id2) WHERE (id1 = 10) WITH (publish_via_partition_root = true); @@ -1515,6 +1664,32 @@ SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'gpt_test_sch.tbl_sch SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_parent'); -- no result (excluded) SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_part1'); -- no result +-- test for EXCEPT clause with schema publication +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch'); -- no result (excluded) +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch2'); -- one row (included via schema) + +-- test for EXCEPT clause with schema publication, where the excluded root's +-- partition lives in a different schema that is separately, fully included +-- (no EXCEPT) in the same publication. The root's exclusion must cascade to +-- the partition regardless of the partition's own schema membership. +CREATE SCHEMA gpt_cross_sch1; +CREATE SCHEMA gpt_cross_sch2; +CREATE TABLE gpt_cross_sch1.croot (id int) PARTITION BY RANGE (id); +CREATE TABLE gpt_cross_sch2.cpart1 PARTITION OF gpt_cross_sch1.croot FOR VALUES FROM (1) TO (10); + +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION pub_cross_schema_except FOR TABLES IN SCHEMA gpt_cross_sch1 EXCEPT (TABLE gpt_cross_sch1.croot), TABLES IN SCHEMA gpt_cross_sch2; +RESET client_min_messages; + +SELECT * FROM test_gpt(ARRAY['pub_cross_schema_except'], 'gpt_cross_sch1.croot'); -- no result (excluded) +-- no result (excluded via cascading root exclusion, even though cpart1's own +-- schema gpt_cross_sch2 is separately, fully included with no EXCEPT) +SELECT * FROM test_gpt(ARRAY['pub_cross_schema_except'], 'gpt_cross_sch2.cpart1'); + +DROP PUBLICATION pub_cross_schema_except; +DROP TABLE gpt_cross_sch2.cpart1, gpt_cross_sch1.croot; +DROP SCHEMA gpt_cross_sch1, gpt_cross_sch2; + -- two rows with different row filter SELECT * FROM test_gpt(ARRAY['pub_all', 'pub_normal'], 'tbl_normal'); @@ -1543,6 +1718,7 @@ DROP PUBLICATION pub_all_no_viaroot; DROP PUBLICATION pub_all_except; DROP PUBLICATION pub_all_except_no_viaroot; DROP PUBLICATION pub_schema; +DROP PUBLICATION pub_schema_except; DROP PUBLICATION pub_normal; DROP PUBLICATION pub_part_leaf; DROP PUBLICATION pub_part_parent; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 43b51c8ff71..6208e98e7eb 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -24,14 +24,17 @@ my $result; sub test_except_root_partition { - my ($pubviaroot) = @_; + my ($pubviaroot, $pubsql) = @_; + $pubsql //= + "CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1)"; + $pubsql .= " WITH (publish_via_partition_root = $pubviaroot)"; # If the root partitioned table is in the EXCEPT clause, all its # partitions are excluded from publication, regardless of the # publish_via_partition_root setting. $node_publisher->safe_psql( 'postgres', qq( - CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1) WITH (publish_via_partition_root = $pubviaroot); + $pubsql; INSERT INTO root1 VALUES (1), (101); )); $node_subscriber->safe_psql('postgres', @@ -223,6 +226,206 @@ $node_subscriber->safe_psql( test_except_root_partition('false'); test_except_root_partition('true'); +# Same validation using TABLES IN SCHEMA instead of FOR ALL TABLES. +my $schema_pub = + "CREATE PUBLICATION tap_pub_part FOR TABLES IN SCHEMA public EXCEPT (TABLE public.root1)"; +test_except_root_partition('false', $schema_pub); +test_except_root_partition('true', $schema_pub); + +# ============================================ +# EXCEPT test cases for TABLES IN SCHEMA +# ============================================ + +# Create a dedicated schema with two tables: one to be published and one to be +# excluded. Also create inherited tables to verify ONLY semantics. +$node_publisher->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_published AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.tab_excluded AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.parent (a int); + CREATE TABLE sch1.child (b int) INHERITS (sch1.parent); +)); + +$node_subscriber->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_published (a int); + CREATE TABLE sch1.tab_excluded (a int); + CREATE TABLE sch1.parent (a int); + CREATE TABLE sch1.child (b int) INHERITS (sch1.parent); +)); + +# Basic test: initial sync respects EXCEPT. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_excluded)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: initial sync copies included table'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: initial sync skips excluded table'); + +# DML: only the included table should be replicated. +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (6); + INSERT INTO sch1.tab_excluded VALUES (6); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(6), + 'TABLES IN SCHEMA EXCEPT: DML on included table is replicated'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: DML on excluded table is not replicated'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Inherited tables: excluding the parent (without ONLY) also excludes the child. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.parent)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.child VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.child"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: excluding parent (without ONLY) also excludes child' +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Test that EXCEPT (TABLE ONLY parent) excludes only the parent itself, not its +# child. Truncate child first so rows from the previous test are not copied by +# the initial table sync of the next subscription. +$node_publisher->safe_psql('postgres', 'TRUNCATE sch1.child'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE sch1.child'); +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE ONLY sch1.parent)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.child VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.child"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: ONLY parent in EXCEPT does not exclude child'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Cleanup schema tables before the multi-publication section. +$node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); +$node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); + +# ============================================ +# EXCEPT test cases for TABLES IN SCHEMA with a cross-schema partition +# ============================================ + +# A partition can live in a different schema than its partitioned root. If +# the root is excluded via EXCEPT under its own schema's clause, the +# exclusion must cascade to all its partitions, even when the partition's +# own schema is separately, fully included (no EXCEPT) in the same +# publication. +$node_publisher->safe_psql( + 'postgres', qq( + CREATE SCHEMA csch1; + CREATE SCHEMA csch2; + CREATE TABLE csch1.croot(a int) PARTITION BY RANGE(a); + CREATE TABLE csch2.cpart1 PARTITION OF csch1.croot FOR VALUES FROM (0) TO (100); + INSERT INTO csch1.croot VALUES (generate_series(1,5)); +)); + +$node_subscriber->safe_psql( + 'postgres', qq( + CREATE SCHEMA csch1; + CREATE SCHEMA csch2; + CREATE TABLE csch1.croot(a int); + CREATE TABLE csch2.cpart1(a int); +)); + +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION cross_sch_pub FOR TABLES IN SCHEMA csch1 EXCEPT (TABLE csch1.croot), TABLES IN SCHEMA csch2 WITH (publish_via_partition_root = false)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION cross_sch_sub CONNECTION '$publisher_connstr' PUBLICATION cross_sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'cross_sch_sub'); + +# Baseline: the root itself, pre-populated with rows before the subscription +# was created, is excluded by its own schema's EXCEPT clause -- initial sync +# must not have copied it. +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM csch1.croot"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: cross-schema partition root is excluded by initial sync' +); + +# Regression case: the partition's own schema (csch2) is separately, fully +# included with no EXCEPT, but the root's exclusion must still cascade to it +# -- initial sync must not have copied the pre-existing rows routed into this +# partition via the root. +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM csch2.cpart1"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: cross-schema partition is excluded by initial sync via cascading root exclusion' +); + +# Insert distinct, identifiable data directly into the partition and verify +# it is not replicated either. +$node_publisher->safe_psql('postgres', + "INSERT INTO csch2.cpart1 VALUES (generate_series(1,5))"); +$node_publisher->wait_for_catchup('cross_sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM csch1.croot"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: cross-schema partition root remains excluded after DML' +); +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM csch2.cpart1"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: cross-schema partition remains excluded after DML via cascading root exclusion' +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION cross_sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION cross_sch_pub'); +$node_publisher->safe_psql('postgres', 'DROP SCHEMA csch1, csch2 CASCADE'); +$node_subscriber->safe_psql('postgres', 'DROP SCHEMA csch1, csch2 CASCADE'); + # ============================================ # Test when a subscription is subscribing to multiple publications # ============================================ @@ -254,6 +457,7 @@ $node_publisher->safe_psql( DROP PUBLICATION tap_pub2; TRUNCATE tab1; )); +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_subscriber->safe_psql('postgres', qq(TRUNCATE tab1)); # OK when a table is excluded by pub1 EXCEPT clause, but it is included by pub2 -- 2.50.1 (Apple Git-155)
v24-0002-Add-EXCEPT-support-to-ALTER-PUBLICATION-ADD-TABL.patch (application/octet-stream, 22.3K) download From 89585dd17eb4c6382ffe5acdd8fbc55341ef71b1 Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Thu, 23 Jul 2026 12:31:51 +0530 Subject: [PATCH v24 2/4] Add EXCEPT support to ALTER PUBLICATION ADD TABLES IN SCHEMA Extend the EXCEPT clause support to allow tables to be excluded when adding a schema to a publication via ALTER PUBLICATION ... ADD. Syntax: ALTER PUBLICATION pub ADD TABLES IN SCHEMA s EXCEPT (TABLE s.t1); Since pg_dump uses ALTER PUBLICATION ... ADD, support for it is included in this patch. --- src/backend/catalog/pg_publication.c | 19 ++-- src/backend/commands/publicationcmds.c | 102 ++++++++++++++++++++-- src/bin/pg_dump/pg_dump.c | 30 ++++++- src/bin/pg_dump/t/002_pg_dump.pl | 24 +++++ src/bin/psql/tab-complete.in.c | 17 ++++ src/test/regress/expected/publication.out | 60 ++++++++++++- src/test/regress/sql/publication.sql | 45 +++++++++- src/test/subscription/t/037_except.pl | 32 +++++++ 8 files changed, 313 insertions(+), 16 deletions(-) diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index b1c5b48c294..ac8d1e62a92 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -729,15 +729,18 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, * here, as CreatePublication() function invalidates all relations as part * of defining a FOR ALL TABLES publication. * - * For ALTER PUBLICATION, invalidation is needed only when adding an - * EXCEPT table to a publication already marked as ALL TABLES. For - * publications that were originally empty or defined as ALL SEQUENCES and - * are being converted to ALL TABLES, invalidation is skipped here, as - * AlterPublicationAllFlags() function invalidates all relations while - * marking the publication as ALL TABLES publication. + * For ALTER PUBLICATION, invalidation is needed when adding an EXCEPT + * table to either a FOR ALL TABLES publication (pub->alltables is true) + * or a FOR TABLES IN SCHEMA publication (is_schema_publication is true). + * The exception: when a publication is being converted to FOR ALL TABLES + * (pub->alltables is still false at this point), + * AlterPublicationAllFlags() will perform a full invalidation, so we skip + * it here. */ - inval_except_table = (alter_stmt != NULL) && pub->alltables && - (alter_stmt->for_all_tables && pri->except); + inval_except_table = (alter_stmt != NULL) && pri->except && + (pub->alltables + ? alter_stmt->for_all_tables + : is_schema_publication(pubid)); if (!pri->except || inval_except_table) { diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 44a5599549d..9f10552dec9 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -71,6 +71,13 @@ static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok); static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); +static void AlterPublicationSchemas(AlterPublicationStmt *stmt, + HeapTuple tup, List *schemaidlist, + List *except_pubtables); +static void AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, + List *except_pubtables, + List *schemaidlist); static char defGetGeneratedColsOption(DefElem *def); static void CheckExceptNotInTableList(List *except_rels, List *explicitrelids); static void ProcessSchemaExceptTables(Oid schemaid, List *except_tables, @@ -1590,7 +1597,8 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, */ static void AlterPublicationSchemas(AlterPublicationStmt *stmt, - HeapTuple tup, List *schemaidlist) + HeapTuple tup, List *schemaidlist, + List *except_pubtables) { Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); @@ -1667,6 +1675,88 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, */ PublicationAddSchemas(pubform->oid, schemaidlist, true, stmt); } + + /* + * Increment the command counter so that is_schema_publication() in + * GetExcludedPublicationTables() can see the just-inserted schema + * rows when AlterPublicationSchemaExceptTables runs next. + */ + if (stmt->action == AP_AddObjects || stmt->action == AP_SetObjects) + CommandCounterIncrement(); + + AlterPublicationSchemaExceptTables(stmt, tup, except_pubtables, schemaidlist); +} + +/* + * Alter the EXCEPT list of a schema-level publication. + * + * Adds, removes, or replaces except-table entries in pg_publication_rel + * (rows with prexcept = true). These entries suppress publication of the + * named tables that would otherwise be covered by a FOR TABLES IN SCHEMA + * clause. + */ +static void +AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, List *except_pubtables, + List *schemaidlist) +{ + Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); + Oid pubid = pubform->oid; + + /* + * Nothing to do if no EXCEPT entries. + */ + if (!except_pubtables) + return; + + /* + * This function handles EXCEPT entries for schema-level publications + * only. For FOR ALL TABLES publications, EXCEPT entries are already + * processed by AlterPublicationTables(). + */ + if (schemaidlist == NIL && !is_schema_publication(pubid)) + return; + + /* + * Dropping a schema from a publication removes all its EXCEPT entries via + * cascade. The concept of "drop all schema tables from the publication + * EXCEPT these ones" is not supported. + */ + if (stmt->action == AP_DropObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); + + /* + * XXX EXCEPT with SET is not currently implemented. Workaround: DROP and + * re-ADD the schema with the desired EXCEPT list. + */ + if (stmt->action == AP_SetObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"), + errhint("Drop and re-add the schema with the desired EXCEPT list."))); + + if (stmt->action == AP_AddObjects) + { + List *rels; + List *explicitrelids; + + rels = OpenTableList(except_pubtables); + + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + /* + * Validate that each excluded table is not also in the explicit table + * list (which would be contradictory). + */ + CheckExceptNotInTableList(rels, explicitrelids); + + PublicationAddTables(pubid, rels, false, stmt); + + CloseTableList(rels); + } } /* @@ -1848,12 +1938,12 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) else { List *relations = NIL; - List *exceptrelations = NIL; + List *except_pubtables = NIL; List *schemaidlist = NIL; Oid pubid = pubform->oid; ObjectsInPublicationToOids(stmt->pubobjects, pstate, &relations, - &exceptrelations, &schemaidlist); + &except_pubtables, &schemaidlist); CheckAlterPublication(stmt, tup, relations, schemaidlist); @@ -1876,10 +1966,12 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) errmsg("publication \"%s\" does not exist", stmt->pubname)); - relations = list_concat(relations, exceptrelations); + if (stmt->for_all_tables) + relations = list_concat(relations, except_pubtables); + AlterPublicationTables(stmt, tup, relations, pstate->p_sourcetext, schemaidlist != NIL); - AlterPublicationSchemas(stmt, tup, schemaidlist); + AlterPublicationSchemas(stmt, tup, schemaidlist, except_pubtables); AlterPublicationAllFlags(stmt, rel, tup); } diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c index 4948e6d80c7..ecd518af02c 100644 --- a/src/bin/pg_dump/pg_dump.c +++ b/src/bin/pg_dump/pg_dump.c @@ -4973,6 +4973,7 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) PublicationInfo *pubinfo = pubsinfo->publication; PQExpBuffer query; char *tag; + bool has_except = false; /* Do nothing if not dumping schema */ if (!dopt->dumpSchema) @@ -4983,7 +4984,34 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) query = createPQExpBuffer(); appendPQExpBuffer(query, "ALTER PUBLICATION %s ", fmtId(pubinfo->dobj.name)); - appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s;\n", fmtId(schemainfo->dobj.name)); + appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s", fmtId(schemainfo->dobj.name)); + + /* + * Append EXCEPT clause for any tables that belong to this schema + * and are excluded from the publication. + */ + for (SimplePtrListCell *cell = pubinfo->except_tables.head; cell; cell = cell->next) + { + TableInfo *tbinfo = (TableInfo *) cell->ptr; + + if (strcmp(tbinfo->dobj.namespace->dobj.name, schemainfo->dobj.name) == 0) + { + if (!has_except) + { + appendPQExpBufferStr(query, " EXCEPT ("); + has_except = true; + } + else + appendPQExpBufferStr(query, ", "); + + appendPQExpBuffer(query, "TABLE ONLY %s", fmtId(tbinfo->dobj.name)); + } + } + + if (has_except) + appendPQExpBufferStr(query, ")"); + + appendPQExpBufferStr(query, ";\n"); /* * There is no point in creating drop query as the drop is done by schema diff --git a/src/bin/pg_dump/t/002_pg_dump.pl b/src/bin/pg_dump/t/002_pg_dump.pl index 9258948b583..d18b3b0d7b9 100644 --- a/src/bin/pg_dump/t/002_pg_dump.pl +++ b/src/bin/pg_dump/t/002_pg_dump.pl @@ -3283,6 +3283,30 @@ my %tests = ( like => { %full_runs, section_post_data => 1, }, }, + 'CREATE PUBLICATION pub11' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub11 FOR TABLES IN SCHEMA dump_test EXCEPT (TABLE test_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub11 WITH (publish = 'insert, update, delete, truncate');\E + .*? + \QALTER PUBLICATION pub11 ADD TABLES IN SCHEMA dump_test EXCEPT (TABLE ONLY test_table);\E + /xms, + like => { %full_runs, section_post_data => 1, }, + }, + + 'CREATE PUBLICATION pub12' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub12 FOR TABLES IN SCHEMA dump_test EXCEPT (TABLE test_table, dump_test.test_second_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub12 WITH (publish = 'insert, update, delete, truncate');\E + .*? + \QALTER PUBLICATION pub12 ADD TABLES IN SCHEMA dump_test EXCEPT (TABLE ONLY test_table, TABLE ONLY test_second_table);\E + /xms, + like => { %full_runs, section_post_data => 1, }, + }, + 'CREATE SUBSCRIPTION sub1' => { create_order => 50, create_sql => 'CREATE SUBSCRIPTION sub1 diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index 04f2b63535f..b31d5431d79 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2359,6 +2359,23 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); + /* After a single schema name in ADD context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index f8f4b187c0a..d8c833acdaa 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -650,12 +650,70 @@ CREATE PUBLICATION testpub_except_ancestor_cross_schema ERROR: partition "public.testpub_part_s2" cannot be both published and excluded DETAIL: Partition root "pub_test.testpub_parted_s" is named in the publication's EXCEPT clause for schema "pub_test". DROP TABLE public.testpub_part_s2; +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; +-- fail: non-existing table in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- fail: EXCEPT table belongs to a different schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 1: ...xcept ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.tes... + ^ +-- fail: TABLE keyword is required for the first entry in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +ERROR: syntax error at or near "testpub_nopk" +LINE 1: ...lter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_no... + ^ +-- fail: exact same table given as both explicitly published and excluded +-- in a single ALTER ... ADD +ALTER PUBLICATION testpub_alter_except + ADD TABLE pub_test.testpub_tbl_s1, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot be both published and excluded +-- fail: add explicit partition and EXCEPT ancestor, given in a +-- single ALTER ... ADD statement +ALTER PUBLICATION testpub_alter_except + ADD TABLE pub_test.testpub_part_s, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ERROR: partition "pub_test.testpub_part_s" cannot be both published and excluded +DETAIL: Partition root "pub_test.testpub_parted_s" is named in the publication's EXCEPT clause for schema "pub_test". +-- fail: partition already explicitly published, then its root is EXCEPT-ed +-- via a later, separate ALTER ... ADD +ALTER PUBLICATION testpub_alter_except ADD TABLE pub_test.testpub_part_s; +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ERROR: partition "pub_test.testpub_part_s" cannot be both published and excluded +DETAIL: Partition root "pub_test.testpub_parted_s" is named in the publication's EXCEPT clause for schema "pub_test". +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_part_s; +-- fail: root already explicitly published, then its partition is rejected +-- from EXCEPT via a later, separate ALTER ... ADD (partitions can never +-- appear in EXCEPT, independent of the root's state) +ALTER PUBLICATION testpub_alter_except ADD TABLE pub_test.testpub_parted_s; +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); +ERROR: cannot specify relation "pub_test.testpub_part_s" in the publication EXCEPT clause +DETAIL: This operation is not supported for individual partitions. +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_parted_s; +-- ADD: qualified and unqualified names; unqualified is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + "pub_test.testpub_tbl_s2" + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP TABLE pub_test.testpub_parted_s CASCADE; DROP TABLE testpub_nopk, testpub_tbl_s1; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi, testpub_alter_except; --------------------------------------------- -- Tests for publications with SEQUENCES --------------------------------------------- diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index dcdc1eb5df9..42b7c78f7fd 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -328,12 +328,55 @@ CREATE PUBLICATION testpub_except_ancestor_cross_schema TABLE public.testpub_part_s2; DROP TABLE public.testpub_part_s2; +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; + +-- fail: non-existing table in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- fail: EXCEPT table belongs to a different schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- fail: TABLE keyword is required for the first entry in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + +-- fail: exact same table given as both explicitly published and excluded +-- in a single ALTER ... ADD +ALTER PUBLICATION testpub_alter_except + ADD TABLE pub_test.testpub_tbl_s1, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: add explicit partition and EXCEPT ancestor, given in a +-- single ALTER ... ADD statement +ALTER PUBLICATION testpub_alter_except + ADD TABLE pub_test.testpub_part_s, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); + +-- fail: partition already explicitly published, then its root is EXCEPT-ed +-- via a later, separate ALTER ... ADD +ALTER PUBLICATION testpub_alter_except ADD TABLE pub_test.testpub_part_s; +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_part_s; + +-- fail: root already explicitly published, then its partition is rejected +-- from EXCEPT via a later, separate ALTER ... ADD (partitions can never +-- appear in EXCEPT, independent of the root's state) +ALTER PUBLICATION testpub_alter_except ADD TABLE pub_test.testpub_parted_s; +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_parted_s; + +-- ADD: qualified and unqualified names; unqualified is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); +\dRp+ testpub_alter_except + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP TABLE pub_test.testpub_parted_s CASCADE; DROP TABLE testpub_nopk, testpub_tbl_s1; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi, testpub_alter_except; --------------------------------------------- -- Tests for publications with SEQUENCES diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 6208e98e7eb..5af08cc067d 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -347,6 +347,38 @@ is($result, qq(5), $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); +# ============================================ +# ALTER PUBLICATION EXCEPT for TABLES IN SCHEMA +# ============================================ + +# Truncate subscriber tables to remove data accumulated from previous tests. +$node_subscriber->safe_psql('postgres', + 'TRUNCATE sch1.tab_published, sch1.tab_excluded, sch1.parent, sch1.child'); + +# ADD: add a schema with an excepted table; verify the except entry takes effect. +$node_publisher->safe_psql('postgres', "CREATE PUBLICATION sch_pub"); +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub ADD TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_excluded)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(6), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: included table synced'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + # Cleanup schema tables before the multi-publication section. $node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); $node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); -- 2.50.1 (Apple Git-155)
v24-0003-Add-EXCEPT-support-to-ALTER-PUBLICATION-SET-TABL.patch (application/octet-stream, 27.4K) download From 3cf8133f7efbce58ed788ec0cdb8242351b4f3b2 Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Thu, 18 Jun 2026 11:32:32 +0530 Subject: [PATCH v24 3/4] Add EXCEPT support to ALTER PUBLICATION SET TABLES IN SCHEMA Extend AlterPublicationExceptTables() with the AP_SetObjects case, which redefines the publication and replaces the entire EXCEPT list. Syntax: ALTER PUBLICATION pub SET TABLES IN SCHEMA s EXCEPT (TABLE t1); This patch also cleans up EXCEPT entries when a schema is dropped from the publication. --- src/backend/commands/publicationcmds.c | 178 +++++++++++++++++++--- src/bin/psql/tab-complete.in.c | 17 +++ src/test/regress/expected/publication.out | 109 +++++++++++++ src/test/regress/sql/publication.sql | 47 ++++++ src/test/subscription/t/037_except.pl | 85 +++++++++++ 5 files changed, 411 insertions(+), 25 deletions(-) diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 9f10552dec9..298273cdc7c 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -67,7 +67,8 @@ static void CloseTableList(List *rels); static void LockSchemaList(List *schemalist); static void PublicationAddTables(Oid pubid, List *rels, bool if_not_exists, AlterPublicationStmt *stmt); -static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok); +static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok, + bool delete_excluded); static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); @@ -1441,7 +1442,7 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, PublicationAddTables(pubid, rels, false, stmt); } else if (stmt->action == AP_DropObjects) - PublicationDropTables(pubid, rels, false); + PublicationDropTables(pubid, rels, false, false); else /* AP_SetObjects */ { List *oldrelids = NIL; @@ -1576,7 +1577,7 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, } /* And drop them. */ - PublicationDropTables(pubid, delrels, true); + PublicationDropTables(pubid, delrels, true, true); /* * Don't bother calculating the difference for adding, we'll catch and @@ -1678,8 +1679,8 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, /* * Increment the command counter so that is_schema_publication() in - * GetExcludedPublicationTables() can see the just-inserted schema - * rows when AlterPublicationSchemaExceptTables runs next. + * GetExcludedPublicationTables() can see the just-inserted schema rows + * when AlterPublicationSchemaExceptTables runs next. */ if (stmt->action == AP_AddObjects || stmt->action == AP_SetObjects) CommandCounterIncrement(); @@ -1697,16 +1698,18 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, */ static void AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, - HeapTuple tup, List *except_pubtables, - List *schemaidlist) + HeapTuple tup, List *except_pubtables, + List *schemaidlist) { Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); Oid pubid = pubform->oid; /* - * Nothing to do if no EXCEPT entries. + * Nothing to do if there are no EXCEPT entries, unless handling the SET + * command, because if the user has removed all exceptions we need to drop + * any existing ones. */ - if (!except_pubtables) + if (!except_pubtables && stmt->action != AP_SetObjects) return; /* @@ -1727,16 +1730,6 @@ AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); - /* - * XXX EXCEPT with SET is not currently implemented. Workaround: DROP and - * re-ADD the schema with the desired EXCEPT list. - */ - if (stmt->action == AP_SetObjects) - ereport(ERROR, - (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"), - errhint("Drop and re-add the schema with the desired EXCEPT list."))); - if (stmt->action == AP_AddObjects) { List *rels; @@ -1755,6 +1748,72 @@ AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, PublicationAddTables(pubid, rels, false, stmt); + CloseTableList(rels); + } + else /* AP_SetObjects */ + { + List *oldexceptrelids = NIL; + List *newexceptrelids = NIL; + List *delrelids = NIL; + List *rels; + List *explicitrelids; + + rels = OpenTableList(except_pubtables); + + /* Collect OIDs of the desired new EXCEPT list. */ + foreach_ptr(PublicationRelInfo, pri, rels) + newexceptrelids = lappend_oid(newexceptrelids, + RelationGetRelid(pri->relation)); + + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + /* Check that there is no clash between included and excluded tables. */ + CheckExceptNotInTableList(rels, explicitrelids); + + /* + * Get the current set of EXCEPT entries. Only FOR ALL TABLES and + * schema-level publications can have EXCEPT entries; for any other + * publication type oldexceptrelids stays NIL. + * + * Note: we check is_schema_publication() against the current catalog + * state (before AlterPublicationSchemas has run), so if the caller is + * doing SET TABLE t1 to convert a schema publication into a plain + * table publication, is_schema_publication() still returns true here. + * That is intentional: it lets us discover and clean up any stale + * EXCEPT entries that belong to the old schema definition. + */ + if (GetPublication(pubid)->alltables || is_schema_publication(pubid)) + oldexceptrelids = GetExcludedPublicationTables(pubid, + PUBLICATION_PART_ROOT); + + /* Build a list of old EXCEPT entries not present in the new list. */ + foreach_oid(oldrelid, oldexceptrelids) + { + if (!list_member_oid(newexceptrelids, oldrelid)) + delrelids = lappend_oid(delrelids, oldrelid); + } + + /* Drop old EXCEPT entries not present in the new list. */ + foreach_oid(relid, delrelids) + { + Oid proid; + ObjectAddress obj; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + /* Add new EXCEPT entries, skipping any already present. */ + PublicationAddTables(pubid, rels, true, stmt); + CloseTableList(rels); } } @@ -2378,33 +2437,69 @@ PublicationAddTables(Oid pubid, List *rels, bool if_not_exists, /* * Remove listed tables from the publication. + * + * delete_excluded controls how EXCEPT (prexcept=true) rows are handled: + * true - delete them silently. Used by the SET path to clear stale + * EXCEPT rows when ALTER PUBLICATION ... SET replaces or removes + * the EXCEPT clause. + * false - treat them as "not a member". Used by ALTER ... DROP TABLE: an + * EXCEPT entry is not something DROP TABLE is expected to remove. */ static void -PublicationDropTables(Oid pubid, List *rels, bool missing_ok) +PublicationDropTables(Oid pubid, List *rels, bool missing_ok, + bool delete_excluded) { ObjectAddress obj; ListCell *lc; - Oid prid; foreach(lc, rels) { PublicationRelInfo *pubrel = (PublicationRelInfo *) lfirst(lc); Relation rel = pubrel->relation; Oid relid = RelationGetRelid(rel); + HeapTuple tup; + Form_pg_publication_rel pubrelform; + Oid prid = InvalidOid; + bool is_except = false; if (pubrel->columns) ereport(ERROR, errcode(ERRCODE_SYNTAX_ERROR), errmsg("column list must not be specified in ALTER PUBLICATION ... DROP")); - prid = GetSysCacheOid2(PUBLICATIONRELMAP, Anum_pg_publication_rel_oid, - ObjectIdGetDatum(relid), - ObjectIdGetDatum(pubid)); - if (!OidIsValid(prid)) + tup = SearchSysCache2(PUBLICATIONRELMAP, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (HeapTupleIsValid(tup)) + { + pubrelform = (Form_pg_publication_rel) GETSTRUCT(tup); + is_except = pubrelform->prexcept; + prid = pubrelform->oid; + ReleaseSysCache(tup); + } + + /* + * DROP TABLE operates only on regular member rows. A missing row and + * an EXCEPT row both mean the table isn't currently published, but we + * distinguish them so the EXCEPT case can carry a hint pointing the + * user at the EXCEPT clause. The SET-cleanup caller (delete_excluded + * = true) intends to remove EXCEPT rows and so bypasses the EXCEPT + * half of this check. + */ + if (!OidIsValid(prid) || (is_except && !delete_excluded)) { if (missing_ok) continue; + if (is_except) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("cannot drop table \"%s\" from publication \"%s\"", + RelationGetQualifiedRelationName(rel), + get_publication_name(pubid, false)), + errdetail("The table is currently named in an EXCEPT clause of the publication."), + errhint("Change the EXCEPT clause using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT."))); + ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("relation \"%s\" is not part of the publication", @@ -2460,6 +2555,7 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) foreach(lc, schemas) { Oid schemaid = lfirst_oid(lc); + List *except_relids; psid = GetSysCacheOid2(PUBLICATIONNAMESPACEMAP, Anum_pg_publication_namespace_oid, @@ -2476,8 +2572,40 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) get_namespace_name(schemaid)))); } + /* + * Collect EXCEPT entries for tables belonging to this schema before + * removing the schema entry. + */ + except_relids = GetExcludedPublicationTables(pubid, PUBLICATION_PART_ROOT); + ObjectAddressSet(obj, PublicationNamespaceRelationId, psid); performDeletion(&obj, DROP_CASCADE, 0); + + /* + * Drop any prexcept rows for tables belonging to this schema. These + * rows have no pg_depend entry pointing at the + * pg_publication_namespace row, so they are not cascaded by the + * performDeletion() call above and must be cleaned up explicitly. + */ + foreach_oid(relid, except_relids) + { + Oid proid; + + if (get_rel_namespace(relid) != schemaid) + continue; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + list_free(except_relids); } } diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index b31d5431d79..77528194a27 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2376,6 +2376,23 @@ match_previous_words(int pattern_id, } else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) COMPLETE_WITH(")"); + /* After a single schema name in SET context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index d8c833acdaa..71bda2aa966 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -708,6 +708,115 @@ Except tables: "pub_test.testpub_tbl_s1" "pub_test.testpub_tbl_s2" +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s2" + +-- fail: table in EXCEPT clause also appears in the explicit table list +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot be both published and excluded +-- fail: explicit partition + EXCEPT-ed root, given in a single SET statement +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_part_s, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ERROR: partition "pub_test.testpub_part_s" cannot be both published and excluded +DETAIL: Partition root "pub_test.testpub_parted_s" is named in the publication's EXCEPT clause for schema "pub_test". +-- fail: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 1: ...xcept SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.tes... + ^ +-- SET: unqualified name in EXCEPT is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- SET without EXCEPT clears the existing except list +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + +-- SET to a different schema removes old schema's EXCEPT entries +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA public; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "public" + +-- fail: nonexistent table in EXCEPT clause (SET path) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- SET: multiple schemas each with their own EXCEPT clause +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- fail: ALTER PUBLICATION ... DROP TABLE on an excluded table is rejected +-- with an EXCEPT-specific error. +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_tbl_s1; +ERROR: cannot drop table "pub_test.testpub_tbl_s1" from publication "testpub_alter_except" +DETAIL: The table is currently named in an EXCEPT clause of the publication. +HINT: Change the EXCEPT clause using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT. +-- the EXCEPT entry is still present after the rejected DROP TABLE +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- fail: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +ERROR: EXCEPT clause is not supported with DROP in ALTER PUBLICATION +-- DROP TABLES IN SCHEMA removes associated EXCEPT entries +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "public" +Except tables: + "public.testpub_tbl1" + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 42b7c78f7fd..73598e1fb2b 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -371,6 +371,53 @@ ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_parted_s; ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); \dRp+ testpub_alter_except +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + +-- fail: table in EXCEPT clause also appears in the explicit table list +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: explicit partition + EXCEPT-ed root, given in a single SET statement +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_part_s, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); + +-- fail: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- SET: unqualified name in EXCEPT is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +\dRp+ testpub_alter_except + +-- SET without EXCEPT clears the existing except list +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + +-- SET to a different schema removes old schema's EXCEPT entries +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA public; +\dRp+ testpub_alter_except + +-- fail: nonexistent table in EXCEPT clause (SET path) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- SET: multiple schemas each with their own EXCEPT clause +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_alter_except + +-- fail: ALTER PUBLICATION ... DROP TABLE on an excluded table is rejected +-- with an EXCEPT-specific error. +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_tbl_s1; +-- the EXCEPT entry is still present after the rejected DROP TABLE +\dRp+ testpub_alter_except + +-- fail: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); + +-- DROP TABLES IN SCHEMA removes associated EXCEPT entries +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 5af08cc067d..d538bc53732 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -376,6 +376,61 @@ $result = is($result, qq(0), 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); +# SET: replace the except list; tab_excluded is now included and tab_published is excluded. +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_published)" +); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (7); + INSERT INTO sch1.tab_excluded VALUES (7); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded WHERE a = 7"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: newly included table is replicated' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published WHERE a = 7"); +is($result, qq(0), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: now-excluded table is not replicated' +); + +# SET without EXCEPT: clears the except list; both tables are now published. +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1"); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (8); + INSERT INTO sch1.tab_excluded VALUES (8); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published WHERE a = 8"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_published replicated after except list cleared' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded WHERE a = 8"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_excluded replicated after except list cleared' +); + $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); @@ -518,6 +573,36 @@ $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); +# OK when a table is excluded by a TABLES IN SCHEMA EXCEPT publication, +# but is included by another publication. +$node_publisher->safe_psql('postgres', 'TRUNCATE tab1'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE tab1'); + +$node_publisher->safe_psql( + 'postgres', qq( + CREATE PUBLICATION tap_pub1 FOR TABLES IN SCHEMA public EXCEPT (TABLE public.tab1); + CREATE PUBLICATION tap_pub2 FOR TABLE tab1; + INSERT INTO tab1 VALUES(1); +)); +$node_subscriber->psql('postgres', + "CREATE SUBSCRIPTION tap_sub CONNECTION '$publisher_connstr' PUBLICATION tap_pub1, tap_pub2" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'tap_sub'); + +$node_publisher->safe_psql('postgres', qq(INSERT INTO tab1 VALUES(2))); +$node_publisher->wait_for_catchup('tap_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT * FROM tab1 ORDER BY a"); +is( $result, qq(1 +2), + "TABLES IN SCHEMA EXCEPT: table excluded in schema pub but included by another pub is replicated" +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); + $node_publisher->stop('fast'); done_testing(); -- 2.50.1 (Apple Git-155)
v24-0004-Documentation-Patch.patch (application/octet-stream, 11.6K) download From bfaa2f6fd9b43fc56049f5d86264a9c047e22b2c Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Thu, 30 Jul 2026 10:15:42 +0530 Subject: [PATCH v24 4/4] Documentation Patch --- doc/src/sgml/logical-replication.sgml | 3 +- doc/src/sgml/ref/alter_publication.sgml | 57 +++++++++++++++++++++++- doc/src/sgml/ref/create_publication.sgml | 42 +++++++++++++---- 3 files changed, 90 insertions(+), 12 deletions(-) diff --git a/doc/src/sgml/logical-replication.sgml b/doc/src/sgml/logical-replication.sgml index 36298cacb75..03f12986b12 100644 --- a/doc/src/sgml/logical-replication.sgml +++ b/doc/src/sgml/logical-replication.sgml @@ -117,7 +117,8 @@ or <literal>FOR ALL SEQUENCES</literal>. Unlike tables, sequences can be synchronized at any time. For more information, see <xref linkend="logical-replication-sequences"/>. When a publication is - created with <literal>FOR ALL TABLES</literal>, a table or set of tables can + created with <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal>, a table or set of tables can be explicitly excluded from publication using the <link linkend="sql-createpublication-params-for-except-table"><literal>EXCEPT</literal></link> clause. diff --git a/doc/src/sgml/ref/alter_publication.sgml b/doc/src/sgml/ref/alter_publication.sgml index d2898d2633e..eb0f3170b53 100644 --- a/doc/src/sgml/ref/alter_publication.sgml +++ b/doc/src/sgml/ref/alter_publication.sgml @@ -31,7 +31,7 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA <replaceable class="parameter">tables_in_schema</replaceable> [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -47,6 +47,10 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <replaceable class="parameter">table_object</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] [ WHERE ( <replaceable class="parameter">expression</replaceable> ) ] +<phrase>and <replaceable class="parameter">tables_in_schema</replaceable> is:</phrase> + + { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] + <phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> TABLE <replaceable class="parameter">table_object</replaceable> [, ... ] @@ -69,6 +73,9 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r The first two variants modify which tables/schemas are part of the publication. The <literal>ADD</literal> and <literal>DROP</literal> clauses will add and remove one or more tables/schemas from the publication. + The <literal>EXCEPT</literal> clause can be used with + <literal>ADD TABLES IN SCHEMA</literal> to exclude specific tables from a + schema-level publication. </para> <para> @@ -93,7 +100,11 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r used with a publication defined with <literal>FOR TABLE</literal> or <literal>FOR TABLES IN SCHEMA</literal>, replaces the list of tables/schemas in the publication with the specified list; the existing tables or schemas - that were present in the publication will be removed. + that were present in the publication will be removed. When + <literal>SET TABLES IN SCHEMA</literal> is used with an + <literal>EXCEPT</literal> clause, the excluded tables for each schema are + replaced with the specified list; if <literal>EXCEPT</literal> is omitted + for a schema, any existing exclusions for that schema are cleared. </para> <para> @@ -210,6 +221,26 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r </listitem> </varlistentry> + <varlistentry> + <term><literal>EXCEPT</literal></term> + <listitem> + <para> + When used with <literal>ADD TABLES IN SCHEMA</literal> + or <literal>SET TABLES IN SCHEMA</literal>, specifies tables to be + excluded from the publication. Each named table must belong to the + schema specified in the same <literal>TABLES IN SCHEMA</literal> clause. + Table names may be schema-qualified or unqualified; unqualified names + are implicitly qualified with the schema named in the same clause. See + <xref linkend="sql-createpublication"/> for further details on the + semantics of <literal>EXCEPT</literal>. + </para> + <para> + Dropping a table always removes it from the <literal>EXCEPT</literal> + clause. + </para> + </listitem> + </varlistentry> + <varlistentry id="sql-alterpublication-params-set"> <term><literal>SET ( <replaceable class="parameter">publication_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] )</literal></term> <listitem> @@ -300,6 +331,28 @@ ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA marketing, sales; </programlisting> </para> + <para> + Add schema <structname>sales</structname> to the publication + <structname>sales_publication</structname>, excluding the + <structname>sales.internal</structname> and + <structname>sales.drafts</structname> tables: +<programlisting> +ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA sales EXCEPT (TABLE internal, drafts); +</programlisting> + </para> + + <para> + Replace the schema list of <structname>sales_publication</structname> with + <structname>sales</structname>, excluding only + <structname>sales.drafts</structname>. Other than + <structname>sales.drafts</structname>, any previously excluded tables for schema + <structname>sales</structname> are no longer excluded. Any schemas previously in + <structname>sales_publication</structname> are removed: +<programlisting> +ALTER PUBLICATION sales_publication SET TABLES IN SCHEMA sales EXCEPT (TABLE drafts); +</programlisting> + </para> + <para> Add tables <structname>users</structname>, <structname>departments</structname> and schema diff --git a/doc/src/sgml/ref/create_publication.sgml b/doc/src/sgml/ref/create_publication.sgml index 35c28006f60..59a8fd8a71d 100644 --- a/doc/src/sgml/ref/create_publication.sgml +++ b/doc/src/sgml/ref/create_publication.sgml @@ -28,7 +28,7 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA <replaceable class="parameter">tables_in_schema</replaceable> [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -39,6 +39,10 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <replaceable class="parameter">table_object</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] [ WHERE ( <replaceable class="parameter">expression</replaceable> ) ] +<phrase>and <replaceable class="parameter">tables_in_schema</replaceable> is:</phrase> + + { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] + <phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> TABLE <replaceable class="parameter">table_object</replaceable> [, ... ] @@ -172,6 +176,8 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <para> Marks the publication as one that replicates changes for all tables in the specified list of schemas, including tables created in the future. + Tables listed in the <literal>EXCEPT</literal> clause for a given schema + are excluded from the publication. </para> <para> @@ -203,7 +209,7 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <para> Marks the publication as one that replicates changes for all tables in the database, including tables created in the future. Tables listed in - <literal>EXCEPT</literal> clause are excluded from the publication. + the <literal>EXCEPT</literal> clause are excluded from the publication. </para> </listitem> </varlistentry> @@ -228,13 +234,21 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <listitem> <para> This clause specifies a list of tables to be excluded from the - publication. + publication. It can be used with <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal>. For <literal>FOR TABLES IN + SCHEMA</literal>, the exclusion applies only to tables in the schema + associated with the <literal>EXCEPT</literal>. </para> <para> - Once a table is excluded, the exclusion applies to that table - regardless of its name or schema. Renaming the table or moving it to - another schema using <command>ALTER TABLE ... SET SCHEMA</command> does - not remove the exclusion. + Once a table is excluded under <literal>FOR ALL TABLES</literal>, the + exclusion applies to that table regardless of its name or schema. + Renaming the table or moving it to another schema using + <command>ALTER TABLE ... SET SCHEMA</command> does not remove the + exclusion. However, for <literal>FOR TABLES IN SCHEMA</literal>, because + the <literal>EXCEPT</literal> is schema-scoped, moving a schema-excluded + table to another schema does remove the exclusion; if the table is later + moved back, the exclusion is not restored and must be re-established + with <command>ALTER PUBLICATION</command>. </para> <para> For inherited tables, if <literal>ONLY</literal> is specified before the @@ -247,8 +261,9 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> </para> <para> For partitioned tables, only the root partitioned table may be specified - in <literal>EXCEPT</literal>. Doing so excludes the root table and - all of its partitions from replication. The optional + in <literal>EXCEPT</literal>. Excluding the root table automatically + excludes all of its partitions from replication, even those in + schemas that are otherwise included in the publication. The optional <literal>ONLY</literal> and <literal>*</literal> has no effect for partitioned tables. </para> @@ -552,6 +567,15 @@ CREATE PUBLICATION production_publication FOR TABLE users, departments, TABLES I CREATE PUBLICATION sales_publication FOR TABLES IN SCHEMA marketing, sales; </programlisting></para> + <para> + Create a publication that publishes all changes for all the tables present in + the schema <structname>sales</structname>, except + <structname>internal</structname> and <structname>drafts</structname>: +<programlisting> +CREATE PUBLICATION sales_filtered FOR TABLES IN SCHEMA sales EXCEPT (TABLE internal, drafts); +</programlisting> + </para> + <para> Create a publication that publishes all changes for table <structname>users</structname>, but replicates only columns <structname>user_id</structname> and -- 2.50.1 (Apple Git-155)
^ permalink raw reply [nested|flat] 196+ messages in thread

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-30 06:03  Nisha Moond <nisha.moond412@gmail.com>
  parent: Peter Smith <smithpb2250@gmail.com>
  0 siblings, 0 replies; 196+ messages in thread

From: Nisha Moond @ 2026-07-30 06:03 UTC (permalink / raw)
  To: Peter Smith <smithpb2250@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Fri, Jul 24, 2026 at 11:54 AM Peter Smith <smithpb2250@gmail.com> wrote:
>
> Some review comments for the v23* patches
>

Thanks for the review. I've incorporated most of the suggestions in
v24. Please see my responses to a few below.

> //////////
> Patch 0001
> //////////
>
> src/backend/catalog/pg_publication.c
>
> is_table_publication:
>
> 2.
>  /*
> - * Returns true if the publication has explicitly included relation (i.e.,
> + * Returns true if the publication has an explicitly-included relation (i.e.,
>   * not marked as EXCEPT).
>   */
>
> In hindsight, the function comment seems a bit odd. It doesn't need to
> mention EXCEPT -- those are more like logic details about *how* it
> works, nothing to do with the purpose of the function.
>
> SUGGESTION
> Returns true if the publication has a FOR TABLE clause.
>

Since this function is being modified, updating the comment makes sense. Done.

> ~
>
> Similarly, the `is_schema_publication` function comment could simply say:
> Returns true if the publication has a FOR TABLES IN SCHEMA clause.
>

This patch doesn't touch this function, so I'm not sure unrelated
comments should be updated here.

> ~~~
>
> GetAllSchemaPublicationRelations:
>
> 3.
> + if (except_relids != NIL)
> + {
> + /* filter out any tables that appear in the EXCEPT clause */
>
> But `except_relids` really is a List so I think the comment saying
> "EXCEPT list" was probably fine here.
>

Fixed.

> ~~~
>
> is_table_publishable_in_publication:
>
> 5.
>   /*
>   * Check whether the table is explicitly published via pg_publication_rel
>   * or pg_publication_namespace.
> + *
> + * A pg_publication_rel row with prexcept=true means the table is
> + * explicitly excluded via EXCEPT and must not be reported as published,
> + * even if its schema is otherwise included.  A row with prexcept=false
> + * means it is explicitly included.  If no pg_publication_rel row exists,
> + * the table is published iff its schema appears in
> + * pg_publication_namespace.
>   */
> - return (SearchSysCacheExists2(PUBLICATIONRELMAP,
> -   ObjectIdGetDatum(relid),
> -   ObjectIdGetDatum(pub->oid)) ||
> - SearchSysCacheExists2(PUBLICATIONNAMESPACEMAP,
> -   ObjectIdGetDatum(get_rel_namespace(relid)),
> -   ObjectIdGetDatum(pub->oid)));
> + if (CheckPublicationRelEntry(pub->oid, relid, &is_except))
> + return !is_except;
> +
> + return SearchSysCacheExists2(PUBLICATIONNAMESPACEMAP,
> + ObjectIdGetDatum(get_rel_namespace(relid)),
> + ObjectIdGetDatum(pub->oid));
>
> I think that the last `if` would be better written as if/else. That's
> because your big comment applies to *both* of those returns, but it is
> not immediately obvious due to the blank line.
>

Done.

> ======
> src/backend/commands/publicationcmds.c
>
> AlterPublication:
>
> 6.
> Code was moved out of patch 0001.
>
> TBH, I thought this could've stayed in patch 0001 -- Although code was
> in the AlterPublication function, AFAICT it had nothing really to do
> with "alter" patch -- Isn't it more related just to the signature
> change of `ObjectsInPublicationToOids` which is elsewhere in here
> patch 0001?

I think it's fine to move the ALTER-related change into the respective
patch. It should make the review easier.

> //////////
> Patch 0003
> //////////
>
> src/backend/commands/publicationcmds.c
>
> 1.
> - List    *exceptrelations = NIL;
> + List    *except_pubtables = NIL;
>   List    *schemaidlist = NIL;
>   Oid pubid = pubform->oid;
>
>   ObjectsInPublicationToOids(stmt->pubobjects, pstate, &relations,
> -    &exceptrelations, &schemaidlist);
> +    &except_pubtables, &schemaidlist);
>
>
> (same as patch 0001 review comment #6)
>
> Wondering if this change belonged in patch 0001, which is where
> ObjectsInPublicationToOids signature was modified.
>

As above, I feel keeping it here makes it easier for reviewers to
follow the changes.

>
> //////////
> Patch 0005
> //////////
>
> There's a couple of threads [1][2] which might get pushed soon. Those
> are going to mean a rebase will be needed, so watch out for them.
>
> doc/src/sgml/logical-replication.sgml
> ======
> doc/src/sgml/ref/alter_publication.sgml
>
> 1.
> +   <varlistentry>
> +    <term><literal>EXCEPT</literal></term>
> +    <listitem>
> +     <para>
> +      When used with <literal>ADD TABLES IN SCHEMA</literal>
> +      or <literal>SET TABLES IN SCHEMA</literal>, specifies
> +      tables to be excluded from the publication.  Each named
> +      table must belong to the schema specified in the same
> +      <literal>TABLES IN SCHEMA</literal> clause.  Table names may be
> +      schema-qualified or unqualified; unqualified names are implicitly
> +      qualified with the schema named in the same clause.  See
> +      <xref linkend="sql-createpublication"/> for further details on the
> +      semantics of <literal>EXCEPT</literal>.
> +     </para>
> +     <para>
> +      Dropping a table always removes it from the <literal>EXCEPT</literal>
> +      clause.
> +     </para>
> +    </listitem>
> +   </varlistentry>
>
> Curiously, this does not mention FOR ALL TABLES EXCEPT?
>
> I felt there was a missing earlier paragraph "When used with ALL TABLES ..."?
>

The FOR ALL TABLES EXCEPT semantics are already documented in the
Description, as discussed in [1]. I'm not sure we need to repeat them
here.
If we decide a separate paragraph is needed for FOR ALL TABLES, we can
settle that in [1]. I'd prefer to keep this patch limited to FOR
TABLES IN SCHEMA.

[1] https://www.postgresql.org/message-id/CABdArM4L5JhUa_PB3TNb0zbor8PpAVX1H3qD%2B6XC3t9TGeJi0w%40mail.g...
--
Thanks,
Nisha





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-30 06:04  Nisha Moond <nisha.moond412@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  1 sibling, 0 replies; 196+ messages in thread

From: Nisha Moond @ 2026-07-30 06:04 UTC (permalink / raw)
  To: shveta malik <shveta.malik@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Tue, Jul 28, 2026 at 2:18 PM shveta malik <shveta.malik@gmail.com> wrote:
>
> On Thu, Jul 23, 2026 at 5:26 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
> >
> >
> > Attached v23 patch set addressing all of the above comments, as well
> > as the comments in [1] and [2].
> >
>
> A few comments on v23-001:
>
> 1)
> + if (CheckPublicationRelEntry(pubid, root, &root_except) && root_except)
> + ereport(ERROR,
> + errcode(ERRCODE_DUPLICATE_OBJECT),
> + errmsg("cannot add partition \"%s\" to publication \"%s\"",
> +    RelationGetQualifiedRelationName(targetrel),
>
> Is the errorcode "ERRCODE_DUPLICATE_OBJECT" intentional? To me it does
> not look duplicate object as ROOT was in EXCEPT while this
> we are trying to add to inclusion list. Other similar places have
> different error, see:
>
> + if (exceptrelid == explicitrelid)
> + ereport(ERROR,
> + errcode(ERRCODE_INVALID_PARAMETER_VALUE),
> + errmsg("table \"%s\" cannot be both published and excluded",
> +    RelationGetQualifiedRelationName(pri->relation)));
>

ERRCODE_INVALID_PARAMETER_VALUE seems like a better fit. Replaced it.

>
> 2)
> + * Also reject any relation in explicitrelids whose partition root is in
> + * except_rels.  Otherwise the catalog would be inconsistent (root excluded,
> + * partition explicitly included), and the ancestor-cascade rule would
> + * silently override the include at replication time.
>
> Shall we simply say:
> /*
>  * Also reject any relation in explicitrelids whose partition root is in
>  * except_rels. Excluding a partition root means that the entire partition
>  * tree is excluded, so a partition cannot be explicitly added to the
>  * publication if its partition root is excluded.
>  */
>

Done

> 3)
> Shall we change this too
> + errdetail("The table is currently named in the EXCEPT clause of the
> publication."),
> similar to:
> + errdetail("Partition root \"%s\" is named in the publication's
> EXCEPT clause for schema \"%s\".",
>

Done, now the error looks like -
 ERROR:  cannot add table "public.t1" to publication "p1"
 DETAIL:  The table is named in the publication's EXCEPT clause for
schema "public".

>
> 4)
> +
> + /*
> + * ancestors is NIL for a partition with a pending DETACH
> + * CONCURRENTLY.
> + */
> + if (ancestors != NIL)
> + root = llast_oid(ancestors);
>
> I see non-null ancestors check at some places while other places do it
> directly, see:
> + root = llast_oid(get_partition_ancestors(relid));
>
> is it intentional?
>

No, it was a miss; I corrected it at above and one more place in pgoutput.c

> 5)
> + list_free(ancestors);
>
> This is also done at some places, while missed at other places.

I checked the patch and list_free(ancestors) exists everywhere I
introduced the list.
Besides these, I noticed at least five existing places in HEAD where
the list isn't freed. Do you think it's worth fixing those in this
patch, or would it be better as a separate cleanup?

--
Thanks,
Nisha





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-30 06:19  Nisha Moond <nisha.moond412@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  2 siblings, 1 reply; 196+ messages in thread

From: Nisha Moond @ 2026-07-30 06:19 UTC (permalink / raw)
  To: shveta malik <shveta.malik@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Thu, Jul 30, 2026 at 11:33 AM Nisha Moond <nisha.moond412@gmail.com> wrote:
>
> On Tue, Jul 28, 2026 at 2:38 PM shveta malik <shveta.malik@gmail.com> wrote:
> >
> > Nisha, the changes in RelationBuildPublicationDesc() looks quite
> > tricky now. We are doing 'list_difference_oid' thrice:
> >
> > --for schema-pub
> > --for schmea-pubs on complete ancestor tree
> > --for all-tables pub
> >
> > Ultimately we are concatenating all individual pubids after
> > subtracting 'exceptpuboids' from each individual 'puboids' list. The
> > 'exceptpuboids' is computed only once and doesn't change with each
> > computation. Why don't we uncondiitonally do list_concat_unique_oid
> > for all pub-ids
> > and only minus 'exceptpuboids' once at the end? Won't it work? Let me
> > know if I am missing something.
> >
>
> Done as suggested. The change modifies the existing code slightly, but
> the function now seems simpler and easier to read overall. It works
> well based on my testing. I'll do a deeper analysis to ensure it
> doesn't change any existing behavior.
>
> > ~~
> >
> > I think, we can now merge 002 to 001, it will help in combined review
> > by placing except-validation logic where it should ultimately be.
> >
>
> Merged both into v24-0001.
> ~~~
>
> Attached v24 patch set.
>

I missed mentioning that, besides the comments, also fixed a bug in describe.
The bug:  with v23, describe (\d t) was incorrectly showing the table
as both included and excluded in same pub -
postgres=# CREATE PUBLICATION p FOR TABLES IN SCHEMA s EXCEPT (TABLE s.t);
CREATE PUBLICATION
postgres=# \d s.t;
                    Table "s.t"
 Column |  Type   | Collation | Nullable | Default
--------+---------+-----------+----------+---------
 a      | integer |           |          |
Included in publications:
    "p"
Excluded from publications:
    "p"

It is now fixed in v24.

--
Thanks,
Nisha





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-31 06:10  shveta malik <shveta.malik@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: shveta malik @ 2026-07-31 06:10 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; shveta malik <shveta.malik@gmail.com>

Nisha,
A few comments on v24-001:

1)
+ if (is_except)
+ ereport(ERROR,
+ (errcode(ERRCODE_DUPLICATE_OBJECT),
+ errmsg("cannot add table \"%s\" to publication \"%s\"",
+ RelationGetQualifiedRelationName(targetrel),
+ pub->name),
+ errdetail("The table is named in the publication's EXCEPT clause for
schema \"%s\".",
+    get_namespace_name(RelationGetNamespace(targetrel))),
+ errhint("Change the EXCEPT clause using ALTER PUBLICATION ... SET
TABLES IN SCHEMA ... EXCEPT.")));
+ else
+ ereport(ERROR,
+ (errcode(ERRCODE_DUPLICATE_OBJECT),
+ errmsg("relation \"%s\" is already member of publication \"%s\"",
+ RelationGetRelationName(targetrel), pub->name)));

Does ERRCODE_INVALID_PARAMETER_VALUE suits better in 'if-block' rather
than ERRCODE_DUPLICATE_OBJECT?
See similar error you added in CheckExceptNotInTableList():

+ if (exceptrelid == explicitrelid)
+ ereport(ERROR,
+ errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("table \"%s\" cannot be both published and excluded",
+    RelationGetQualifiedRelationName(pri->relation)));

2)
+static void
+ProcessSchemaExceptTables(Oid schemaid, List *except_tables,

Since we have defined most of the arguments in comment section, we can
add 'pstate' as well for the sake of completion.

3)
Atop CheckExceptNotInTableList(), please add a comment indicating why
this funciton is still needed when we already have similar checks in
publication_add_relation and check_publication_add_relation.

4)
I was debugging the flow to see why 'CheckExceptNotInTableList' is
still needed when we have similar check in publication_add_relation().
My analysis:

publication_add_relation() accepts 'if_not_exists' i.e. add the new
entry 'if already not present' else skip it (no error if it is a
duplicate addition). Most flows pass it as 'true'. The current code
skips raising error if if_not_exists=true and entry exists. It made
sense earlier, but in our implementation, I feel it should still raise
an error if entries are cross wired (i.e., if an exclusion is present
and we are trying to add it as an inclusion, or vice versa). The
'if_not_exists' based 'skip logic' should only be exercised if the
nature of existing entity is of same kind as user is trying to add.
Let me know if you have different understanding.

Based on this, I tried debugging:

create publication pub1 for table s1.t1, tables in schema s1 except
(table s1.t1);

What changes I did:
--I skipped CheckExceptNotInTableList() invoked from
CreatePublication() so that flow directly hits the immediate next call
PublicationAddTables for schmea's except entries.
--In publication_add_relation(), I made this 'if_not_exists'
correction (by simply making it false for debuggin purpose).

The flow was as follows:

--CREATE-SUb first added table s1.t1 with prexcept=false through
PublicationAddTables.

--It then added Schmea to pg_pub_namespace using PublicationAddSchemas
and then invoked PublicationAddTables on except-table for the schema.
This step (against my expectation) could not find the entry added in
previous step (prexcept=false once) using CheckPublicationRelEntry()
and thus could not hit the required error. Instead it hit more
internal error:
ERROR:  duplicate key value violates unique constraint
"pg_publication_rel_prrelid_prpubid_index"

So it seems the catalog change from the first step was not visible in
the second step. What am I missing? The rel-cache invalidation or
something else?

Nisha, can you debug and analyse in this direction? Expectation is to
either get rid of CheckExceptNotInTableList() or to conclude that
CheckExceptNotInTableList() is a reasonable addition to the code.

thanks
Shveta






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-31 07:47  Shlok Kyal <shlok.kyal.oss@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  2 siblings, 1 reply; 196+ messages in thread

From: Shlok Kyal @ 2026-07-31 07:47 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Peter Smith <smithpb2250@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

> Attached v24 patch set.
>
Hi Nisha,

While addressing comments for one of my patches, I took a quick look
at patch 0004 (the documentation patch). I have a few comments:
1. While building documenttation, I find following error:
/usr/bin/xmllint --nonet --path . --path . --output postgres-full.xml
--noent --valid postgres.sgml
/usr/bin/xsltproc --nonet --path . --path . --stringparam pg.version
'20devel'  stylesheet.xsl postgres-full.xml
ERROR: id attribute missing on <varlistentry> element under /book[@id
= 'postgres']/part[@id = 'reference']/reference[@id =
'sql-commands']/refentry[@id =
'sql-alterpublication']/refsect1/variablelist
no result for postgres-full.xml
make: *** [Makefile:130: html-stamp] Error 10

I think we need to define a id attribute here:
+   <varlistentry>
+    <term><literal>EXCEPT</literal></term>
+    <listitem>

2. Should we add 'clause' after <literal>EXCEPT</literal> ?
+      SCHEMA</literal>, the exclusion applies only to tables in the schema
+      associated with the <literal>EXCEPT</literal>.

3. Maybe we can simplify the below:
+   <structname>sales.drafts</structname>. Other than
+   <structname>sales.drafts</structname>, any previously excluded
tables for schema
+   <structname>sales</structname> are no longer excluded. Any schemas
previously in

Maybe change:
Other than <structname>sales.drafts</structname>, any previously excluded tables
for schema <structname>sales</structname> are no longer excluded.
to:
All other previously excluded tables in schema <structname>sales</structname>
are no longer excluded.

Thanks,
Shlok Kyal






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-07-31 08:44  Peter Smith <smithpb2250@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  2 siblings, 1 reply; 196+ messages in thread

From: Peter Smith @ 2026-07-31 08:44 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

A couple of comments for v24-0001

======
Commit message.

1.
Extend table exclusion support in publications to allow specific
tables to be excluded from schema-level publications using an
EXCEPT clause in CREATE PUBLICATION.

Supported syntax:
CREATE PUBLICATION <pub> FOR TABLES IN SCHEMA s EXCEPT (TABLE t1,...);

~

1a.
Change /<pub>/pub/

~

1b.
Now that you are combining more patches, this commit message seemed a
bit light on details.

You might say include things like:

NOTES
- Conflicting or redundant EXCEPT clauses are not allowed
- EXCEPT clause tables must come from the associate schema
- psql describe commands are updated handle tables excluded from schemas
- Excluding partitions in not allowed
- Excluding a partition root excludes the entire partition tree, even
tables in different schemas
- etc.

======
src/backend/utils/cache/relcache.c

RelationBuildPublicationDesc:

1.
+ /* Drop the publications that exclude this relation. */
+ if (exceptpuboids != NIL)
+ puboids = list_difference_oid(puboids, exceptpuboids);
+

AFAIK, there is no DROP PUBLICATION in this logic.

Instead of "Drop", how about "Ignore" or "Skip" to remove any ambiguity.

======
Kind Regards,
Peter Smith.
Fujitsu Australia






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-04 08:41  Nisha Moond <nisha.moond412@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  0 siblings, 4 replies; 196+ messages in thread

From: Nisha Moond @ 2026-08-04 08:41 UTC (permalink / raw)
  To: shveta malik <shveta.malik@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Fri, Jul 31, 2026 at 11:41 AM shveta malik <shveta.malik@gmail.com> wrote:
>
> Nisha,
> A few comments on v24-001:
>
> 1)
> + if (is_except)
> + ereport(ERROR,
> + (errcode(ERRCODE_DUPLICATE_OBJECT),
> + errmsg("cannot add table \"%s\" to publication \"%s\"",
> + RelationGetQualifiedRelationName(targetrel),
> + pub->name),
> + errdetail("The table is named in the publication's EXCEPT clause for
> schema \"%s\".",
> +    get_namespace_name(RelationGetNamespace(targetrel))),
> + errhint("Change the EXCEPT clause using ALTER PUBLICATION ... SET
> TABLES IN SCHEMA ... EXCEPT.")));
> + else
> + ereport(ERROR,
> + (errcode(ERRCODE_DUPLICATE_OBJECT),
> + errmsg("relation \"%s\" is already member of publication \"%s\"",
> + RelationGetRelationName(targetrel), pub->name)));
>
> Does ERRCODE_INVALID_PARAMETER_VALUE suits better in 'if-block' rather
> than ERRCODE_DUPLICATE_OBJECT?
> See similar error you added in CheckExceptNotInTableList():
>
> + if (exceptrelid == explicitrelid)
> + ereport(ERROR,
> + errcode(ERRCODE_INVALID_PARAMETER_VALUE),
> + errmsg("table \"%s\" cannot be both published and excluded",
> +    RelationGetQualifiedRelationName(pri->relation)));
>

Changed to ERRCODE_INVALID_PARAMETER_VALUE in if-block.

> 2)
> +static void
> +ProcessSchemaExceptTables(Oid schemaid, List *except_tables,
>
> Since we have defined most of the arguments in comment section, we can
> add 'pstate' as well for the sake of completion.
>

Done.

> 3)
> Atop CheckExceptNotInTableList(), please add a comment indicating why
> this funciton is still needed when we already have similar checks in
> publication_add_relation and check_publication_add_relation.
>
> 4)
> I was debugging the flow to see why 'CheckExceptNotInTableList' is
> still needed when we have similar check in publication_add_relation().
> My analysis:
>
> publication_add_relation() accepts 'if_not_exists' i.e. add the new
> entry 'if already not present' else skip it (no error if it is a
> duplicate addition). Most flows pass it as 'true'. The current code
> skips raising error if if_not_exists=true and entry exists. It made
> sense earlier, but in our implementation, I feel it should still raise
> an error if entries are cross wired (i.e., if an exclusion is present
> and we are trying to add it as an inclusion, or vice versa). The
> 'if_not_exists' based 'skip logic' should only be exercised if the
> nature of existing entity is of same kind as user is trying to add.
> Let me know if you have different understanding.
>
> Based on this, I tried debugging:
>
> create publication pub1 for table s1.t1, tables in schema s1 except
> (table s1.t1);
>
> What changes I did:
> --I skipped CheckExceptNotInTableList() invoked from
> CreatePublication() so that flow directly hits the immediate next call
> PublicationAddTables for schmea's except entries.
> --In publication_add_relation(), I made this 'if_not_exists'
> correction (by simply making it false for debuggin purpose).
>
> The flow was as follows:
>
> --CREATE-SUb first added table s1.t1 with prexcept=false through
> PublicationAddTables.
>
> --It then added Schmea to pg_pub_namespace using PublicationAddSchemas
> and then invoked PublicationAddTables on except-table for the schema.
> This step (against my expectation) could not find the entry added in
> previous step (prexcept=false once) using CheckPublicationRelEntry()
> and thus could not hit the required error. Instead it hit more
> internal error:
> ERROR:  duplicate key value violates unique constraint
> "pg_publication_rel_prrelid_prpubid_index"
>
> So it seems the catalog change from the first step was not visible in
> the second step. What am I missing? The rel-cache invalidation or
> something else?
>
> Nisha, can you debug and analyse in this direction? Expectation is to
> either get rid of CheckExceptNotInTableList() or to conclude that
> CheckExceptNotInTableList() is a reasonable addition to the code.
>

CheckExceptNotInTableList() was written to handle only CREATE
PUBLICATION ... EXCEPT.

IIUC you are not seeing the catalog change because of command-counter
MVCC, not relcache invalidation. CommandCounterIncrement() is what
makes the changes so far visible to later lookups —
CreatePublication() already does that once, for the new pg_publication
row.

So yes, we could add a CommandCounterIncrement() between the two
PublicationAddTables() calls, but I don't think it gets us to a better
place:
  1. The error message would be misleading. The explicit tables are
added first, so it is the later EXCEPT insertion that finds the
existing row, and that row has prexcept = false — so we would report -
relation "%s" is already member of publication "%s" (with a hint
pointing at ALTER PUBLICATION ... SET) for a CREATE PUBLICATION
statement. This one is arguable, though — we could tweak the error
message accordingly.
  2. It still doesn't solve the partition case. Visibility aside,
check_publication_add_relation() only looks upwards from the relation
being added ("is my root excluded?"). For
     CREATE PUBLICATION p FOR TABLE part, TABLES IN SCHEMA s EXCEPT
(TABLE root);
  the root's EXCEPT row does not exist yet when part is inserted, and
when root is inserted it isn't a partition, so no check runs at all.
Catching it there would need a new downward scan over every partition
of an excluded root, which is more work than comparing the lists we
already have in hand.

Since CreatePublication() has every table of the statement available
in memory, this separate function identifies the contradiction with no
catalog lookup at all. So IMO keeping CheckExceptNotInTableList() is
the better way; I have expanded the comment atop the function to
explain this. Let me know your thoughts.
~~~

Attached is the v25 patch set addressing all of the above, as well as
Shlok's and Peter's comments in [1] and [2].

[1] https://www.postgresql.org/message-id/CANhcyEXtX-tAMMMvsK%2Be1TUzUWT77%2BiwTbXPx-nM1Va_UjYTHg%40mail...
[2] https://www.postgresql.org/message-id/CAHut%2BPumod7UW71WHO0GMA2qibG%2BTTsX7j5FJykAJgBwR73EdA%40mail...

--
Thanks,
Nisha

Attachments: download all (4 files, .tar.gz)

v25-0001-Support-EXCEPT-clause-for-schema-level-publicati.patch (application/octet-stream, 85.7K) download From f1702d41935c977d1ada0df02130c708c542dad9 Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Tue, 16 Jun 2026 10:58:49 +0530 Subject: [PATCH v25 1/4] Support EXCEPT clause for schema-level publications Extend table exclusion support in publications to allow specific tables to be excluded from schema-level publications using an EXCEPT clause in CREATE PUBLICATION. Supported syntax: CREATE PUBLICATION pub FOR TABLES IN SCHEMA s EXCEPT (TABLE t1,...); This reuses the existing opt_pub_except_clause grammar and stores excluded tables as pg_publication_rel entries with prexcept = true, requiring no catalog changes. NOTES - EXCEPT is supported only with FOR TABLES IN SCHEMA, not FOR TABLE. - Each EXCEPT clause applies only to its own schema; cross-schema references are rejected. - A schema may appear only once with an EXCEPT clause. - A table cannot be both explicitly published and excluded in the same statement. - Only partition roots may be excluded. Excluding a root excludes the entire partition tree, including partitions in other published schemas. Individual partitions cannot be added while their root is excluded, and ATTACH PARTITION is rejected if the attached table is excluded. - ALTER TABLE ... SET SCHEMA removes schema-scoped exclusions, matching existing schema-publication behavior. - psql describe output and tab completion are updated to support the new syntax. --- src/backend/catalog/pg_publication.c | 237 ++++++++++++++--- src/backend/commands/publicationcmds.c | 255 +++++++++++++++++- src/backend/commands/tablecmds.c | 24 +- src/backend/parser/gram.y | 27 +- src/backend/replication/pgoutput/pgoutput.c | 37 ++- src/backend/utils/cache/relcache.c | 38 ++- src/bin/psql/describe.c | 44 +++- src/bin/psql/tab-complete.in.c | 35 ++- src/include/catalog/pg_publication.h | 1 + src/include/commands/publicationcmds.h | 2 + src/include/nodes/parsenodes.h | 2 + src/test/regress/expected/publication.out | 278 +++++++++++++++++++- src/test/regress/sql/publication.sql | 178 ++++++++++++- src/test/subscription/t/037_except.pl | 208 ++++++++++++++- 14 files changed, 1270 insertions(+), 96 deletions(-) diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index ea28ec319c5..183a3b2abff 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -53,7 +53,7 @@ typedef struct * error if not. */ static void -check_publication_add_relation(PublicationRelInfo *pri) +check_publication_add_relation(PublicationRelInfo *pri, Oid pubid) { Relation targetrel = pri->relation; const char *relname; @@ -70,12 +70,51 @@ check_publication_add_relation(PublicationRelInfo *pri) errormsg = gettext_noop("cannot add relation \"%s\" to publication"); } - /* If in EXCEPT clause, must be root partitioned table */ - if (pri->except && targetrel->rd_rel->relispartition) - ereport(ERROR, - (errcode(ERRCODE_INVALID_PARAMETER_VALUE), - errmsg(errormsg, relname), - errdetail("This operation is not supported for individual partitions."))); + /* + * A partition cannot be added to a publication if its partition root is + * excluded by the publication. We follow the rule that excluding a + * partition root means that the entire partition tree is excluded. Thus, + * check whether the root is in the EXCEPT clause and reject adding the + * individual partition to the publication. + */ + if (targetrel->rd_rel->relispartition) + { + List *ancestors; + + if (pri->except) + { + /* If in EXCEPT clause, must be root partitioned table */ + ereport(ERROR, + (errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg(errormsg, relname), + errdetail("This operation is not supported for individual partitions."))); + } + + /* + * ancestors is NIL for a partition with a pending DETACH + * CONCURRENTLY, in which case there is no root to check. + */ + ancestors = get_partition_ancestors(RelationGetRelid(targetrel)); + if (ancestors != NIL) + { + Oid root = llast_oid(ancestors); + bool root_except; + + if (CheckPublicationRelEntry(pubid, root, &root_except) && root_except) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("cannot add partition \"%s\" to publication \"%s\"", + RelationGetQualifiedRelationName(targetrel), + get_publication_name(pubid, false)), + errdetail("Partition root \"%s\" is named in the publication's EXCEPT clause for schema \"%s\".", + quote_qualified_identifier(get_namespace_name(get_rel_namespace(root)), + get_rel_name(root)), + get_namespace_name(get_rel_namespace(root))), + errhint("Change the EXCEPT clause using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT.")); + } + + list_free(ancestors); + } /* Must be a regular or partitioned table */ if (RelationGetForm(targetrel)->relkind != RELKIND_RELATION && @@ -319,8 +358,7 @@ is_schema_publication(Oid pubid) } /* - * Returns true if the publication has explicitly included relation (i.e., - * not marked as EXCEPT). + * Returns true if the publication has a FOR TABLE clause. */ bool is_table_publication(Oid pubid) @@ -340,19 +378,23 @@ is_table_publication(Oid pubid) scan = systable_beginscan(pubrelsrel, PublicationRelPrpubidIndexId, true, NULL, 1, &scankey); - tup = systable_getnext(scan); - if (HeapTupleIsValid(tup)) - { - Form_pg_publication_rel pubrel; - pubrel = (Form_pg_publication_rel) GETSTRUCT(tup); - - /* - * For any publication, pg_publication_rel contains either only EXCEPT - * entries or only explicitly included tables. Therefore, examining - * the first tuple is sufficient to determine table inclusion. - */ - result = !pubrel->prexcept; + /* + * A publication can have both explicitly included (prexcept = false) and + * EXCEPT (prexcept = true) rows for the same pubid. For example: + * + * CREATE PUBLICATION pub1 FOR TABLE s1.t1, TABLES IN SCHEMA s2 EXCEPT + * (TABLE s2.t1); + * + * Scan until we find an explicitly included row. + */ + while (HeapTupleIsValid(tup = systable_getnext(scan))) + { + if (!((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept) + { + result = true; + break; + } } systable_endscan(scan); @@ -361,6 +403,27 @@ is_table_publication(Oid pubid) return result; } +/* + * Check whether a pg_publication_rel row exists for (pubid, relid); if so, + * set *is_except to its prexcept flag. + */ +bool +CheckPublicationRelEntry(Oid pubid, Oid relid, bool *is_except) +{ + HeapTuple tup; + + tup = SearchSysCache2(PUBLICATIONRELMAP, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (!HeapTupleIsValid(tup)) + return false; + + *is_except = ((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept; + ReleaseSysCache(tup); + + return true; +} + /* * Returns true if the relation has column list associated with the * publication, false otherwise. @@ -456,11 +519,26 @@ GetPubPartitionOptionRelations(List *result, PublicationPartOpt pub_partopt, * ancestor is at the end of the list. */ Oid -GetTopMostAncestorInPublication(Oid puboid, List *ancestors, int *ancestor_level) +GetTopMostAncestorInPublication(Oid puboid, List *ancestors, + int *ancestor_level) { ListCell *lc; Oid topmost_relid = InvalidOid; int level = 0; + bool root_except; + + if (ancestors == NIL) + return InvalidOid; + + /* + * If the partition root is excluded from this publication via an EXCEPT + * clause, the partition is not published through this publication, so + * return InvalidOid. Since only partition roots can appear in an EXCEPT + * clause, the root is the only ancestor worth a catalog lookup. + */ + if (CheckPublicationRelEntry(puboid, llast_oid(ancestors), &root_except) && + root_except) + return InvalidOid; /* * Find the "topmost" ancestor that is in this publication. @@ -547,6 +625,7 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, List *relids = NIL; int i; bool inval_except_table; + bool is_except; rel = table_open(PublicationRelRelationId, RowExclusiveLock); @@ -555,21 +634,30 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, * duplicates, it's here just to provide nicer error message in common * case. The real protection is the unique key on the catalog. */ - if (SearchSysCacheExists2(PUBLICATIONRELMAP, ObjectIdGetDatum(relid), - ObjectIdGetDatum(pubid))) + if (CheckPublicationRelEntry(pubid, relid, &is_except)) { table_close(rel, RowExclusiveLock); if (if_not_exists) return InvalidObjectAddress; - ereport(ERROR, - (errcode(ERRCODE_DUPLICATE_OBJECT), - errmsg("relation \"%s\" is already member of publication \"%s\"", - RelationGetRelationName(targetrel), pub->name))); + if (is_except) + ereport(ERROR, + (errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("cannot add table \"%s\" to publication \"%s\"", + RelationGetQualifiedRelationName(targetrel), + pub->name), + errdetail("The table is named in the publication's EXCEPT clause for schema \"%s\".", + get_namespace_name(RelationGetNamespace(targetrel))), + errhint("Change the EXCEPT clause using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT."))); + else + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("relation \"%s\" is already member of publication \"%s\"", + RelationGetRelationName(targetrel), pub->name))); } - check_publication_add_relation(pri); + check_publication_add_relation(pri, pubid); /* Validate and translate column names into a Bitmapset of attnums. */ attnums = pub_collist_validate(pri->relation, pri->columns); @@ -992,12 +1080,13 @@ GetIncludedPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) * Gets list of table oids that were specified in the EXCEPT clause for a * publication. * - * This should only be used FOR ALL TABLES publications. + * This is used for FOR ALL TABLES and FOR TABLES IN SCHEMA publications, + * both of which support EXCEPT TABLE. */ List * GetExcludedPublicationTables(Oid pubid, PublicationPartOpt pub_partopt) { - Assert(GetPublication(pubid)->alltables); + Assert(GetPublication(pubid)->alltables || is_schema_publication(pubid)); return get_publication_relations(pubid, pub_partopt, true); } @@ -1242,22 +1331,63 @@ GetSchemaPublicationRelations(Oid schemaid, PublicationPartOpt pub_partopt) /* * Gets the list of all relations published by FOR TABLES IN SCHEMA - * publication. + * publication, excluding any tables listed in EXCEPT clauses. */ List * GetAllSchemaPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) { List *result = NIL; List *pubschemalist = GetPublicationSchemas(pubid); + List *except_relids = NIL; ListCell *cell; + /* get the list of tables excluded via EXCEPT TABLE for this publication */ + if (pubschemalist != NIL) + except_relids = GetExcludedPublicationTables(pubid, pub_partopt); + foreach(cell, pubschemalist) { Oid schemaid = lfirst_oid(cell); List *schemaRels = NIL; schemaRels = GetSchemaPublicationRelations(schemaid, pub_partopt); - result = list_concat(result, schemaRels); + + if (except_relids != NIL) + { + /* filter out any tables that appear in the EXCEPT list */ + foreach_oid(relid, schemaRels) + { + bool excluded = list_member_oid(except_relids, relid); + + /* + * A partition whose root is excluded from the publication is + * also excluded, even if the partition itself lives in a + * different (included) schema. Only the topmost root of a + * partition hierarchy can ever appear in EXCEPT (see + * check_publication_add_relation()), so it's enough to check + * the last element of the ancestors list, rather than walking + * the whole chain. + */ + if (!excluded && get_rel_relispartition(relid)) + { + List *ancestors = get_partition_ancestors(relid); + + if (ancestors != NIL) + { + excluded = list_member_oid(except_relids, + llast_oid(ancestors)); + list_free(ancestors); + } + } + + if (!excluded) + result = lappend_oid(result, relid); + } + + list_free(schemaRels); + } + else + result = list_concat(result, schemaRels); } return result; @@ -1334,6 +1464,7 @@ is_table_publishable_in_publication(Oid relid, Publication *pub) { bool relispartition; List *ancestors = NIL; + bool is_except; /* * For non-pubviaroot publications, a partitioned table is never the @@ -1381,6 +1512,10 @@ is_table_publishable_in_publication(Oid relid, Publication *pub) */ /* + * If the partition root is excluded via the EXCEPT clause, the partition + * is never considered to be published through this publication. Check + * this before checking whether an ancestor is published. + * * If an ancestor is published, the partition's status depends on * publish_via_partition_root value. * @@ -1390,20 +1525,38 @@ is_table_publishable_in_publication(Oid relid, Publication *pub) * If it's false, the partition is covered by its ancestor's presence in * the publication, it should be included (return true). */ - if (relispartition && - OidIsValid(GetTopMostAncestorInPublication(pub->oid, ancestors, NULL))) - return !pub->pubviaroot; + if (relispartition) + { + /* + * ancestors can be NIL for a partition whose DETACH ... CONCURRENTLY + * is pending, in which case there is no ancestor to check. + */ + if (ancestors != NIL && + CheckPublicationRelEntry(pub->oid, llast_oid(ancestors), &is_except) && + is_except) + return false; + + if (OidIsValid(GetTopMostAncestorInPublication(pub->oid, ancestors, NULL))) + return !pub->pubviaroot; + } /* * Check whether the table is explicitly published via pg_publication_rel * or pg_publication_namespace. + * + * A pg_publication_rel row with prexcept=true means the table is + * explicitly excluded via EXCEPT and must not be reported as published, + * even if its schema is otherwise included. A row with prexcept=false + * means it is explicitly included. If no pg_publication_rel row exists, + * the table is published iff its schema appears in + * pg_publication_namespace. */ - return (SearchSysCacheExists2(PUBLICATIONRELMAP, - ObjectIdGetDatum(relid), - ObjectIdGetDatum(pub->oid)) || - SearchSysCacheExists2(PUBLICATIONNAMESPACEMAP, - ObjectIdGetDatum(get_rel_namespace(relid)), - ObjectIdGetDatum(pub->oid))); + if (CheckPublicationRelEntry(pub->oid, relid, &is_except)) + return !is_except; + else + return SearchSysCacheExists2(PUBLICATIONNAMESPACEMAP, + ObjectIdGetDatum(get_rel_namespace(relid)), + ObjectIdGetDatum(pub->oid)); } /* diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 440adb356ad..3e86458ebd3 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -22,6 +22,7 @@ #include "catalog/namespace.h" #include "catalog/objectaccess.h" #include "catalog/objectaddress.h" +#include "catalog/partition.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" #include "catalog/pg_namespace.h" @@ -71,6 +72,11 @@ static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); static char defGetGeneratedColsOption(DefElem *def); +static void CheckExceptNotInTableList(List *except_rels, List *explicitrelids); +static void ProcessSchemaExceptTables(Oid schemaid, List *except_tables, + ParseState *pstate, List **schemas, + List **schemas_with_except, + List **except_pubtables); static void @@ -175,16 +181,87 @@ parse_publication_options(ParseState *pstate, } } +/* + * Qualify unqualified EXCEPT table names with the given schema (rejecting + * any explicitly qualified with a different schema), and append them to + * *except_pubtables. + * + * Also rejects a schema being mentioned more than once with an EXCEPT + * clause, even if the EXCEPT clauses are identical — much like + * OpenTableList() rejects "FOR TABLE t1(a), t1(a)" despite the column + * lists matching. A schema can still be mentioned multiple times, just + * not more than once with EXCEPT. + * + * schemaid: OID of the schema for this TABLES IN SCHEMA mention. + * except_tables: the EXCEPT list (or NIL) attached to this mention. + * pstate: parse state of the statement, used to report the error position of + * an offending EXCEPT entry. + * *schemas: accumulates all schema OIDs seen so far in this statement. + * *schemas_with_except: This is a subset of *schemas. Tracks which of + * the seen schemas of this statement had an EXCEPT clause. + * *except_pubtables: accumulates the (now schema-qualified) EXCEPT table + * entries across the whole statement. + */ +static void +ProcessSchemaExceptTables(Oid schemaid, List *except_tables, + ParseState *pstate, List **schemas, + List **schemas_with_except, List **except_pubtables) +{ + char *schema_name = get_namespace_name(schemaid); + bool schema_has_except = (except_tables != NIL); + + /* + * A repeating schema is only a problem if this mention has EXCEPT, or an + * earlier mention of the same schema did. + */ + if (list_member_oid(*schemas, schemaid)) + { + if (schema_has_except || + list_member_oid(*schemas_with_except, schemaid)) + ereport(ERROR, + errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("conflicting or redundant EXCEPT clauses for schema \"%s\"", + schema_name)); + } + + if (schema_has_except) + *schemas_with_except = lappend_oid(*schemas_with_except, schemaid); + + /* Filter out duplicates if the user specifies "sch1, sch1" */ + *schemas = list_append_unique_oid(*schemas, schemaid); + + if (!schema_has_except) + return; + + foreach_ptr(PublicationObjSpec, eobj, except_tables) + { + RangeVar *relation = eobj->pubtable->relation; + + if (relation->schemaname == NULL) + relation->schemaname = schema_name; + else if (strcmp(relation->schemaname, schema_name) != 0) + ereport(ERROR, + errcode(ERRCODE_INVALID_OBJECT_DEFINITION), + errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", + quote_qualified_identifier(relation->schemaname, relation->relname), + schema_name), + parser_errposition(pstate, eobj->location)); + + *except_pubtables = lappend(*except_pubtables, eobj->pubtable); + } +} + /* * Convert the PublicationObjSpecType list into schema oid list and * PublicationTable list. */ static void ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, - List **rels, List **exceptrels, List **schemas) + List **rels, List **except_pubtables, List **schemas) { ListCell *cell; PublicationObjSpec *pubobj; + List *schemas_with_except = NIL; if (!pubobjspec_list) return; @@ -200,7 +277,7 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, { case PUBLICATIONOBJ_EXCEPT_TABLE: pubobj->pubtable->except = true; - *exceptrels = lappend(*exceptrels, pubobj->pubtable); + *except_pubtables = lappend(*except_pubtables, pubobj->pubtable); break; case PUBLICATIONOBJ_TABLE: pubobj->pubtable->except = false; @@ -209,8 +286,10 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, case PUBLICATIONOBJ_TABLES_IN_SCHEMA: schemaid = get_namespace_oid(pubobj->name, false); - /* Filter out duplicates if user specifies "sch1, sch1" */ - *schemas = list_append_unique_oid(*schemas, schemaid); + ProcessSchemaExceptTables(schemaid, pubobj->except_tables, + pstate, schemas, + &schemas_with_except, + except_pubtables); break; case PUBLICATIONOBJ_TABLES_IN_CUR_SCHEMA: search_path = fetch_search_path(false); @@ -222,8 +301,10 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, schemaid = linitial_oid(search_path); list_free(search_path); - /* Filter out duplicates if user specifies "sch1, sch1" */ - *schemas = list_append_unique_oid(*schemas, schemaid); + ProcessSchemaExceptTables(schemaid, pubobj->except_tables, + pstate, schemas, + &schemas_with_except, + except_pubtables); break; default: /* shouldn't happen */ @@ -770,6 +851,72 @@ TransformPubWhereClauses(List *tables, const char *queryString, } } +/* + * Check that a table is not both excluded and published in the same DDL. + * + * An excluded relation (except_rels) cannot also be present in + * explicitrelids, the list of OIDs added to the publication by the explicit + * TABLE list. + * + * Also reject any relation in explicitrelids whose partition root is in + * except_rels. Excluding a partition root means that the entire partition + * tree is excluded, so a partition cannot be explicitly added to the + * publication if its partition root is excluded. + * + * Both checks are made here, on the lists the statement supplied, because at + * this point the catalog cannot answer either question: + * + * - CreatePublication() inserts the explicit tables and the EXCEPT tables in + * a single command, and a row inserted by the current command is not + * visible to a later lookup within that command. So the similar checks in + * publication_add_relation() and check_publication_add_relation(), which + * read pg_publication_rel, find nothing to complain about. + * + * - In the partition case the excluded root's row does not exist at all yet, + * and those checks only look upward from the relation being added. + */ +static void +CheckExceptNotInTableList(List *except_rels, List *explicitrelids) +{ + foreach_oid(explicitrelid, explicitrelids) + { + Oid root = InvalidOid; + + if (get_rel_relispartition(explicitrelid)) + { + List *ancestors = get_partition_ancestors(explicitrelid); + + /* + * ancestors is NIL for a partition with a pending DETACH + * CONCURRENTLY. + */ + if (ancestors != NIL) + root = llast_oid(ancestors); + list_free(ancestors); + } + + foreach_ptr(PublicationRelInfo, pri, except_rels) + { + Oid exceptrelid = RelationGetRelid(pri->relation); + + if (exceptrelid == explicitrelid) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" cannot be both published and excluded", + RelationGetQualifiedRelationName(pri->relation))); + + if (OidIsValid(root) && exceptrelid == root) + ereport(ERROR, + (errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("partition \"%s\" cannot be both published and excluded", + quote_qualified_identifier(get_namespace_name(get_rel_namespace(explicitrelid)), + get_rel_name(explicitrelid))), + errdetail("Partition root \"%s\" is named in the publication's EXCEPT clause for schema \"%s\".", + RelationGetQualifiedRelationName(pri->relation), + get_namespace_name(RelationGetNamespace(pri->relation))))); + } + } +} /* * Given a list of tables that are going to be added to a publication, @@ -849,7 +996,7 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) char publish_generated_columns; AclResult aclresult; List *relations = NIL; - List *exceptrelations = NIL; + List *except_pubtables = NIL; List *schemaidlist = NIL; /* must have CREATE privilege on database */ @@ -936,16 +1083,16 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) /* Associate objects with the publication. */ ObjectsInPublicationToOids(stmt->pubobjects, pstate, &relations, - &exceptrelations, &schemaidlist); + &except_pubtables, &schemaidlist); if (stmt->for_all_tables) { /* Process EXCEPT table list */ - if (exceptrelations != NIL) + if (except_pubtables != NIL) { List *rels; - rels = OpenTableList(exceptrelations); + rels = OpenTableList(except_pubtables); PublicationAddTables(puboid, rels, true, NULL); CloseTableList(rels); } @@ -959,6 +1106,8 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) } else if (!stmt->for_all_sequences) { + List *explicitrelids = NIL; + /* FOR TABLES IN SCHEMA requires superuser */ if (schemaidlist != NIL && !superuser()) ereport(ERROR, @@ -978,6 +1127,20 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) publish_via_partition_root); PublicationAddTables(puboid, rels, true, NULL); + + /* + * Collect explicit table OIDs now, before we close the relation + * list, so that except-table validation below can check for + * contradictions without relying on a catalog scan that might not + * yet see the just-inserted rows. + */ + if (except_pubtables != NIL) + { + foreach_ptr(PublicationRelInfo, pri, rels) + explicitrelids = lappend_oid(explicitrelids, + RelationGetRelid(pri->relation)); + } + CloseTableList(rels); } @@ -989,6 +1152,22 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) */ LockSchemaList(schemaidlist); PublicationAddSchemas(puboid, schemaidlist, true, NULL); + + if (except_pubtables != NIL) + { + List *except_rels; + + except_rels = OpenTableList(except_pubtables); + + /* + * Validate that a table is not both explicitly included and + * excluded by the schema's EXCEPT clause. + */ + CheckExceptNotInTableList(except_rels, explicitrelids); + + PublicationAddTables(puboid, except_rels, true, NULL); + CloseTableList(except_rels); + } } } @@ -1829,6 +2008,62 @@ RemovePublicationSchemaById(Oid psoid) table_close(rel, RowExclusiveLock); } +/* + * Remove any EXCEPT clause entries for a relation from schema publications. + * Called when a table changes schema (ALTER TABLE ... SET SCHEMA), so that + * a schema-scoped exclusion does not silently follow the table to its new + * schema. + */ +void +RemoveSchemaPubExceptForRel(Oid relid, Oid oldNspOid, Oid newNspOid) +{ + List *pubids; + + /* + * If the table is not actually moving to a different schema (no-op ALTER + * TABLE ... SET SCHEMA <current_schema>), there is nothing to do. + */ + if (oldNspOid == newNspOid) + return; + + pubids = GetRelationExcludedPublications(relid); + + foreach_oid(pubid, pubids) + { + Oid proid; + + /* + * This problem does not apply to FOR ALL TABLES publications, because + * their EXCEPT clause is publication-scoped, not schema-scoped: the + * exclusion should persist regardless of what schema the table is in. + */ + if (!is_schema_publication(pubid)) + continue; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddress obj; + + ObjectAddressSet(obj, PublicationRelRelationId, proid); + + ereport(DEBUG2, + errmsg_internal("auto-remove exclusion of table \"%s.%s\" from publication \"%s\": table moved to schema \"%s\"", + get_namespace_name(oldNspOid), + get_rel_name(relid), + get_publication_name(pubid, false), + get_namespace_name(newNspOid))); + + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + list_free(pubids); +} + /* * Open relations specified by a PublicationTable list. * The returned tables are locked in ShareUpdateExclusiveLock mode in order to diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 2fa534413ea..6d0b7b77432 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -49,6 +49,7 @@ #include "catalog/pg_opclass.h" #include "catalog/pg_policy.h" #include "catalog/pg_proc.h" +#include "catalog/pg_publication.h" #include "catalog/pg_publication_rel.h" #include "catalog/pg_rewrite.h" #include "catalog/pg_statistic_ext.h" @@ -63,6 +64,7 @@ #include "commands/event_trigger.h" #include "commands/extension.h" #include "commands/repack.h" +#include "commands/publicationcmds.h" #include "commands/sequence.h" #include "commands/tablecmds.h" #include "commands/tablespace.h" @@ -19735,6 +19737,16 @@ AlterTableNamespaceInternal(Relation rel, Oid oldNspOid, Oid nspOid, AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid, false, objsMoved); + /* + * Remove any EXCEPT clause entries for this relation from schema + * publications. A schema-scoped exclusion is no longer meaningful once + * the table moves to a different schema. + */ + if (rel->rd_rel->relkind == RELKIND_RELATION || + rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE) + RemoveSchemaPubExceptForRel(RelationGetRelid(rel), oldNspOid, + nspOid); + table_close(classRel, RowExclusiveLock); } @@ -21068,6 +21080,7 @@ ATExecAttachPartition(List **wqueue, Relation rel, PartitionCmd *cmd, if (exceptpuboids != NIL) { bool first = true; + bool has_alltables_pub = false; StringInfoData pubnames; initStringInfo(&pubnames); @@ -21081,17 +21094,22 @@ ATExecAttachPartition(List **wqueue, Relation rel, PartitionCmd *cmd, else appendStringInfo(&pubnames, _(", \"%s\""), pubname); first = false; + + if (GetPublication(pubid)->alltables) + has_alltables_pub = true; } ereport(ERROR, errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), - errmsg_plural("cannot attach table \"%s\" as partition because it is referenced in publication %s EXCEPT clause", - "cannot attach table \"%s\" as partition because it is referenced in publications %s EXCEPT clause", + errmsg_plural("cannot attach table \"%s\" as partition because it is named in EXCEPT clause of publication %s", + "cannot attach table \"%s\" as partition because it is named in EXCEPT clause of publications %s", list_length(exceptpuboids), RelationGetRelationName(attachrel), pubnames.data), errdetail("The publication EXCEPT clause cannot contain tables that are partitions."), - errhint("Change the publication's EXCEPT clause using ALTER PUBLICATION ... SET ALL TABLES.")); + errhint("%s", has_alltables_pub ? + _("Change the EXCEPT clause using ALTER PUBLICATION ... SET ALL TABLES ... EXCEPT.") : + _("Change the EXCEPT clause using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT."))); } list_free(exceptpuboids); diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y index 17035fb4d15..14520a5ccab 100644 --- a/src/backend/parser/gram.y +++ b/src/backend/parser/gram.y @@ -58,6 +58,7 @@ #include "nodes/makefuncs.h" #include "nodes/nodeFuncs.h" #include "parser/parser.h" +#include "utils/builtins.h" #include "utils/datetime.h" #include "utils/xml.h" @@ -11282,7 +11283,7 @@ AlterOwnerStmt: ALTER AGGREGATE aggregate_with_argtypes OWNER TO RoleSpec * pub_obj is one of: * * TABLE table [, ...] - * TABLES IN SCHEMA schema [, ...] + * TABLES IN SCHEMA schema [EXCEPT (TABLE table [, ...] )] [, ...] * *****************************************************************************/ @@ -11342,23 +11343,26 @@ PublicationObjSpec: $$->pubtable->columns = $3; $$->pubtable->whereClause = $4; } - | TABLES IN_P SCHEMA ColId + | TABLES IN_P SCHEMA ColId opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_SCHEMA; $$->name = $4; + $$->except_tables = $5; $$->location = @4; } - | TABLES IN_P SCHEMA CURRENT_SCHEMA + | TABLES IN_P SCHEMA CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_CUR_SCHEMA; + $$->except_tables = $5; $$->location = @4; } - | ColId opt_column_list OptWhereClause + | ColId opt_column_list OptWhereClause opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $4; /* * If either a row filter or column list is specified, create * a PublicationTable object. @@ -11402,10 +11406,11 @@ PublicationObjSpec: $$->pubtable->columns = $2; $$->pubtable->whereClause = $3; } - | CURRENT_SCHEMA + | CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $2; $$->location = @1; } ; @@ -20867,6 +20872,11 @@ preprocess_pub_all_objtype_list(List *all_objects_list, List **pubobjects, /* * Process pubobjspec_list to check for errors in any of the objects and * convert PUBLICATIONOBJ_CONTINUATION into appropriate PublicationObjSpecType. + * + * The except_tables attached to TABLES IN SCHEMA nodes are left in place here; + * ObjectsInPublicationToOids() qualifies their names, validates schema + * membership, and merges the qualified tables into its except_pubtables + * output list once the schema OID is known. */ static void preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) @@ -20895,6 +20905,13 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLE) { + /* EXCEPT is not valid for table objects */ + if (pubobj->except_tables != NIL) + ereport(ERROR, + errcode(ERRCODE_SYNTAX_ERROR), + errmsg("EXCEPT is not allowed for TABLE publication objects"), + parser_errposition(pubobj->location)); + /* relation name or pubtable must be set for this type of object */ if (!pubobj->name && !pubobj->pubtable) ereport(ERROR, diff --git a/src/backend/replication/pgoutput/pgoutput.c b/src/backend/replication/pgoutput/pgoutput.c index 4ecfcbff7ab..a1ca56e06ee 100644 --- a/src/backend/replication/pgoutput/pgoutput.c +++ b/src/backend/replication/pgoutput/pgoutput.c @@ -2280,10 +2280,41 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) } } - if (list_member_oid(pubids, pub->oid) || - list_member_oid(schemaPubids, pub->oid) || - ancestor_published) + if (list_member_oid(pubids, pub->oid) || ancestor_published) publish = true; + else if (list_member_oid(schemaPubids, pub->oid)) + { + Oid root_relid; + bool root_is_except = false; + + /* + * schemaPubids is the list of publications that include + * relid's own schema, independent of the ancestor walk + * above -- a partition can live in a different schema + * than its root. Still need to check for exclusion here, + * using the top-most ancestor since only a root + * (non-partition) table can appear in an EXCEPT clause. + */ + if (am_partition) + { + List *ancestors = get_partition_ancestors(relid); + + /* + * ancestors is NIL for a partition with a pending + * DETACH CONCURRENTLY; + */ + root_relid = (ancestors == NIL) ? relid : + llast_oid(ancestors); + list_free(ancestors); + } + else + root_relid = relid; + + CheckPublicationRelEntry(pub->oid, root_relid, &root_is_except); + + if (!root_is_except) + publish = true; + } } /* diff --git a/src/backend/utils/cache/relcache.c b/src/backend/utils/cache/relcache.c index 19c4ff6e75e..419bcc09a35 100644 --- a/src/backend/utils/cache/relcache.c +++ b/src/backend/utils/cache/relcache.c @@ -5807,7 +5807,6 @@ RelationBuildPublicationDesc(Relation relation, PublicationDesc *pubdesc) { List *puboids = NIL; List *exceptpuboids = NIL; - List *alltablespuboids; ListCell *lc; MemoryContext oldcxt; Oid schemaid; @@ -5851,12 +5850,18 @@ RelationBuildPublicationDesc(Relation relation, PublicationDesc *pubdesc) if (relation->rd_rel->relispartition) { - Oid last_ancestor_relid; - - /* Add publications that the ancestors are in too. */ ancestors = get_partition_ancestors(relid); - last_ancestor_relid = llast_oid(ancestors); + /* + * Only the topmost root of a partition hierarchy can appear in an + * EXCEPT clause, so that is where exclusion has to be evaluated. + * ancestors is NIL for a partition with a pending DETACH + * CONCURRENTLY, in which case there is no root to consult. + */ + if (ancestors != NIL) + exceptpuboids = GetRelationExcludedPublications(llast_oid(ancestors)); + + /* Add publications that the ancestors are in too. */ foreach(lc, ancestors) { Oid ancestor = lfirst_oid(lc); @@ -5867,27 +5872,16 @@ RelationBuildPublicationDesc(Relation relation, PublicationDesc *pubdesc) puboids = list_concat_unique_oid(puboids, GetSchemaPublications(schemaid)); } - - /* - * Only the top-most ancestor can appear in the EXCEPT clause. - * Therefore, for a partition, exclusion must be evaluated at the - * top-most ancestor. - */ - exceptpuboids = GetRelationExcludedPublications(last_ancestor_relid); } else - { - /* - * For a regular table or a root partitioned table, check exclusion on - * table itself. - */ exceptpuboids = GetRelationExcludedPublications(relid); - } - alltablespuboids = GetAllTablesPublications(); - puboids = list_concat_unique_oid(puboids, - list_difference_oid(alltablespuboids, - exceptpuboids)); + puboids = list_concat_unique_oid(puboids, GetAllTablesPublications()); + + /* Ignore the publications that exclude this relation. */ + if (exceptpuboids != NIL) + puboids = list_difference_oid(puboids, exceptpuboids); + foreach(lc, puboids) { Oid pubid = lfirst_oid(lc); diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c index ad9c8affb4f..bb980fc1c91 100644 --- a/src/bin/psql/describe.c +++ b/src/bin/psql/describe.c @@ -3036,7 +3036,29 @@ describeOneTableDetails(const char *schemaname, "FROM pg_catalog.pg_publication p\n" " JOIN pg_catalog.pg_publication_namespace pn ON p.oid = pn.pnpubid\n" " JOIN pg_catalog.pg_class pc ON pc.relnamespace = pn.pnnspid\n" - "WHERE pc.oid ='%s' and pg_catalog.pg_relation_is_publishable('%s')\n" + "WHERE pc.oid ='%s' and pg_catalog.pg_relation_is_publishable('%s')\n", + oid, oid); + + if (pset.sversion >= 200000) + { + /* + * Publishing the schema does not publish a table named in the + * publication's EXCEPT clause, nor a partition whose root is + * named there, since excluding a root excludes the whole + * partition tree. Unlike the FOR ALL TABLES case below, a + * schema publication can have both kinds of + * pg_publication_rel row, so prexcept has to be tested. + */ + appendPQExpBuffer(&buf, + " AND NOT EXISTS (\n" + " SELECT 1\n" + " FROM pg_catalog.pg_publication_rel pr\n" + " WHERE pr.prpubid = p.oid AND pr.prexcept AND\n" + " (pr.prrelid = '%s' OR pr.prrelid = pg_catalog.pg_partition_root('%s')))\n", + oid, oid); + } + + appendPQExpBuffer(&buf, "UNION\n" "SELECT pubname\n" " , pg_catalog.pg_get_expr(pr.prqual, c.oid)\n" @@ -3060,7 +3082,7 @@ describeOneTableDetails(const char *schemaname, " FROM pg_catalog.pg_publication_namespace pn\n" " WHERE pn.pnpubid = p.oid\n" " AND pn.pnnspid = c.relnamespace)\n", - oid, oid, oid); + oid); if (pset.sversion >= 190000) { @@ -6839,6 +6861,24 @@ describePublications(const char *pattern) if (!addFooterToPublicationDesc(&buf, _("Tables from schemas:"), true, &cont)) goto error_return; + + if (pset.sversion >= 200000) + { + /* + * Get tables in the EXCEPT clause for this schema + * publication. + */ + printfPQExpBuffer(&buf, + "SELECT concat(c.relnamespace::regnamespace, '.', c.relname)\n" + "FROM pg_catalog.pg_class c\n" + " JOIN pg_catalog.pg_publication_rel pr ON c.oid = pr.prrelid\n" + "WHERE pr.prpubid = '%s'\n" + " AND pr.prexcept\n" + "ORDER BY 1", pubid); + if (!addFooterToPublicationDesc(&buf, _("Except tables:"), + true, &cont)) + goto error_return; + } } } else diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index 17dcabe755f..04f2b63535f 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -1065,6 +1065,24 @@ static const SchemaQuery Query_for_trigger_of_table = { "SELECT nspname FROM pg_catalog.pg_namespace "\ " WHERE nspname LIKE '%s'" +#define Query_for_list_of_tables_in_schema \ +"SELECT n.nspname || '.' || c.relname "\ +" FROM pg_catalog.pg_class c "\ +" JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "\ +" WHERE c.relkind IN (" CppAsString2(RELKIND_RELATION) ", " \ + CppAsString2(RELKIND_PARTITIONED_TABLE) ") "\ +" AND (n.nspname || '.' || c.relname) LIKE '%s' "\ +" AND n.nspname = '%s'" + +#define Query_for_list_of_tables_in_current_schema \ +"SELECT c.relname "\ +" FROM pg_catalog.pg_class c "\ +" JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "\ +" WHERE c.relkind IN (" CppAsString2(RELKIND_RELATION) ", " \ + CppAsString2(RELKIND_PARTITIONED_TABLE) ") "\ +" AND c.relname LIKE '%s' "\ +" AND n.nspname = pg_catalog.current_schema()" + /* Use COMPLETE_WITH_QUERY_VERBATIM with these queries for GUC names: */ #define Query_for_list_of_alter_system_set_vars \ "SELECT pg_catalog.lower(name) FROM pg_catalog.pg_settings "\ @@ -3777,8 +3795,21 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); - else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && (!ends_with(prev_wd, ','))) - COMPLETE_WITH("WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE", "WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* Complete "CREATE PUBLICATION <name> [...] WITH" */ else if (Matches("CREATE", "PUBLICATION", MatchAnyN, "WITH", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/include/catalog/pg_publication.h b/src/include/catalog/pg_publication.h index 89b4bb14f62..d241b781ccc 100644 --- a/src/include/catalog/pg_publication.h +++ b/src/include/catalog/pg_publication.h @@ -192,6 +192,7 @@ extern List *GetPubPartitionOptionRelations(List *result, Oid relid); extern Oid GetTopMostAncestorInPublication(Oid puboid, List *ancestors, int *ancestor_level); +extern bool CheckPublicationRelEntry(Oid pubid, Oid relid, bool *is_except); extern bool is_publishable_relation(Relation rel); extern bool is_schema_publication(Oid pubid); diff --git a/src/include/commands/publicationcmds.h b/src/include/commands/publicationcmds.h index 4cf45c17cc5..fb1703aa675 100644 --- a/src/include/commands/publicationcmds.h +++ b/src/include/commands/publicationcmds.h @@ -27,6 +27,8 @@ extern void AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt); extern void RemovePublicationById(Oid pubid); extern void RemovePublicationRelById(Oid proid); extern void RemovePublicationSchemaById(Oid psoid); +extern void RemoveSchemaPubExceptForRel(Oid relid, Oid oldNspOid, + Oid newNspOid); extern ObjectAddress AlterPublicationOwner(const char *name, Oid newOwnerId); extern void AlterPublicationOwner_oid(Oid pubid, Oid newOwnerId); diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h index 5c8f9a07b62..0cccb4393c2 100644 --- a/src/include/nodes/parsenodes.h +++ b/src/include/nodes/parsenodes.h @@ -4530,6 +4530,8 @@ typedef struct PublicationObjSpec PublicationObjSpecType pubobjtype; /* type of this publication object */ char *name; PublicationTable *pubtable; + List *except_tables; /* tables specified in the EXCEPT clause (for + * TABLES IN SCHEMA) */ ParseLoc location; /* token location, or -1 if unknown */ } PublicationObjSpec; diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 9c6386d518a..f8f4b187c0a 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -279,6 +279,12 @@ CREATE PUBLICATION testpub_foralltables_excepttable2 FOR ALL TABLES EXCEPT (test ERROR: syntax error at or near "testpub_tbl1" LINE 1: ..._foralltables_excepttable2 FOR ALL TABLES EXCEPT (testpub_tb... ^ +-- fail - EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testpub_tbl3); +ERROR: EXCEPT is not allowed for TABLE publication objects +LINE 2: FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testp... + ^ --------------------------------------------- -- SET ALL TABLES/SEQUENCES --------------------------------------------- @@ -473,13 +479,186 @@ CREATE TABLE tab_main (a int) PARTITION BY RANGE(a); -- Attaching a partition is not allowed if the partitioned table appears in a -- publication's EXCEPT clause. ALTER TABLE tab_main ATTACH PARTITION testpub_root FOR VALUES FROM (0) TO (200); -ERROR: cannot attach table "testpub_root" as partition because it is referenced in publication "testpub8" EXCEPT clause +ERROR: cannot attach table "testpub_root" as partition because it is named in EXCEPT clause of publication "testpub8" DETAIL: The publication EXCEPT clause cannot contain tables that are partitions. -HINT: Change the publication's EXCEPT clause using ALTER PUBLICATION ... SET ALL TABLES. +HINT: Change the EXCEPT clause using ALTER PUBLICATION ... SET ALL TABLES ... EXCEPT. RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Create same-named tables in public to verify unqualified EXCEPT entries +-- are qualified with the named schema, not public +CREATE TABLE testpub_nopk (foo int, bar int); +CREATE TABLE testpub_tbl_s1 (a int primary key, b text); +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + Publication testpub_schema_except1 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- Exclude multiple tables using unqualified names; same-named tables exist in +-- public to confirm unqualified names resolve to pub_test, not public +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + Publication testpub_schema_except2 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_nopk" + "pub_test.testpub_tbl_s1" + +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testp... + ^ +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); +ERROR: table "pub_test.testpub_tbl_s1" in EXCEPT clause does not belong to schema "public" +LINE 2: ...R TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.t... + ^ +-- Multiple schemas each with their own EXCEPT clause +CREATE PUBLICATION testpub_schema_except_multi + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_schema_except_multi + Publication testpub_schema_except_multi + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- fail: same schema repeated with same EXCEPT clauses +CREATE PUBLICATION testpub_schema_except_conflict + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: conflicting or redundant EXCEPT clauses for schema "pub_test" +-- fail: same schema repeated with conflicting or no EXCEPT clauses +CREATE PUBLICATION testpub_schema_except_conflict2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2), + pub_test; +ERROR: conflicting or redundant EXCEPT clauses for schema "pub_test" +-- ALTER TABLE ... SET SCHEMA on a table excluded by a schema publication: +-- the schema-scoped exclusion is no longer meaningful once the table moves +-- out of its schema, so the exclusion is auto-removed. +CREATE PUBLICATION testpub_schema_except_setsch + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_schema_except_setsch + Publication testpub_schema_except_setsch + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s2" + +ALTER TABLE pub_test.testpub_tbl_s2 SET SCHEMA public; +\dRp+ testpub_schema_except_setsch + Publication testpub_schema_except_setsch + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + +DROP PUBLICATION testpub_schema_except_setsch; +-- Restore for further tests +ALTER TABLE public.testpub_tbl_s2 SET SCHEMA pub_test; +-- fail: table appears in both the explicit table list and the EXCEPT clause +CREATE PUBLICATION testpub_except_conflict + FOR TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot be both published and excluded +-- fail: nonexistent table in EXCEPT clause +CREATE PUBLICATION testpub_except_norel + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- fail: partition cannot appear in EXCEPT clause; only root tables are allowed +CREATE TABLE pub_test.testpub_parted_s (a int) PARTITION BY LIST (a); +CREATE TABLE pub_test.testpub_part_s PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (1); +CREATE PUBLICATION testpub_except_partition + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); +ERROR: cannot specify relation "pub_test.testpub_part_s" in the publication EXCEPT clause +DETAIL: This operation is not supported for individual partitions. +-- fail: TABLE keyword is required for the first entry in the EXCEPT clause +CREATE PUBLICATION testpub_except_nokw + FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +ERROR: syntax error at or near "testpub_nopk" +LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + ^ +-- Check that a table excluded from a schema publication is reported only as +-- excluded and not as published. +\d pub_test.testpub_nopk + Table "pub_test.testpub_nopk" + Column | Type | Collation | Nullable | Default +--------+---------+-----------+----------+--------- + foo | integer | | | + bar | integer | | | +Included in publications: + "testpub_schema_except1" + "testpub_schema_except_multi" +Excluded from publications: + "testpub_schema_except2" + +-- fail: ADD TABLE for a partition is rejected when a partition ancestor +-- is currently in the publication's EXCEPT list. +CREATE PUBLICATION testpub_except_ancestor + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ALTER PUBLICATION testpub_except_ancestor ADD TABLE pub_test.testpub_part_s; +ERROR: cannot add partition "pub_test.testpub_part_s" to publication "testpub_except_ancestor" +DETAIL: Partition root "pub_test.testpub_parted_s" is named in the publication's EXCEPT clause for schema "pub_test". +HINT: Change the EXCEPT clause using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT. +DROP PUBLICATION testpub_except_ancestor; +-- fail: same contradiction (explicit partition + EXCEPT-ed ancestor), but +-- given in a single statement instead of two separate ones +CREATE PUBLICATION testpub_except_ancestor_same_create + FOR TABLE pub_test.testpub_part_s, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ERROR: partition "pub_test.testpub_part_s" cannot be both published and excluded +DETAIL: Partition root "pub_test.testpub_parted_s" is named in the publication's EXCEPT clause for schema "pub_test". +-- fail: same contradiction as above, but the partition lives in a different +-- schema (public) than its EXCEPT-ed root (pub_test) +CREATE TABLE public.testpub_part_s2 PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (2); +CREATE PUBLICATION testpub_except_ancestor_cross_schema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s), + TABLE public.testpub_part_s2; +ERROR: partition "public.testpub_part_s2" cannot be both published and excluded +DETAIL: Partition root "pub_test.testpub_parted_s" is named in the publication's EXCEPT clause for schema "pub_test". +DROP TABLE public.testpub_part_s2; +-- Cleanup +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP TABLE pub_test.testpub_parted_s CASCADE; +DROP TABLE testpub_nopk, testpub_tbl_s1; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +--------------------------------------------- +-- Tests for publications with SEQUENCES +--------------------------------------------- CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; -- FOR ALL SEQUENCES @@ -1970,6 +2149,54 @@ ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b); ERROR: column specification not allowed for schema LINE 1: ...TION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b)... ^ +-- EXCEPT clause with CURRENT_SCHEMA: cross-schema entry must be rejected +SET search_path = pub_test1; +-- qualified name from wrong schema -> error +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.tbl1); +ERROR: table "pub_test2.tbl1" in EXCEPT clause does not belong to schema "pub_test1" +LINE 1: ...FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.... + ^ +-- unqualified name implicitly qualified with current schema (pub_test1.tbl) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl); +RESET client_min_messages; +\dRp+ testpub_cursch_except + Publication testpub_cursch_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test1" +Except tables: + "pub_test1.tbl" + +DROP PUBLICATION testpub_cursch_except; +-- succeeds: CURRENT_SCHEMA and pub_test1 (same schema) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_named_same + FOR TABLES IN SCHEMA CURRENT_SCHEMA, pub_test1; +RESET client_min_messages; +\dRp+ testpub_cursch_named_same + Publication testpub_cursch_named_same + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test1" + +DROP PUBLICATION testpub_cursch_named_same; +-- fail: CURRENT_SCHEMA and pub_test1 (same schema) have +-- conflicting EXCEPT clauses +CREATE PUBLICATION testpub_cursch_named_conflict + FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl), + pub_test1 EXCEPT (TABLE tbl1); +ERROR: conflicting or redundant EXCEPT clauses for schema "pub_test1" +-- fail: two CURRENT_SCHEMA mentions with conflicting EXCEPT clauses +CREATE PUBLICATION testpub_cursch_cursch_conflict + FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl), + CURRENT_SCHEMA EXCEPT (TABLE tbl1); +ERROR: conflicting or redundant EXCEPT clauses for schema "pub_test1" +RESET search_path; -- cleanup pub_test1 schema for invalidation tests ALTER PUBLICATION testpub2_forschema DROP TABLES IN SCHEMA pub_test1; DROP PUBLICATION testpub3_forschema, testpub4_forschema, testpub5_forschema, testpub6_forschema, testpub_fortable; @@ -2321,6 +2548,7 @@ DROP ROLE regress_publication_user_dummy; -- Test pg_get_publication_tables(text[], oid) function CREATE SCHEMA gpt_test_sch; CREATE TABLE gpt_test_sch.tbl_sch (id int); +CREATE TABLE gpt_test_sch.tbl_sch2 (id int); CREATE TABLE tbl_normal (id int); CREATE TABLE tbl_parent (id1 int, id2 int, id3 int) PARTITION BY RANGE (id1); CREATE TABLE tbl_part1 PARTITION OF tbl_parent FOR VALUES FROM (1) TO (10); @@ -2331,6 +2559,7 @@ CREATE PUBLICATION pub_all_no_viaroot FOR ALL TABLES WITH (publish_via_partition CREATE PUBLICATION pub_all_except FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = true); CREATE PUBLICATION pub_all_except_no_viaroot FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_schema FOR TABLES IN SCHEMA gpt_test_sch; +CREATE PUBLICATION pub_schema_except FOR TABLES IN SCHEMA gpt_test_sch EXCEPT (TABLE gpt_test_sch.tbl_sch); CREATE PUBLICATION pub_normal FOR TABLE tbl_normal WHERE (id < 10); CREATE PUBLICATION pub_part_leaf FOR TABLE tbl_part1 WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_part_parent FOR TABLE tbl_parent (id1, id2) WHERE (id1 = 10) WITH (publish_via_partition_root = true); @@ -2482,6 +2711,44 @@ SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_part1'); -- no r ---------+---------+-------+------ (0 rows) +-- test for EXCEPT clause with schema publication +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch'); -- no result (excluded) + pubname | relname | attrs | qual +---------+---------+-------+------ +(0 rows) + +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch2'); -- one row (included via schema) + pubname | relname | attrs | qual +-------------------+----------+-------+------ + pub_schema_except | tbl_sch2 | 1 | +(1 row) + +-- test for EXCEPT clause with schema publication, where the excluded root's +-- partition lives in a different schema that is separately, fully included +-- (no EXCEPT) in the same publication. The root's exclusion must cascade to +-- the partition regardless of the partition's own schema membership. +CREATE SCHEMA gpt_cross_sch1; +CREATE SCHEMA gpt_cross_sch2; +CREATE TABLE gpt_cross_sch1.croot (id int) PARTITION BY RANGE (id); +CREATE TABLE gpt_cross_sch2.cpart1 PARTITION OF gpt_cross_sch1.croot FOR VALUES FROM (1) TO (10); +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION pub_cross_schema_except FOR TABLES IN SCHEMA gpt_cross_sch1 EXCEPT (TABLE gpt_cross_sch1.croot), TABLES IN SCHEMA gpt_cross_sch2; +RESET client_min_messages; +SELECT * FROM test_gpt(ARRAY['pub_cross_schema_except'], 'gpt_cross_sch1.croot'); -- no result (excluded) + pubname | relname | attrs | qual +---------+---------+-------+------ +(0 rows) + +-- no result (excluded via cascading root exclusion, even though cpart1's own +-- schema gpt_cross_sch2 is separately, fully included with no EXCEPT) +SELECT * FROM test_gpt(ARRAY['pub_cross_schema_except'], 'gpt_cross_sch2.cpart1'); + pubname | relname | attrs | qual +---------+---------+-------+------ +(0 rows) + +DROP PUBLICATION pub_cross_schema_except; +DROP TABLE gpt_cross_sch2.cpart1, gpt_cross_sch1.croot; +DROP SCHEMA gpt_cross_sch1, gpt_cross_sch2; -- two rows with different row filter SELECT * FROM test_gpt(ARRAY['pub_all', 'pub_normal'], 'tbl_normal'); pubname | relname | attrs | qual @@ -2534,6 +2801,7 @@ DROP PUBLICATION pub_all_no_viaroot; DROP PUBLICATION pub_all_except; DROP PUBLICATION pub_all_except_no_viaroot; DROP PUBLICATION pub_schema; +DROP PUBLICATION pub_schema_except; DROP PUBLICATION pub_normal; DROP PUBLICATION pub_part_leaf; DROP PUBLICATION pub_part_parent; @@ -2542,7 +2810,9 @@ DROP PUBLICATION pub_part_parent_child; DROP VIEW gpt_test_view; DROP TABLE tbl_normal, tbl_parent, tbl_part1; DROP SCHEMA gpt_test_sch CASCADE; -NOTICE: drop cascades to table gpt_test_sch.tbl_sch +NOTICE: drop cascades to 2 other objects +DETAIL: drop cascades to table gpt_test_sch.tbl_sch +drop cascades to table gpt_test_sch.tbl_sch2 -- stage objects for pg_dump tests CREATE SCHEMA pubme CREATE TABLE t0 (c int, d int) CREATE TABLE t1 (c int); CREATE SCHEMA pubme2 CREATE TABLE t0 (c int, d int); diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index fac54b02e27..dcdc1eb5df9 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -125,6 +125,9 @@ CREATE PUBLICATION testpub_foralltables_excepttable1 FOR ALL TABLES EXCEPT (TABL \d testpub_tbl1 -- fail - first table in the EXCEPT list should use TABLE keyword CREATE PUBLICATION testpub_foralltables_excepttable2 FOR ALL TABLES EXCEPT (testpub_tbl1, testpub_tbl2); +-- fail - EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testpub_tbl3); --------------------------------------------- -- SET ALL TABLES/SEQUENCES @@ -222,7 +225,119 @@ RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Create same-named tables in public to verify unqualified EXCEPT entries +-- are qualified with the named schema, not public +CREATE TABLE testpub_nopk (foo int, bar int); +CREATE TABLE testpub_tbl_s1 (a int primary key, b text); + +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + +-- Exclude multiple tables using unqualified names; same-named tables exist in +-- public to confirm unqualified names resolve to pub_test, not public +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); + +-- Multiple schemas each with their own EXCEPT clause +CREATE PUBLICATION testpub_schema_except_multi + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_schema_except_multi + +-- fail: same schema repeated with same EXCEPT clauses +CREATE PUBLICATION testpub_schema_except_conflict + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: same schema repeated with conflicting or no EXCEPT clauses +CREATE PUBLICATION testpub_schema_except_conflict2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2), + pub_test; + +-- ALTER TABLE ... SET SCHEMA on a table excluded by a schema publication: +-- the schema-scoped exclusion is no longer meaningful once the table moves +-- out of its schema, so the exclusion is auto-removed. +CREATE PUBLICATION testpub_schema_except_setsch + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_schema_except_setsch +ALTER TABLE pub_test.testpub_tbl_s2 SET SCHEMA public; +\dRp+ testpub_schema_except_setsch +DROP PUBLICATION testpub_schema_except_setsch; +-- Restore for further tests +ALTER TABLE public.testpub_tbl_s2 SET SCHEMA pub_test; + +-- fail: table appears in both the explicit table list and the EXCEPT clause +CREATE PUBLICATION testpub_except_conflict + FOR TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: nonexistent table in EXCEPT clause +CREATE PUBLICATION testpub_except_norel + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- fail: partition cannot appear in EXCEPT clause; only root tables are allowed +CREATE TABLE pub_test.testpub_parted_s (a int) PARTITION BY LIST (a); +CREATE TABLE pub_test.testpub_part_s PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (1); +CREATE PUBLICATION testpub_except_partition + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); + +-- fail: TABLE keyword is required for the first entry in the EXCEPT clause +CREATE PUBLICATION testpub_except_nokw + FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + +-- Check that a table excluded from a schema publication is reported only as +-- excluded and not as published. +\d pub_test.testpub_nopk + +-- fail: ADD TABLE for a partition is rejected when a partition ancestor +-- is currently in the publication's EXCEPT list. +CREATE PUBLICATION testpub_except_ancestor + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ALTER PUBLICATION testpub_except_ancestor ADD TABLE pub_test.testpub_part_s; +DROP PUBLICATION testpub_except_ancestor; + +-- fail: same contradiction (explicit partition + EXCEPT-ed ancestor), but +-- given in a single statement instead of two separate ones +CREATE PUBLICATION testpub_except_ancestor_same_create + FOR TABLE pub_test.testpub_part_s, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); + +-- fail: same contradiction as above, but the partition lives in a different +-- schema (public) than its EXCEPT-ed root (pub_test) +CREATE TABLE public.testpub_part_s2 PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (2); +CREATE PUBLICATION testpub_except_ancestor_cross_schema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s), + TABLE public.testpub_part_s2; +DROP TABLE public.testpub_part_s2; + +-- Cleanup +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP TABLE pub_test.testpub_parted_s CASCADE; +DROP TABLE testpub_nopk, testpub_tbl_s1; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; + +--------------------------------------------- +-- Tests for publications with SEQUENCES +--------------------------------------------- CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; @@ -1194,6 +1309,38 @@ ALTER PUBLICATION testpub1_forschema SET TABLES IN SCHEMA pub_test1, pub_test1; ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo (a, b); ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b); +-- EXCEPT clause with CURRENT_SCHEMA: cross-schema entry must be rejected +SET search_path = pub_test1; +-- qualified name from wrong schema -> error +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.tbl1); +-- unqualified name implicitly qualified with current schema (pub_test1.tbl) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl); +RESET client_min_messages; +\dRp+ testpub_cursch_except +DROP PUBLICATION testpub_cursch_except; + +-- succeeds: CURRENT_SCHEMA and pub_test1 (same schema) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_named_same + FOR TABLES IN SCHEMA CURRENT_SCHEMA, pub_test1; +RESET client_min_messages; +\dRp+ testpub_cursch_named_same +DROP PUBLICATION testpub_cursch_named_same; + +-- fail: CURRENT_SCHEMA and pub_test1 (same schema) have +-- conflicting EXCEPT clauses +CREATE PUBLICATION testpub_cursch_named_conflict + FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl), + pub_test1 EXCEPT (TABLE tbl1); + +-- fail: two CURRENT_SCHEMA mentions with conflicting EXCEPT clauses +CREATE PUBLICATION testpub_cursch_cursch_conflict + FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl), + CURRENT_SCHEMA EXCEPT (TABLE tbl1); + +RESET search_path; + -- cleanup pub_test1 schema for invalidation tests ALTER PUBLICATION testpub2_forschema DROP TABLES IN SCHEMA pub_test1; DROP PUBLICATION testpub3_forschema, testpub4_forschema, testpub5_forschema, testpub6_forschema, testpub_fortable; @@ -1448,6 +1595,7 @@ DROP ROLE regress_publication_user_dummy; -- Test pg_get_publication_tables(text[], oid) function CREATE SCHEMA gpt_test_sch; CREATE TABLE gpt_test_sch.tbl_sch (id int); +CREATE TABLE gpt_test_sch.tbl_sch2 (id int); CREATE TABLE tbl_normal (id int); CREATE TABLE tbl_parent (id1 int, id2 int, id3 int) PARTITION BY RANGE (id1); CREATE TABLE tbl_part1 PARTITION OF tbl_parent FOR VALUES FROM (1) TO (10); @@ -1459,6 +1607,7 @@ CREATE PUBLICATION pub_all_no_viaroot FOR ALL TABLES WITH (publish_via_partition CREATE PUBLICATION pub_all_except FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = true); CREATE PUBLICATION pub_all_except_no_viaroot FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_schema FOR TABLES IN SCHEMA gpt_test_sch; +CREATE PUBLICATION pub_schema_except FOR TABLES IN SCHEMA gpt_test_sch EXCEPT (TABLE gpt_test_sch.tbl_sch); CREATE PUBLICATION pub_normal FOR TABLE tbl_normal WHERE (id < 10); CREATE PUBLICATION pub_part_leaf FOR TABLE tbl_part1 WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_part_parent FOR TABLE tbl_parent (id1, id2) WHERE (id1 = 10) WITH (publish_via_partition_root = true); @@ -1515,6 +1664,32 @@ SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'gpt_test_sch.tbl_sch SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_parent'); -- no result (excluded) SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_part1'); -- no result +-- test for EXCEPT clause with schema publication +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch'); -- no result (excluded) +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch2'); -- one row (included via schema) + +-- test for EXCEPT clause with schema publication, where the excluded root's +-- partition lives in a different schema that is separately, fully included +-- (no EXCEPT) in the same publication. The root's exclusion must cascade to +-- the partition regardless of the partition's own schema membership. +CREATE SCHEMA gpt_cross_sch1; +CREATE SCHEMA gpt_cross_sch2; +CREATE TABLE gpt_cross_sch1.croot (id int) PARTITION BY RANGE (id); +CREATE TABLE gpt_cross_sch2.cpart1 PARTITION OF gpt_cross_sch1.croot FOR VALUES FROM (1) TO (10); + +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION pub_cross_schema_except FOR TABLES IN SCHEMA gpt_cross_sch1 EXCEPT (TABLE gpt_cross_sch1.croot), TABLES IN SCHEMA gpt_cross_sch2; +RESET client_min_messages; + +SELECT * FROM test_gpt(ARRAY['pub_cross_schema_except'], 'gpt_cross_sch1.croot'); -- no result (excluded) +-- no result (excluded via cascading root exclusion, even though cpart1's own +-- schema gpt_cross_sch2 is separately, fully included with no EXCEPT) +SELECT * FROM test_gpt(ARRAY['pub_cross_schema_except'], 'gpt_cross_sch2.cpart1'); + +DROP PUBLICATION pub_cross_schema_except; +DROP TABLE gpt_cross_sch2.cpart1, gpt_cross_sch1.croot; +DROP SCHEMA gpt_cross_sch1, gpt_cross_sch2; + -- two rows with different row filter SELECT * FROM test_gpt(ARRAY['pub_all', 'pub_normal'], 'tbl_normal'); @@ -1543,6 +1718,7 @@ DROP PUBLICATION pub_all_no_viaroot; DROP PUBLICATION pub_all_except; DROP PUBLICATION pub_all_except_no_viaroot; DROP PUBLICATION pub_schema; +DROP PUBLICATION pub_schema_except; DROP PUBLICATION pub_normal; DROP PUBLICATION pub_part_leaf; DROP PUBLICATION pub_part_parent; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 43b51c8ff71..6208e98e7eb 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -24,14 +24,17 @@ my $result; sub test_except_root_partition { - my ($pubviaroot) = @_; + my ($pubviaroot, $pubsql) = @_; + $pubsql //= + "CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1)"; + $pubsql .= " WITH (publish_via_partition_root = $pubviaroot)"; # If the root partitioned table is in the EXCEPT clause, all its # partitions are excluded from publication, regardless of the # publish_via_partition_root setting. $node_publisher->safe_psql( 'postgres', qq( - CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1) WITH (publish_via_partition_root = $pubviaroot); + $pubsql; INSERT INTO root1 VALUES (1), (101); )); $node_subscriber->safe_psql('postgres', @@ -223,6 +226,206 @@ $node_subscriber->safe_psql( test_except_root_partition('false'); test_except_root_partition('true'); +# Same validation using TABLES IN SCHEMA instead of FOR ALL TABLES. +my $schema_pub = + "CREATE PUBLICATION tap_pub_part FOR TABLES IN SCHEMA public EXCEPT (TABLE public.root1)"; +test_except_root_partition('false', $schema_pub); +test_except_root_partition('true', $schema_pub); + +# ============================================ +# EXCEPT test cases for TABLES IN SCHEMA +# ============================================ + +# Create a dedicated schema with two tables: one to be published and one to be +# excluded. Also create inherited tables to verify ONLY semantics. +$node_publisher->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_published AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.tab_excluded AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.parent (a int); + CREATE TABLE sch1.child (b int) INHERITS (sch1.parent); +)); + +$node_subscriber->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_published (a int); + CREATE TABLE sch1.tab_excluded (a int); + CREATE TABLE sch1.parent (a int); + CREATE TABLE sch1.child (b int) INHERITS (sch1.parent); +)); + +# Basic test: initial sync respects EXCEPT. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_excluded)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: initial sync copies included table'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: initial sync skips excluded table'); + +# DML: only the included table should be replicated. +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (6); + INSERT INTO sch1.tab_excluded VALUES (6); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(6), + 'TABLES IN SCHEMA EXCEPT: DML on included table is replicated'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: DML on excluded table is not replicated'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Inherited tables: excluding the parent (without ONLY) also excludes the child. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.parent)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.child VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.child"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: excluding parent (without ONLY) also excludes child' +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Test that EXCEPT (TABLE ONLY parent) excludes only the parent itself, not its +# child. Truncate child first so rows from the previous test are not copied by +# the initial table sync of the next subscription. +$node_publisher->safe_psql('postgres', 'TRUNCATE sch1.child'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE sch1.child'); +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE ONLY sch1.parent)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.child VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.child"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: ONLY parent in EXCEPT does not exclude child'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Cleanup schema tables before the multi-publication section. +$node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); +$node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); + +# ============================================ +# EXCEPT test cases for TABLES IN SCHEMA with a cross-schema partition +# ============================================ + +# A partition can live in a different schema than its partitioned root. If +# the root is excluded via EXCEPT under its own schema's clause, the +# exclusion must cascade to all its partitions, even when the partition's +# own schema is separately, fully included (no EXCEPT) in the same +# publication. +$node_publisher->safe_psql( + 'postgres', qq( + CREATE SCHEMA csch1; + CREATE SCHEMA csch2; + CREATE TABLE csch1.croot(a int) PARTITION BY RANGE(a); + CREATE TABLE csch2.cpart1 PARTITION OF csch1.croot FOR VALUES FROM (0) TO (100); + INSERT INTO csch1.croot VALUES (generate_series(1,5)); +)); + +$node_subscriber->safe_psql( + 'postgres', qq( + CREATE SCHEMA csch1; + CREATE SCHEMA csch2; + CREATE TABLE csch1.croot(a int); + CREATE TABLE csch2.cpart1(a int); +)); + +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION cross_sch_pub FOR TABLES IN SCHEMA csch1 EXCEPT (TABLE csch1.croot), TABLES IN SCHEMA csch2 WITH (publish_via_partition_root = false)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION cross_sch_sub CONNECTION '$publisher_connstr' PUBLICATION cross_sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'cross_sch_sub'); + +# Baseline: the root itself, pre-populated with rows before the subscription +# was created, is excluded by its own schema's EXCEPT clause -- initial sync +# must not have copied it. +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM csch1.croot"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: cross-schema partition root is excluded by initial sync' +); + +# Regression case: the partition's own schema (csch2) is separately, fully +# included with no EXCEPT, but the root's exclusion must still cascade to it +# -- initial sync must not have copied the pre-existing rows routed into this +# partition via the root. +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM csch2.cpart1"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: cross-schema partition is excluded by initial sync via cascading root exclusion' +); + +# Insert distinct, identifiable data directly into the partition and verify +# it is not replicated either. +$node_publisher->safe_psql('postgres', + "INSERT INTO csch2.cpart1 VALUES (generate_series(1,5))"); +$node_publisher->wait_for_catchup('cross_sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM csch1.croot"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: cross-schema partition root remains excluded after DML' +); +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM csch2.cpart1"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: cross-schema partition remains excluded after DML via cascading root exclusion' +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION cross_sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION cross_sch_pub'); +$node_publisher->safe_psql('postgres', 'DROP SCHEMA csch1, csch2 CASCADE'); +$node_subscriber->safe_psql('postgres', 'DROP SCHEMA csch1, csch2 CASCADE'); + # ============================================ # Test when a subscription is subscribing to multiple publications # ============================================ @@ -254,6 +457,7 @@ $node_publisher->safe_psql( DROP PUBLICATION tap_pub2; TRUNCATE tab1; )); +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_subscriber->safe_psql('postgres', qq(TRUNCATE tab1)); # OK when a table is excluded by pub1 EXCEPT clause, but it is included by pub2 -- 2.50.1 (Apple Git-155)
v25-0002-Add-EXCEPT-support-to-ALTER-PUBLICATION-ADD-TABL.patch (application/octet-stream, 22.3K) download From e24ac087a9ca3ca0993ab68afa1a780893dbe66a Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Thu, 23 Jul 2026 12:31:51 +0530 Subject: [PATCH v25 2/4] Add EXCEPT support to ALTER PUBLICATION ADD TABLES IN SCHEMA Extend the EXCEPT clause support to allow tables to be excluded when adding a schema to a publication via ALTER PUBLICATION ... ADD. Syntax: ALTER PUBLICATION pub ADD TABLES IN SCHEMA s EXCEPT (TABLE s.t1); Since pg_dump uses ALTER PUBLICATION ... ADD, support for it is included in this patch. --- src/backend/catalog/pg_publication.c | 19 ++-- src/backend/commands/publicationcmds.c | 102 ++++++++++++++++++++-- src/bin/pg_dump/pg_dump.c | 30 ++++++- src/bin/pg_dump/t/002_pg_dump.pl | 24 +++++ src/bin/psql/tab-complete.in.c | 17 ++++ src/test/regress/expected/publication.out | 60 ++++++++++++- src/test/regress/sql/publication.sql | 45 +++++++++- src/test/subscription/t/037_except.pl | 32 +++++++ 8 files changed, 313 insertions(+), 16 deletions(-) diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index 183a3b2abff..f8b78322cfd 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -729,15 +729,18 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, * here, as CreatePublication() function invalidates all relations as part * of defining a FOR ALL TABLES publication. * - * For ALTER PUBLICATION, invalidation is needed only when adding an - * EXCEPT table to a publication already marked as ALL TABLES. For - * publications that were originally empty or defined as ALL SEQUENCES and - * are being converted to ALL TABLES, invalidation is skipped here, as - * AlterPublicationAllFlags() function invalidates all relations while - * marking the publication as ALL TABLES publication. + * For ALTER PUBLICATION, invalidation is needed when adding an EXCEPT + * table to either a FOR ALL TABLES publication (pub->alltables is true) + * or a FOR TABLES IN SCHEMA publication (is_schema_publication is true). + * The exception: when a publication is being converted to FOR ALL TABLES + * (pub->alltables is still false at this point), + * AlterPublicationAllFlags() will perform a full invalidation, so we skip + * it here. */ - inval_except_table = (alter_stmt != NULL) && pub->alltables && - (alter_stmt->for_all_tables && pri->except); + inval_except_table = (alter_stmt != NULL) && pri->except && + (pub->alltables + ? alter_stmt->for_all_tables + : is_schema_publication(pubid)); if (!pri->except || inval_except_table) { diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 3e86458ebd3..4b918c09893 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -71,6 +71,13 @@ static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok); static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); +static void AlterPublicationSchemas(AlterPublicationStmt *stmt, + HeapTuple tup, List *schemaidlist, + List *except_pubtables); +static void AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, + List *except_pubtables, + List *schemaidlist); static char defGetGeneratedColsOption(DefElem *def); static void CheckExceptNotInTableList(List *except_rels, List *explicitrelids); static void ProcessSchemaExceptTables(Oid schemaid, List *except_tables, @@ -1604,7 +1611,8 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, */ static void AlterPublicationSchemas(AlterPublicationStmt *stmt, - HeapTuple tup, List *schemaidlist) + HeapTuple tup, List *schemaidlist, + List *except_pubtables) { Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); @@ -1681,6 +1689,88 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, */ PublicationAddSchemas(pubform->oid, schemaidlist, true, stmt); } + + /* + * Increment the command counter so that is_schema_publication() in + * GetExcludedPublicationTables() can see the just-inserted schema + * rows when AlterPublicationSchemaExceptTables runs next. + */ + if (stmt->action == AP_AddObjects || stmt->action == AP_SetObjects) + CommandCounterIncrement(); + + AlterPublicationSchemaExceptTables(stmt, tup, except_pubtables, schemaidlist); +} + +/* + * Alter the EXCEPT list of a schema-level publication. + * + * Adds, removes, or replaces except-table entries in pg_publication_rel + * (rows with prexcept = true). These entries suppress publication of the + * named tables that would otherwise be covered by a FOR TABLES IN SCHEMA + * clause. + */ +static void +AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, List *except_pubtables, + List *schemaidlist) +{ + Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); + Oid pubid = pubform->oid; + + /* + * Nothing to do if no EXCEPT entries. + */ + if (!except_pubtables) + return; + + /* + * This function handles EXCEPT entries for schema-level publications + * only. For FOR ALL TABLES publications, EXCEPT entries are already + * processed by AlterPublicationTables(). + */ + if (schemaidlist == NIL && !is_schema_publication(pubid)) + return; + + /* + * Dropping a schema from a publication removes all its EXCEPT entries via + * cascade. The concept of "drop all schema tables from the publication + * EXCEPT these ones" is not supported. + */ + if (stmt->action == AP_DropObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); + + /* + * XXX EXCEPT with SET is not currently implemented. Workaround: DROP and + * re-ADD the schema with the desired EXCEPT list. + */ + if (stmt->action == AP_SetObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"), + errhint("Drop and re-add the schema with the desired EXCEPT list."))); + + if (stmt->action == AP_AddObjects) + { + List *rels; + List *explicitrelids; + + rels = OpenTableList(except_pubtables); + + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + /* + * Validate that each excluded table is not also in the explicit table + * list (which would be contradictory). + */ + CheckExceptNotInTableList(rels, explicitrelids); + + PublicationAddTables(pubid, rels, false, stmt); + + CloseTableList(rels); + } } /* @@ -1862,12 +1952,12 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) else { List *relations = NIL; - List *exceptrelations = NIL; + List *except_pubtables = NIL; List *schemaidlist = NIL; Oid pubid = pubform->oid; ObjectsInPublicationToOids(stmt->pubobjects, pstate, &relations, - &exceptrelations, &schemaidlist); + &except_pubtables, &schemaidlist); CheckAlterPublication(stmt, tup, relations, schemaidlist); @@ -1890,10 +1980,12 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) errmsg("publication \"%s\" does not exist", stmt->pubname)); - relations = list_concat(relations, exceptrelations); + if (stmt->for_all_tables) + relations = list_concat(relations, except_pubtables); + AlterPublicationTables(stmt, tup, relations, pstate->p_sourcetext, schemaidlist != NIL); - AlterPublicationSchemas(stmt, tup, schemaidlist); + AlterPublicationSchemas(stmt, tup, schemaidlist, except_pubtables); AlterPublicationAllFlags(stmt, rel, tup); } diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c index 4948e6d80c7..ecd518af02c 100644 --- a/src/bin/pg_dump/pg_dump.c +++ b/src/bin/pg_dump/pg_dump.c @@ -4973,6 +4973,7 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) PublicationInfo *pubinfo = pubsinfo->publication; PQExpBuffer query; char *tag; + bool has_except = false; /* Do nothing if not dumping schema */ if (!dopt->dumpSchema) @@ -4983,7 +4984,34 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) query = createPQExpBuffer(); appendPQExpBuffer(query, "ALTER PUBLICATION %s ", fmtId(pubinfo->dobj.name)); - appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s;\n", fmtId(schemainfo->dobj.name)); + appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s", fmtId(schemainfo->dobj.name)); + + /* + * Append EXCEPT clause for any tables that belong to this schema + * and are excluded from the publication. + */ + for (SimplePtrListCell *cell = pubinfo->except_tables.head; cell; cell = cell->next) + { + TableInfo *tbinfo = (TableInfo *) cell->ptr; + + if (strcmp(tbinfo->dobj.namespace->dobj.name, schemainfo->dobj.name) == 0) + { + if (!has_except) + { + appendPQExpBufferStr(query, " EXCEPT ("); + has_except = true; + } + else + appendPQExpBufferStr(query, ", "); + + appendPQExpBuffer(query, "TABLE ONLY %s", fmtId(tbinfo->dobj.name)); + } + } + + if (has_except) + appendPQExpBufferStr(query, ")"); + + appendPQExpBufferStr(query, ";\n"); /* * There is no point in creating drop query as the drop is done by schema diff --git a/src/bin/pg_dump/t/002_pg_dump.pl b/src/bin/pg_dump/t/002_pg_dump.pl index 9258948b583..d18b3b0d7b9 100644 --- a/src/bin/pg_dump/t/002_pg_dump.pl +++ b/src/bin/pg_dump/t/002_pg_dump.pl @@ -3283,6 +3283,30 @@ my %tests = ( like => { %full_runs, section_post_data => 1, }, }, + 'CREATE PUBLICATION pub11' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub11 FOR TABLES IN SCHEMA dump_test EXCEPT (TABLE test_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub11 WITH (publish = 'insert, update, delete, truncate');\E + .*? + \QALTER PUBLICATION pub11 ADD TABLES IN SCHEMA dump_test EXCEPT (TABLE ONLY test_table);\E + /xms, + like => { %full_runs, section_post_data => 1, }, + }, + + 'CREATE PUBLICATION pub12' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub12 FOR TABLES IN SCHEMA dump_test EXCEPT (TABLE test_table, dump_test.test_second_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub12 WITH (publish = 'insert, update, delete, truncate');\E + .*? + \QALTER PUBLICATION pub12 ADD TABLES IN SCHEMA dump_test EXCEPT (TABLE ONLY test_table, TABLE ONLY test_second_table);\E + /xms, + like => { %full_runs, section_post_data => 1, }, + }, + 'CREATE SUBSCRIPTION sub1' => { create_order => 50, create_sql => 'CREATE SUBSCRIPTION sub1 diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index 04f2b63535f..b31d5431d79 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2359,6 +2359,23 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); + /* After a single schema name in ADD context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index f8f4b187c0a..d8c833acdaa 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -650,12 +650,70 @@ CREATE PUBLICATION testpub_except_ancestor_cross_schema ERROR: partition "public.testpub_part_s2" cannot be both published and excluded DETAIL: Partition root "pub_test.testpub_parted_s" is named in the publication's EXCEPT clause for schema "pub_test". DROP TABLE public.testpub_part_s2; +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; +-- fail: non-existing table in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- fail: EXCEPT table belongs to a different schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 1: ...xcept ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.tes... + ^ +-- fail: TABLE keyword is required for the first entry in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +ERROR: syntax error at or near "testpub_nopk" +LINE 1: ...lter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_no... + ^ +-- fail: exact same table given as both explicitly published and excluded +-- in a single ALTER ... ADD +ALTER PUBLICATION testpub_alter_except + ADD TABLE pub_test.testpub_tbl_s1, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot be both published and excluded +-- fail: add explicit partition and EXCEPT ancestor, given in a +-- single ALTER ... ADD statement +ALTER PUBLICATION testpub_alter_except + ADD TABLE pub_test.testpub_part_s, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ERROR: partition "pub_test.testpub_part_s" cannot be both published and excluded +DETAIL: Partition root "pub_test.testpub_parted_s" is named in the publication's EXCEPT clause for schema "pub_test". +-- fail: partition already explicitly published, then its root is EXCEPT-ed +-- via a later, separate ALTER ... ADD +ALTER PUBLICATION testpub_alter_except ADD TABLE pub_test.testpub_part_s; +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ERROR: partition "pub_test.testpub_part_s" cannot be both published and excluded +DETAIL: Partition root "pub_test.testpub_parted_s" is named in the publication's EXCEPT clause for schema "pub_test". +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_part_s; +-- fail: root already explicitly published, then its partition is rejected +-- from EXCEPT via a later, separate ALTER ... ADD (partitions can never +-- appear in EXCEPT, independent of the root's state) +ALTER PUBLICATION testpub_alter_except ADD TABLE pub_test.testpub_parted_s; +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); +ERROR: cannot specify relation "pub_test.testpub_part_s" in the publication EXCEPT clause +DETAIL: This operation is not supported for individual partitions. +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_parted_s; +-- ADD: qualified and unqualified names; unqualified is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + "pub_test.testpub_tbl_s2" + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP TABLE pub_test.testpub_parted_s CASCADE; DROP TABLE testpub_nopk, testpub_tbl_s1; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi, testpub_alter_except; --------------------------------------------- -- Tests for publications with SEQUENCES --------------------------------------------- diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index dcdc1eb5df9..42b7c78f7fd 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -328,12 +328,55 @@ CREATE PUBLICATION testpub_except_ancestor_cross_schema TABLE public.testpub_part_s2; DROP TABLE public.testpub_part_s2; +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; + +-- fail: non-existing table in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- fail: EXCEPT table belongs to a different schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- fail: TABLE keyword is required for the first entry in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + +-- fail: exact same table given as both explicitly published and excluded +-- in a single ALTER ... ADD +ALTER PUBLICATION testpub_alter_except + ADD TABLE pub_test.testpub_tbl_s1, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: add explicit partition and EXCEPT ancestor, given in a +-- single ALTER ... ADD statement +ALTER PUBLICATION testpub_alter_except + ADD TABLE pub_test.testpub_part_s, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); + +-- fail: partition already explicitly published, then its root is EXCEPT-ed +-- via a later, separate ALTER ... ADD +ALTER PUBLICATION testpub_alter_except ADD TABLE pub_test.testpub_part_s; +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_part_s; + +-- fail: root already explicitly published, then its partition is rejected +-- from EXCEPT via a later, separate ALTER ... ADD (partitions can never +-- appear in EXCEPT, independent of the root's state) +ALTER PUBLICATION testpub_alter_except ADD TABLE pub_test.testpub_parted_s; +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_parted_s; + +-- ADD: qualified and unqualified names; unqualified is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); +\dRp+ testpub_alter_except + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP TABLE pub_test.testpub_parted_s CASCADE; DROP TABLE testpub_nopk, testpub_tbl_s1; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi, testpub_alter_except; --------------------------------------------- -- Tests for publications with SEQUENCES diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 6208e98e7eb..5af08cc067d 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -347,6 +347,38 @@ is($result, qq(5), $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); +# ============================================ +# ALTER PUBLICATION EXCEPT for TABLES IN SCHEMA +# ============================================ + +# Truncate subscriber tables to remove data accumulated from previous tests. +$node_subscriber->safe_psql('postgres', + 'TRUNCATE sch1.tab_published, sch1.tab_excluded, sch1.parent, sch1.child'); + +# ADD: add a schema with an excepted table; verify the except entry takes effect. +$node_publisher->safe_psql('postgres', "CREATE PUBLICATION sch_pub"); +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub ADD TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_excluded)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(6), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: included table synced'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + # Cleanup schema tables before the multi-publication section. $node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); $node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); -- 2.50.1 (Apple Git-155)
v25-0003-Add-EXCEPT-support-to-ALTER-PUBLICATION-SET-TABL.patch (application/octet-stream, 27.4K) download From c42045aa82d2f25a8ebc09f6ee84de0fe1cf1433 Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Thu, 18 Jun 2026 11:32:32 +0530 Subject: [PATCH v25 3/4] Add EXCEPT support to ALTER PUBLICATION SET TABLES IN SCHEMA Extend AlterPublicationExceptTables() with the AP_SetObjects case, which redefines the publication and replaces the entire EXCEPT list. Syntax: ALTER PUBLICATION pub SET TABLES IN SCHEMA s EXCEPT (TABLE t1); This patch also cleans up EXCEPT entries when a schema is dropped from the publication. --- src/backend/commands/publicationcmds.c | 178 +++++++++++++++++++--- src/bin/psql/tab-complete.in.c | 17 +++ src/test/regress/expected/publication.out | 109 +++++++++++++ src/test/regress/sql/publication.sql | 47 ++++++ src/test/subscription/t/037_except.pl | 85 +++++++++++ 5 files changed, 411 insertions(+), 25 deletions(-) diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 4b918c09893..f9f23ee0e9e 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -67,7 +67,8 @@ static void CloseTableList(List *rels); static void LockSchemaList(List *schemalist); static void PublicationAddTables(Oid pubid, List *rels, bool if_not_exists, AlterPublicationStmt *stmt); -static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok); +static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok, + bool delete_excluded); static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); @@ -1455,7 +1456,7 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, PublicationAddTables(pubid, rels, false, stmt); } else if (stmt->action == AP_DropObjects) - PublicationDropTables(pubid, rels, false); + PublicationDropTables(pubid, rels, false, false); else /* AP_SetObjects */ { List *oldrelids = NIL; @@ -1590,7 +1591,7 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, } /* And drop them. */ - PublicationDropTables(pubid, delrels, true); + PublicationDropTables(pubid, delrels, true, true); /* * Don't bother calculating the difference for adding, we'll catch and @@ -1692,8 +1693,8 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, /* * Increment the command counter so that is_schema_publication() in - * GetExcludedPublicationTables() can see the just-inserted schema - * rows when AlterPublicationSchemaExceptTables runs next. + * GetExcludedPublicationTables() can see the just-inserted schema rows + * when AlterPublicationSchemaExceptTables runs next. */ if (stmt->action == AP_AddObjects || stmt->action == AP_SetObjects) CommandCounterIncrement(); @@ -1711,16 +1712,18 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, */ static void AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, - HeapTuple tup, List *except_pubtables, - List *schemaidlist) + HeapTuple tup, List *except_pubtables, + List *schemaidlist) { Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); Oid pubid = pubform->oid; /* - * Nothing to do if no EXCEPT entries. + * Nothing to do if there are no EXCEPT entries, unless handling the SET + * command, because if the user has removed all exceptions we need to drop + * any existing ones. */ - if (!except_pubtables) + if (!except_pubtables && stmt->action != AP_SetObjects) return; /* @@ -1741,16 +1744,6 @@ AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); - /* - * XXX EXCEPT with SET is not currently implemented. Workaround: DROP and - * re-ADD the schema with the desired EXCEPT list. - */ - if (stmt->action == AP_SetObjects) - ereport(ERROR, - (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"), - errhint("Drop and re-add the schema with the desired EXCEPT list."))); - if (stmt->action == AP_AddObjects) { List *rels; @@ -1769,6 +1762,72 @@ AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, PublicationAddTables(pubid, rels, false, stmt); + CloseTableList(rels); + } + else /* AP_SetObjects */ + { + List *oldexceptrelids = NIL; + List *newexceptrelids = NIL; + List *delrelids = NIL; + List *rels; + List *explicitrelids; + + rels = OpenTableList(except_pubtables); + + /* Collect OIDs of the desired new EXCEPT list. */ + foreach_ptr(PublicationRelInfo, pri, rels) + newexceptrelids = lappend_oid(newexceptrelids, + RelationGetRelid(pri->relation)); + + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + /* Check that there is no clash between included and excluded tables. */ + CheckExceptNotInTableList(rels, explicitrelids); + + /* + * Get the current set of EXCEPT entries. Only FOR ALL TABLES and + * schema-level publications can have EXCEPT entries; for any other + * publication type oldexceptrelids stays NIL. + * + * Note: we check is_schema_publication() against the current catalog + * state (before AlterPublicationSchemas has run), so if the caller is + * doing SET TABLE t1 to convert a schema publication into a plain + * table publication, is_schema_publication() still returns true here. + * That is intentional: it lets us discover and clean up any stale + * EXCEPT entries that belong to the old schema definition. + */ + if (GetPublication(pubid)->alltables || is_schema_publication(pubid)) + oldexceptrelids = GetExcludedPublicationTables(pubid, + PUBLICATION_PART_ROOT); + + /* Build a list of old EXCEPT entries not present in the new list. */ + foreach_oid(oldrelid, oldexceptrelids) + { + if (!list_member_oid(newexceptrelids, oldrelid)) + delrelids = lappend_oid(delrelids, oldrelid); + } + + /* Drop old EXCEPT entries not present in the new list. */ + foreach_oid(relid, delrelids) + { + Oid proid; + ObjectAddress obj; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + /* Add new EXCEPT entries, skipping any already present. */ + PublicationAddTables(pubid, rels, true, stmt); + CloseTableList(rels); } } @@ -2392,33 +2451,69 @@ PublicationAddTables(Oid pubid, List *rels, bool if_not_exists, /* * Remove listed tables from the publication. + * + * delete_excluded controls how EXCEPT (prexcept=true) rows are handled: + * true - delete them silently. Used by the SET path to clear stale + * EXCEPT rows when ALTER PUBLICATION ... SET replaces or removes + * the EXCEPT clause. + * false - treat them as "not a member". Used by ALTER ... DROP TABLE: an + * EXCEPT entry is not something DROP TABLE is expected to remove. */ static void -PublicationDropTables(Oid pubid, List *rels, bool missing_ok) +PublicationDropTables(Oid pubid, List *rels, bool missing_ok, + bool delete_excluded) { ObjectAddress obj; ListCell *lc; - Oid prid; foreach(lc, rels) { PublicationRelInfo *pubrel = (PublicationRelInfo *) lfirst(lc); Relation rel = pubrel->relation; Oid relid = RelationGetRelid(rel); + HeapTuple tup; + Form_pg_publication_rel pubrelform; + Oid prid = InvalidOid; + bool is_except = false; if (pubrel->columns) ereport(ERROR, errcode(ERRCODE_SYNTAX_ERROR), errmsg("column list must not be specified in ALTER PUBLICATION ... DROP")); - prid = GetSysCacheOid2(PUBLICATIONRELMAP, Anum_pg_publication_rel_oid, - ObjectIdGetDatum(relid), - ObjectIdGetDatum(pubid)); - if (!OidIsValid(prid)) + tup = SearchSysCache2(PUBLICATIONRELMAP, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (HeapTupleIsValid(tup)) + { + pubrelform = (Form_pg_publication_rel) GETSTRUCT(tup); + is_except = pubrelform->prexcept; + prid = pubrelform->oid; + ReleaseSysCache(tup); + } + + /* + * DROP TABLE operates only on regular member rows. A missing row and + * an EXCEPT row both mean the table isn't currently published, but we + * distinguish them so the EXCEPT case can carry a hint pointing the + * user at the EXCEPT clause. The SET-cleanup caller (delete_excluded + * = true) intends to remove EXCEPT rows and so bypasses the EXCEPT + * half of this check. + */ + if (!OidIsValid(prid) || (is_except && !delete_excluded)) { if (missing_ok) continue; + if (is_except) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("cannot drop table \"%s\" from publication \"%s\"", + RelationGetQualifiedRelationName(rel), + get_publication_name(pubid, false)), + errdetail("The table is currently named in an EXCEPT clause of the publication."), + errhint("Change the EXCEPT clause using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT."))); + ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("relation \"%s\" is not part of the publication", @@ -2474,6 +2569,7 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) foreach(lc, schemas) { Oid schemaid = lfirst_oid(lc); + List *except_relids; psid = GetSysCacheOid2(PUBLICATIONNAMESPACEMAP, Anum_pg_publication_namespace_oid, @@ -2490,8 +2586,40 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) get_namespace_name(schemaid)))); } + /* + * Collect EXCEPT entries for tables belonging to this schema before + * removing the schema entry. + */ + except_relids = GetExcludedPublicationTables(pubid, PUBLICATION_PART_ROOT); + ObjectAddressSet(obj, PublicationNamespaceRelationId, psid); performDeletion(&obj, DROP_CASCADE, 0); + + /* + * Drop any prexcept rows for tables belonging to this schema. These + * rows have no pg_depend entry pointing at the + * pg_publication_namespace row, so they are not cascaded by the + * performDeletion() call above and must be cleaned up explicitly. + */ + foreach_oid(relid, except_relids) + { + Oid proid; + + if (get_rel_namespace(relid) != schemaid) + continue; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + list_free(except_relids); } } diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index b31d5431d79..77528194a27 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2376,6 +2376,23 @@ match_previous_words(int pattern_id, } else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) COMPLETE_WITH(")"); + /* After a single schema name in SET context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index d8c833acdaa..71bda2aa966 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -708,6 +708,115 @@ Except tables: "pub_test.testpub_tbl_s1" "pub_test.testpub_tbl_s2" +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s2" + +-- fail: table in EXCEPT clause also appears in the explicit table list +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot be both published and excluded +-- fail: explicit partition + EXCEPT-ed root, given in a single SET statement +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_part_s, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ERROR: partition "pub_test.testpub_part_s" cannot be both published and excluded +DETAIL: Partition root "pub_test.testpub_parted_s" is named in the publication's EXCEPT clause for schema "pub_test". +-- fail: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 1: ...xcept SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.tes... + ^ +-- SET: unqualified name in EXCEPT is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- SET without EXCEPT clears the existing except list +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + +-- SET to a different schema removes old schema's EXCEPT entries +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA public; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "public" + +-- fail: nonexistent table in EXCEPT clause (SET path) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- SET: multiple schemas each with their own EXCEPT clause +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- fail: ALTER PUBLICATION ... DROP TABLE on an excluded table is rejected +-- with an EXCEPT-specific error. +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_tbl_s1; +ERROR: cannot drop table "pub_test.testpub_tbl_s1" from publication "testpub_alter_except" +DETAIL: The table is currently named in an EXCEPT clause of the publication. +HINT: Change the EXCEPT clause using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT. +-- the EXCEPT entry is still present after the rejected DROP TABLE +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- fail: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +ERROR: EXCEPT clause is not supported with DROP in ALTER PUBLICATION +-- DROP TABLES IN SCHEMA removes associated EXCEPT entries +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "public" +Except tables: + "public.testpub_tbl1" + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 42b7c78f7fd..73598e1fb2b 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -371,6 +371,53 @@ ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_parted_s; ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); \dRp+ testpub_alter_except +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + +-- fail: table in EXCEPT clause also appears in the explicit table list +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: explicit partition + EXCEPT-ed root, given in a single SET statement +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_part_s, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); + +-- fail: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- SET: unqualified name in EXCEPT is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +\dRp+ testpub_alter_except + +-- SET without EXCEPT clears the existing except list +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + +-- SET to a different schema removes old schema's EXCEPT entries +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA public; +\dRp+ testpub_alter_except + +-- fail: nonexistent table in EXCEPT clause (SET path) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- SET: multiple schemas each with their own EXCEPT clause +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_alter_except + +-- fail: ALTER PUBLICATION ... DROP TABLE on an excluded table is rejected +-- with an EXCEPT-specific error. +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_tbl_s1; +-- the EXCEPT entry is still present after the rejected DROP TABLE +\dRp+ testpub_alter_except + +-- fail: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); + +-- DROP TABLES IN SCHEMA removes associated EXCEPT entries +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 5af08cc067d..d538bc53732 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -376,6 +376,61 @@ $result = is($result, qq(0), 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); +# SET: replace the except list; tab_excluded is now included and tab_published is excluded. +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_published)" +); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (7); + INSERT INTO sch1.tab_excluded VALUES (7); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded WHERE a = 7"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: newly included table is replicated' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published WHERE a = 7"); +is($result, qq(0), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: now-excluded table is not replicated' +); + +# SET without EXCEPT: clears the except list; both tables are now published. +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1"); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (8); + INSERT INTO sch1.tab_excluded VALUES (8); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published WHERE a = 8"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_published replicated after except list cleared' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded WHERE a = 8"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_excluded replicated after except list cleared' +); + $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); @@ -518,6 +573,36 @@ $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); +# OK when a table is excluded by a TABLES IN SCHEMA EXCEPT publication, +# but is included by another publication. +$node_publisher->safe_psql('postgres', 'TRUNCATE tab1'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE tab1'); + +$node_publisher->safe_psql( + 'postgres', qq( + CREATE PUBLICATION tap_pub1 FOR TABLES IN SCHEMA public EXCEPT (TABLE public.tab1); + CREATE PUBLICATION tap_pub2 FOR TABLE tab1; + INSERT INTO tab1 VALUES(1); +)); +$node_subscriber->psql('postgres', + "CREATE SUBSCRIPTION tap_sub CONNECTION '$publisher_connstr' PUBLICATION tap_pub1, tap_pub2" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'tap_sub'); + +$node_publisher->safe_psql('postgres', qq(INSERT INTO tab1 VALUES(2))); +$node_publisher->wait_for_catchup('tap_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT * FROM tab1 ORDER BY a"); +is( $result, qq(1 +2), + "TABLES IN SCHEMA EXCEPT: table excluded in schema pub but included by another pub is replicated" +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); + $node_publisher->stop('fast'); done_testing(); -- 2.50.1 (Apple Git-155)
v25-0004-Documentation-Patch.patch (application/octet-stream, 11.6K) download From 642c3a8eff986e8bae5fb95f79d59ca5da1a39aa Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Thu, 30 Jul 2026 10:15:42 +0530 Subject: [PATCH v25 4/4] Documentation Patch --- doc/src/sgml/logical-replication.sgml | 3 +- doc/src/sgml/ref/alter_publication.sgml | 56 +++++++++++++++++++++++- doc/src/sgml/ref/create_publication.sgml | 42 ++++++++++++++---- 3 files changed, 89 insertions(+), 12 deletions(-) diff --git a/doc/src/sgml/logical-replication.sgml b/doc/src/sgml/logical-replication.sgml index 36298cacb75..03f12986b12 100644 --- a/doc/src/sgml/logical-replication.sgml +++ b/doc/src/sgml/logical-replication.sgml @@ -117,7 +117,8 @@ or <literal>FOR ALL SEQUENCES</literal>. Unlike tables, sequences can be synchronized at any time. For more information, see <xref linkend="logical-replication-sequences"/>. When a publication is - created with <literal>FOR ALL TABLES</literal>, a table or set of tables can + created with <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal>, a table or set of tables can be explicitly excluded from publication using the <link linkend="sql-createpublication-params-for-except-table"><literal>EXCEPT</literal></link> clause. diff --git a/doc/src/sgml/ref/alter_publication.sgml b/doc/src/sgml/ref/alter_publication.sgml index d2898d2633e..6952901e260 100644 --- a/doc/src/sgml/ref/alter_publication.sgml +++ b/doc/src/sgml/ref/alter_publication.sgml @@ -31,7 +31,7 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA <replaceable class="parameter">tables_in_schema</replaceable> [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -47,6 +47,10 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <replaceable class="parameter">table_object</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] [ WHERE ( <replaceable class="parameter">expression</replaceable> ) ] +<phrase>and <replaceable class="parameter">tables_in_schema</replaceable> is:</phrase> + + { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] + <phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> TABLE <replaceable class="parameter">table_object</replaceable> [, ... ] @@ -69,6 +73,9 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r The first two variants modify which tables/schemas are part of the publication. The <literal>ADD</literal> and <literal>DROP</literal> clauses will add and remove one or more tables/schemas from the publication. + The <literal>EXCEPT</literal> clause can be used with + <literal>ADD TABLES IN SCHEMA</literal> to exclude specific tables from a + schema-level publication. </para> <para> @@ -93,7 +100,11 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r used with a publication defined with <literal>FOR TABLE</literal> or <literal>FOR TABLES IN SCHEMA</literal>, replaces the list of tables/schemas in the publication with the specified list; the existing tables or schemas - that were present in the publication will be removed. + that were present in the publication will be removed. When + <literal>SET TABLES IN SCHEMA</literal> is used with an + <literal>EXCEPT</literal> clause, the excluded tables for each schema are + replaced with the specified list; if <literal>EXCEPT</literal> is omitted + for a schema, any existing exclusions for that schema are cleared. </para> <para> @@ -210,6 +221,26 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r </listitem> </varlistentry> + <varlistentry id="sql-alterpublication-params-except"> + <term><literal>EXCEPT</literal></term> + <listitem> + <para> + When used with <literal>ADD TABLES IN SCHEMA</literal> + or <literal>SET TABLES IN SCHEMA</literal>, specifies tables to be + excluded from the publication. Each named table must belong to the + schema specified in the same <literal>TABLES IN SCHEMA</literal> clause. + Table names may be schema-qualified or unqualified; unqualified names + are implicitly qualified with the schema named in the same clause. See + <xref linkend="sql-createpublication"/> for further details on the + semantics of <literal>EXCEPT</literal>. + </para> + <para> + Dropping a table always removes it from the <literal>EXCEPT</literal> + clause. + </para> + </listitem> + </varlistentry> + <varlistentry id="sql-alterpublication-params-set"> <term><literal>SET ( <replaceable class="parameter">publication_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] )</literal></term> <listitem> @@ -300,6 +331,27 @@ ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA marketing, sales; </programlisting> </para> + <para> + Add schema <structname>sales</structname> to the publication + <structname>sales_publication</structname>, excluding the + <structname>sales.internal</structname> and + <structname>sales.drafts</structname> tables: +<programlisting> +ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA sales EXCEPT (TABLE internal, drafts); +</programlisting> + </para> + + <para> + Replace the schema list of <structname>sales_publication</structname> with + <structname>sales</structname>, excluding only + <structname>sales.drafts</structname>. All other previously excluded tables + in schema <structname>sales</structname> are no longer excluded. Any schemas + previously in <structname>sales_publication</structname> are removed: +<programlisting> +ALTER PUBLICATION sales_publication SET TABLES IN SCHEMA sales EXCEPT (TABLE drafts); +</programlisting> + </para> + <para> Add tables <structname>users</structname>, <structname>departments</structname> and schema diff --git a/doc/src/sgml/ref/create_publication.sgml b/doc/src/sgml/ref/create_publication.sgml index 35c28006f60..5b128694ad0 100644 --- a/doc/src/sgml/ref/create_publication.sgml +++ b/doc/src/sgml/ref/create_publication.sgml @@ -28,7 +28,7 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA <replaceable class="parameter">tables_in_schema</replaceable> [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -39,6 +39,10 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <replaceable class="parameter">table_object</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] [ WHERE ( <replaceable class="parameter">expression</replaceable> ) ] +<phrase>and <replaceable class="parameter">tables_in_schema</replaceable> is:</phrase> + + { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] + <phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> TABLE <replaceable class="parameter">table_object</replaceable> [, ... ] @@ -172,6 +176,8 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <para> Marks the publication as one that replicates changes for all tables in the specified list of schemas, including tables created in the future. + Tables listed in the <literal>EXCEPT</literal> clause for a given schema + are excluded from the publication. </para> <para> @@ -203,7 +209,7 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <para> Marks the publication as one that replicates changes for all tables in the database, including tables created in the future. Tables listed in - <literal>EXCEPT</literal> clause are excluded from the publication. + the <literal>EXCEPT</literal> clause are excluded from the publication. </para> </listitem> </varlistentry> @@ -228,13 +234,21 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <listitem> <para> This clause specifies a list of tables to be excluded from the - publication. + publication. It can be used with <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal>. For <literal>FOR TABLES IN + SCHEMA</literal>, the exclusion applies only to tables in the schema + associated with the <literal>EXCEPT</literal> clause. </para> <para> - Once a table is excluded, the exclusion applies to that table - regardless of its name or schema. Renaming the table or moving it to - another schema using <command>ALTER TABLE ... SET SCHEMA</command> does - not remove the exclusion. + Once a table is excluded under <literal>FOR ALL TABLES</literal>, the + exclusion applies to that table regardless of its name or schema. + Renaming the table or moving it to another schema using + <command>ALTER TABLE ... SET SCHEMA</command> does not remove the + exclusion. However, for <literal>FOR TABLES IN SCHEMA</literal>, because + the <literal>EXCEPT</literal> is schema-scoped, moving a schema-excluded + table to another schema does remove the exclusion; if the table is later + moved back, the exclusion is not restored and must be re-established + with <command>ALTER PUBLICATION</command>. </para> <para> For inherited tables, if <literal>ONLY</literal> is specified before the @@ -247,8 +261,9 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> </para> <para> For partitioned tables, only the root partitioned table may be specified - in <literal>EXCEPT</literal>. Doing so excludes the root table and - all of its partitions from replication. The optional + in <literal>EXCEPT</literal>. Excluding the root table automatically + excludes all of its partitions from replication, even those in + schemas that are otherwise included in the publication. The optional <literal>ONLY</literal> and <literal>*</literal> has no effect for partitioned tables. </para> @@ -552,6 +567,15 @@ CREATE PUBLICATION production_publication FOR TABLE users, departments, TABLES I CREATE PUBLICATION sales_publication FOR TABLES IN SCHEMA marketing, sales; </programlisting></para> + <para> + Create a publication that publishes all changes for all the tables present in + the schema <structname>sales</structname>, except + <structname>internal</structname> and <structname>drafts</structname>: +<programlisting> +CREATE PUBLICATION sales_filtered FOR TABLES IN SCHEMA sales EXCEPT (TABLE internal, drafts); +</programlisting> + </para> + <para> Create a publication that publishes all changes for table <structname>users</structname>, but replicates only columns <structname>user_id</structname> and -- 2.50.1 (Apple Git-155)
^ permalink raw reply [nested|flat] 196+ messages in thread

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-04 08:41  Nisha Moond <nisha.moond412@gmail.com>
  parent: Shlok Kyal <shlok.kyal.oss@gmail.com>
  0 siblings, 0 replies; 196+ messages in thread

From: Nisha Moond @ 2026-08-04 08:41 UTC (permalink / raw)
  To: Shlok Kyal <shlok.kyal.oss@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Peter Smith <smithpb2250@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Fri, Jul 31, 2026 at 1:18 PM Shlok Kyal <shlok.kyal.oss@gmail.com> wrote:
>
> > Attached v24 patch set.
> >
> Hi Nisha,
>
> While addressing comments for one of my patches, I took a quick look
> at patch 0004 (the documentation patch). I have a few comments:

Thanks Shlok for the review

> 1. While building documenttation, I find following error:
> /usr/bin/xmllint --nonet --path . --path . --output postgres-full.xml
> --noent --valid postgres.sgml
> /usr/bin/xsltproc --nonet --path . --path . --stringparam pg.version
> '20devel'  stylesheet.xsl postgres-full.xml
> ERROR: id attribute missing on <varlistentry> element under /book[@id
> = 'postgres']/part[@id = 'reference']/reference[@id =
> 'sql-commands']/refentry[@id =
> 'sql-alterpublication']/refsect1/variablelist
> no result for postgres-full.xml
> make: *** [Makefile:130: html-stamp] Error 10
>
> I think we need to define a id attribute here:
> +   <varlistentry>
> +    <term><literal>EXCEPT</literal></term>
> +    <listitem>
>

Fixed in v25.

> 2. Should we add 'clause' after <literal>EXCEPT</literal> ?
> +      SCHEMA</literal>, the exclusion applies only to tables in the schema
> +      associated with the <literal>EXCEPT</literal>.
>

Makes sense, updated in v25.

> 3. Maybe we can simplify the below:
> +   <structname>sales.drafts</structname>. Other than
> +   <structname>sales.drafts</structname>, any previously excluded
> tables for schema
> +   <structname>sales</structname> are no longer excluded. Any schemas
> previously in
>
> Maybe change:
> Other than <structname>sales.drafts</structname>, any previously excluded tables
> for schema <structname>sales</structname> are no longer excluded.
> to:
> All other previously excluded tables in schema <structname>sales</structname>
> are no longer excluded.
>

I'm okay with suggestion. Updated in v25.

--
Thanks,
Nisha





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-04 08:42  Nisha Moond <nisha.moond412@gmail.com>
  parent: Peter Smith <smithpb2250@gmail.com>
  0 siblings, 0 replies; 196+ messages in thread

From: Nisha Moond @ 2026-08-04 08:42 UTC (permalink / raw)
  To: Peter Smith <smithpb2250@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Fri, Jul 31, 2026 at 2:14 PM Peter Smith <smithpb2250@gmail.com> wrote:
>
> A couple of comments for v24-0001
>
> ======
> Commit message.
>
> 1.
> Extend table exclusion support in publications to allow specific
> tables to be excluded from schema-level publications using an
> EXCEPT clause in CREATE PUBLICATION.
>
> Supported syntax:
> CREATE PUBLICATION <pub> FOR TABLES IN SCHEMA s EXCEPT (TABLE t1,...);
>
> ~
>
> 1a.
> Change /<pub>/pub/
>
> ~
>
> 1b.
> Now that you are combining more patches, this commit message seemed a
> bit light on details.
>
> You might say include things like:
>
> NOTES
> - Conflicting or redundant EXCEPT clauses are not allowed
> - EXCEPT clause tables must come from the associate schema
> - psql describe commands are updated handle tables excluded from schemas
> - Excluding partitions in not allowed
> - Excluding a partition root excludes the entire partition tree, even
> tables in different schemas
> - etc.
>

Update the commit message for patch 001 with more details.

> ======
> src/backend/utils/cache/relcache.c
>
> RelationBuildPublicationDesc:
>
> 1.
> + /* Drop the publications that exclude this relation. */
> + if (exceptpuboids != NIL)
> + puboids = list_difference_oid(puboids, exceptpuboids);
> +
>
> AFAIK, there is no DROP PUBLICATION in this logic.
>
> Instead of "Drop", how about "Ignore" or "Skip" to remove any ambiguity.
>

Updated.

--
Thanks,
Nisha






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-04 10:13  shveta malik <shveta.malik@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  3 siblings, 0 replies; 196+ messages in thread

From: shveta malik @ 2026-08-04 10:13 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; shveta malik <shveta.malik@gmail.com>

On Tue, Aug 4, 2026 at 2:11 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
>
> On Fri, Jul 31, 2026 at 11:41 AM shveta malik <shveta.malik@gmail.com> wrote:
> >
> > Nisha,
> > A few comments on v24-001:
> >
> > 1)
> > + if (is_except)
> > + ereport(ERROR,
> > + (errcode(ERRCODE_DUPLICATE_OBJECT),
> > + errmsg("cannot add table \"%s\" to publication \"%s\"",
> > + RelationGetQualifiedRelationName(targetrel),
> > + pub->name),
> > + errdetail("The table is named in the publication's EXCEPT clause for
> > schema \"%s\".",
> > +    get_namespace_name(RelationGetNamespace(targetrel))),
> > + errhint("Change the EXCEPT clause using ALTER PUBLICATION ... SET
> > TABLES IN SCHEMA ... EXCEPT.")));
> > + else
> > + ereport(ERROR,
> > + (errcode(ERRCODE_DUPLICATE_OBJECT),
> > + errmsg("relation \"%s\" is already member of publication \"%s\"",
> > + RelationGetRelationName(targetrel), pub->name)));
> >
> > Does ERRCODE_INVALID_PARAMETER_VALUE suits better in 'if-block' rather
> > than ERRCODE_DUPLICATE_OBJECT?
> > See similar error you added in CheckExceptNotInTableList():
> >
> > + if (exceptrelid == explicitrelid)
> > + ereport(ERROR,
> > + errcode(ERRCODE_INVALID_PARAMETER_VALUE),
> > + errmsg("table \"%s\" cannot be both published and excluded",
> > +    RelationGetQualifiedRelationName(pri->relation)));
> >
>
> Changed to ERRCODE_INVALID_PARAMETER_VALUE in if-block.
>
> > 2)
> > +static void
> > +ProcessSchemaExceptTables(Oid schemaid, List *except_tables,
> >
> > Since we have defined most of the arguments in comment section, we can
> > add 'pstate' as well for the sake of completion.
> >
>
> Done.
>
> > 3)
> > Atop CheckExceptNotInTableList(), please add a comment indicating why
> > this funciton is still needed when we already have similar checks in
> > publication_add_relation and check_publication_add_relation.
> >
> > 4)
> > I was debugging the flow to see why 'CheckExceptNotInTableList' is
> > still needed when we have similar check in publication_add_relation().
> > My analysis:
> >
> > publication_add_relation() accepts 'if_not_exists' i.e. add the new
> > entry 'if already not present' else skip it (no error if it is a
> > duplicate addition). Most flows pass it as 'true'. The current code
> > skips raising error if if_not_exists=true and entry exists. It made
> > sense earlier, but in our implementation, I feel it should still raise
> > an error if entries are cross wired (i.e., if an exclusion is present
> > and we are trying to add it as an inclusion, or vice versa). The
> > 'if_not_exists' based 'skip logic' should only be exercised if the
> > nature of existing entity is of same kind as user is trying to add.
> > Let me know if you have different understanding.
> >
> > Based on this, I tried debugging:
> >
> > create publication pub1 for table s1.t1, tables in schema s1 except
> > (table s1.t1);
> >
> > What changes I did:
> > --I skipped CheckExceptNotInTableList() invoked from
> > CreatePublication() so that flow directly hits the immediate next call
> > PublicationAddTables for schmea's except entries.
> > --In publication_add_relation(), I made this 'if_not_exists'
> > correction (by simply making it false for debuggin purpose).
> >
> > The flow was as follows:
> >
> > --CREATE-SUb first added table s1.t1 with prexcept=false through
> > PublicationAddTables.
> >
> > --It then added Schmea to pg_pub_namespace using PublicationAddSchemas
> > and then invoked PublicationAddTables on except-table for the schema.
> > This step (against my expectation) could not find the entry added in
> > previous step (prexcept=false once) using CheckPublicationRelEntry()
> > and thus could not hit the required error. Instead it hit more
> > internal error:
> > ERROR:  duplicate key value violates unique constraint
> > "pg_publication_rel_prrelid_prpubid_index"
> >
> > So it seems the catalog change from the first step was not visible in
> > the second step. What am I missing? The rel-cache invalidation or
> > something else?
> >
> > Nisha, can you debug and analyse in this direction? Expectation is to
> > either get rid of CheckExceptNotInTableList() or to conclude that
> > CheckExceptNotInTableList() is a reasonable addition to the code.
> >
>
> CheckExceptNotInTableList() was written to handle only CREATE
> PUBLICATION ... EXCEPT.
>
> IIUC you are not seeing the catalog change because of command-counter
> MVCC, not relcache invalidation. CommandCounterIncrement() is what
> makes the changes so far visible to later lookups —
> CreatePublication() already does that once, for the new pg_publication
> row.
>
> So yes, we could add a CommandCounterIncrement() between the two
> PublicationAddTables() calls, but I don't think it gets us to a better
> place:
>   1. The error message would be misleading. The explicit tables are
> added first, so it is the later EXCEPT insertion that finds the
> existing row, and that row has prexcept = false — so we would report -
> relation "%s" is already member of publication "%s" (with a hint
> pointing at ALTER PUBLICATION ... SET) for a CREATE PUBLICATION
> statement. This one is arguable, though — we could tweak the error
> message accordingly.
>   2. It still doesn't solve the partition case. Visibility aside,
> check_publication_add_relation() only looks upwards from the relation
> being added ("is my root excluded?"). For
>      CREATE PUBLICATION p FOR TABLE part, TABLES IN SCHEMA s EXCEPT
> (TABLE root);
>   the root's EXCEPT row does not exist yet when part is inserted, and
> when root is inserted it isn't a partition, so no check runs at all.
> Catching it there would need a new downward scan over every partition
> of an excluded root,

Okay, I see your point.

> which is more work than comparing the lists we
> already have in hand.

I agree. It is expensive as well.

>
> Since CreatePublication() has every table of the statement available
> in memory, this separate function identifies the contradiction with no
> catalog lookup at all. So IMO keeping CheckExceptNotInTableList() is
> the better way; I have expanded the comment atop the function to
> explain this. Let me know your thoughts.

I will reveiw the comment. But I agree with the overall approach.

> ~~~
>
> Attached is the v25 patch set addressing all of the above, as well as
> Shlok's and Peter's comments in [1] and [2].
>
> [1] https://www.postgresql.org/message-id/CANhcyEXtX-tAMMMvsK%2Be1TUzUWT77%2BiwTbXPx-nM1Va_UjYTHg%40mail...
> [2] https://www.postgresql.org/message-id/CAHut%2BPumod7UW71WHO0GMA2qibG%2BTTsX7j5FJykAJgBwR73EdA%40mail...
>
> --
> Thanks,
> Nisha






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-05 01:18  Peter Smith <smithpb2250@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  3 siblings, 1 reply; 196+ messages in thread

From: Peter Smith @ 2026-08-05 01:18 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

Some review comments for v25*.

======

//////////
Patch v25-0001
//////////

======
Commit Message

1.
 - EXCEPT is supported only with FOR TABLES IN SCHEMA, not FOR TABLE.

~

I think you can remove this first note. It seems redundant because
it's already clear (from the supported syntax etc) that this patch has
nothing to do with FOR TABLE. Anyway, saying "EXCEPT is supported only
with FOR TABLES IN SCHEMA" ignores the already-existing functionality
of FOR ALL TABLES EXCEPT, so it could be misleading.

//////////
Patch v25-0004
//////////

1.
+  <para>
+   Replace the schema list of <structname>sales_publication</structname> with
+   <structname>sales</structname>, excluding only
+   <structname>sales.drafts</structname>. All other previously excluded tables
+   in schema <structname>sales</structname> are no longer excluded. Any schemas
+   previously in <structname>sales_publication</structname> are removed:
+<programlisting>
+ALTER PUBLICATION sales_publication SET TABLES IN SCHEMA sales EXCEPT
(TABLE drafts);
+</programlisting>
+  </para>

IMO the word "Replace" already tells it's going to overwrite
everything that may have been there previously, so the current
explanation seemed unnecessarily verbose.

SUGGESTION
Replace the schema list of <structname>sales_publication</structname>
with only schema <structname>sales</structname>, excluding only
<structname>sales.drafts</structname>.

======
Kind Regards,
Peter Smith.
Fujitsu Australia





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-05 09:00  shveta malik <shveta.malik@gmail.com>
  parent: Peter Smith <smithpb2250@gmail.com>
  0 siblings, 2 replies; 196+ messages in thread

From: shveta malik @ 2026-08-05 09:00 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; Peter Smith <smithpb2250@gmail.com>; shveta malik <shveta.malik@gmail.com>

A few comments on v25-001:

1)
We can rearrange the comment atop ProcessSchemaExceptTables() to
mention EXCEPT-clause duplicate removal first in accordance with the
code.

2)
+ * list, so that except-table validation below can check for

Just a minor tweak:
 so that the except-table validation for pub-included schemas below

3)
+ * Both checks are made here, on the lists the statement supplied, because at
+ * this point the catalog cannot answer either question:
+ *
+ * - CreatePublication() inserts the explicit tables and the EXCEPT tables in
+ *   a single command, and a row inserted by the current command is not
+ *   visible to a later lookup within that command.  So the similar checks in
+ *   publication_add_relation() and check_publication_add_relation(), which
+ *   read pg_publication_rel, find nothing to complain about.
+ *
+ * - In the partition case the excluded root's row does not exist at all yet,
+ *   and those checks only look upward from the relation being added.

Slightly confusing, the problem is that "those checks" in the second
bullet implicitly refers to the checks mentioned only in the first
bullet. Shall we say:

/*
 * Both checks are performed here, on the lists supplied by the statement,
 * because at this point the catalog cannot answer either question. The
 * corresponding checks in publication_add_relation() and
 * check_publication_add_relation() rely on pg_publication_rel entries and
 * ancestor lookups, neither of which is sufficient in the cases below:
 *
 * - CreatePublication() inserts the explicit tables and the EXCEPT tables in
 *   a single command, and rows inserted by the current command are not
 *   visible to later lookups within the same command.
 *
 * - In the partition case, the excluded root's row might not yet exist
 *   because the root may be added to the EXCEPT list later. Detecting such
 *   contradictions when adding the root to the EXCEPT clause would require
 *   traversing downward through the partition hierarchy, whereas the
 *   existing ancestor lookups only traverse upward from the relation being
 *   added.
 */


But the comment may become too long. I wonder do we even need to
mention these 2 points : 'An excluded relation...' and 'Also reject
any relation..' as the error messages in code are self-explanatory. We
can cut down on those if you agree. Also fell free to reduce above
suggested comment as you see apt.


4)
+ if (except_pubtables != NIL)
+ {
+ List    *except_rels;
+
+ except_rels = OpenTableList(except_pubtables);
+
+ /*
+ * Validate that a table is not both explicitly included and
+ * excluded by the schema's EXCEPT clause.
+ */
+ CheckExceptNotInTableList(except_rels, explicitrelids);

We can have an ASSERT to ensure explicitrelids must not be NIL here
i.e. we have not come here post first if-block (if
(stmt->for_all_tables)). This is not a possibility but it is not
vlaidated anywhere.

5)
RelationBuildPublicationDesc()
- /*
- * For a regular table or a root partitioned table, check exclusion on
- * table itself.
- */

Is this intentional to remove this comment? It still makes sense.

6)
+ /*
+ * Only the topmost root of a partition hierarchy can appear in an
+ * EXCEPT clause, so that is where exclusion has to be evaluated.
+ * ancestors is NIL for a partition with a pending DETACH
+ * CONCURRENTLY, in which case there is no root to consult.
+ */
+ if (ancestors != NIL)
+ exceptpuboids = GetRelationExcludedPublications(llast_oid(ancestors));

-
- /*
- * Only the top-most ancestor can appear in the EXCEPT clause.
- * Therefore, for a partition, exclusion must be evaluated at the
- * top-most ancestor.
- */
- exceptpuboids = GetRelationExcludedPublications(last_ancestor_relid);

Also, can we move computing exceptpuboids at its earlier place. This
will avoid showing redundant changes in patch.

thanks
Shveta






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-06 04:55  shveta malik <shveta.malik@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  1 sibling, 0 replies; 196+ messages in thread

From: shveta malik @ 2026-08-06 04:55 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; Peter Smith <smithpb2250@gmail.com>; shveta malik <shveta.malik@gmail.com>

I reviewed test changes in 037.pl today. Should we add one more test
for the case where a subscription subscribes to multiple publications,
where one publication excludes a table from the schema, and another
includes the full same schema?

thanks
Shveta






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-07 11:56  vignesh C <vignesh21@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  3 siblings, 1 reply; 196+ messages in thread

From: vignesh C @ 2026-08-07 11:56 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Peter Smith <smithpb2250@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Tue, 4 Aug 2026 at 14:11, Nisha Moond <nisha.moond412@gmail.com> wrote:
>
> Attached is the v25 patch set addressing all of the above, as well as
> Shlok's and Peter's comments in [1] and [2].

I noticed what appears to be an unexpected behavior with publications
involving inherited tables and wanted to check whether this is
intentional. The following steps reproduce the behavior:
CREATE SCHEMA s1;
CREATE SCHEMA s2;
CREATE TABLE s1.parent (a int);
CREATE TABLE s2.child (b int) INHERITS (s1.parent);

-- Create a publication excluding the parent table
CREATE PUBLICATION p FOR TABLES IN SCHEMA s1 EXCEPT (TABLE s1.parent);

The publication excludes both the parent and child tables:
postgres=# \dRp+
                                                           Publication p
     Owner      | All tables | All sequences | Inserts | Updates |
Deletes | Truncates | Generated columns | Via root | Description
----------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+-------------
 test           | f          | f             | t       | t       | t
    | t         | none              | f        |
Tables from schemas:
    "s1"
Except tables:
    "s1.parent"
    "s2.child"

Now remove the schema from the publication:
ALTER PUBLICATION p DROP TABLES IN SCHEMA s1;

After doing so, the publication still retains the child table in the
exclusion list:
postgres=# \dRp+
                                                           Publication p
     Owner      | All tables | All sequences | Inserts | Updates |
Deletes | Truncates | Generated columns | Via root | Description
----------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+-------------
 test           | f          | f             | t       | t       | t
    | t         | none              | f        |
Except tables:
    "s2.child"

My question is whether it is intentional to retain the automatically
added exclusion for s2.child after dropping all tables from schema s1
from the publication. This also appears to have implications for
pg_dump. Since the publication no longer contains any schema entries,
pg_dump generates:
CREATE PUBLICATION p WITH (publish = 'insert, update, delete, truncate');

The dumped definition does not include the retained EXCEPT (TABLE
s2.child) state, so restoring the dump would not recreate the original
publication.
Thoughts?

Regards,
Vignesh





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-07 14:21  vignesh C <vignesh21@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  3 siblings, 1 reply; 196+ messages in thread

From: vignesh C @ 2026-08-07 14:21 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Peter Smith <smithpb2250@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Tue, 4 Aug 2026 at 14:11, Nisha Moond <nisha.moond412@gmail.com> wrote:
>
> Attached is the v25 patch set addressing all of the above, as well as
> Shlok's and Peter's comments in [1] and [2].

There is another issue with pg_dump when dumping a publication created
using FOR TABLES IN SCHEMA ... EXCEPT.
CREATE SCHEMA s1;
CREATE SCHEMA s2;
CREATE TABLE s1.parent (a int);
CREATE TABLE s2.child (b int) INHERITS (s1.parent);

-- Create a publication excluding the parent table
CREATE PUBLICATION p FOR TABLES IN SCHEMA s1 EXCEPT (TABLE s1.parent);

The publication correctly excludes both the parent and its inherited child:
postgres=# \dRp+
Publication p
Owner      | All tables | All sequences | Inserts | Updates | Deletes
| Truncates | Generated columns | Via root | Description
------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+-------------
test        | f          | f             | t       | t       | t
| t         | none              | f        |
Tables from schemas:
  "s1"
Except tables:
  "s1.parent"
  "s2.child"

However, pg_dump generates the following definition:
CREATE PUBLICATION p WITH (publish = 'insert, update, delete, truncate');
ALTER PUBLICATION p OWNER TO test;
ALTER PUBLICATION p ADD TABLES IN SCHEMA s1 EXCEPT (TABLE ONLY parent);

The dumped definition excludes only the parent table and omits the
inherited child (s2.child), even though the publication excludes both
tables.
As a result, restoring the dump recreates a publication with different
semantics: s2.child becomes part of the publication after restore.
It appears that pg_dump does not preserve the complete exclusion list
for publications created using FOR TABLES IN SCHEMA ... EXCEPT when
inherited tables are involved.

Regards,
Vignesh





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-11 08:57  vignesh C <vignesh21@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  1 sibling, 2 replies; 196+ messages in thread

From: vignesh C @ 2026-08-11 08:57 UTC (permalink / raw)
  To: shveta malik <shveta.malik@gmail.com>; +Cc: Nisha Moond <nisha.moond412@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; Peter Smith <smithpb2250@gmail.com>

On Wed, 5 Aug 2026 at 14:30, shveta malik <shveta.malik@gmail.com> wrote:
>
> A few comments on v25-001:
>
> 3)
> + * Both checks are made here, on the lists the statement supplied, because at
> + * this point the catalog cannot answer either question:
> + *
> + * - CreatePublication() inserts the explicit tables and the EXCEPT tables in
> + *   a single command, and a row inserted by the current command is not
> + *   visible to a later lookup within that command.  So the similar checks in
> + *   publication_add_relation() and check_publication_add_relation(), which
> + *   read pg_publication_rel, find nothing to complain about.
> + *
> + * - In the partition case the excluded root's row does not exist at all yet,
> + *   and those checks only look upward from the relation being added.
>
> Slightly confusing, the problem is that "those checks" in the second
> bullet implicitly refers to the checks mentioned only in the first
> bullet. Shall we say:
>
> /*
>  * Both checks are performed here, on the lists supplied by the statement,
>  * because at this point the catalog cannot answer either question. The
>  * corresponding checks in publication_add_relation() and
>  * check_publication_add_relation() rely on pg_publication_rel entries and
>  * ancestor lookups, neither of which is sufficient in the cases below:
>  *
>  * - CreatePublication() inserts the explicit tables and the EXCEPT tables in
>  *   a single command, and rows inserted by the current command are not
>  *   visible to later lookups within the same command.
>  *
>  * - In the partition case, the excluded root's row might not yet exist
>  *   because the root may be added to the EXCEPT list later. Detecting such
>  *   contradictions when adding the root to the EXCEPT clause would require
>  *   traversing downward through the partition hierarchy, whereas the
>  *   existing ancestor lookups only traverse upward from the relation being
>  *   added.
>  */

Modified

>
> But the comment may become too long. I wonder do we even need to
> mention these 2 points : 'An excluded relation...' and 'Also reject
> any relation..' as the error messages in code are self-explanatory. We
> can cut down on those if you agree. Also fell free to reduce above
> suggested comment as you see apt.

I agree with you to remove this as it seemed obvious from the error message.

> 4)
> + if (except_pubtables != NIL)
> + {
> + List    *except_rels;
> +
> + except_rels = OpenTableList(except_pubtables);
> +
> + /*
> + * Validate that a table is not both explicitly included and
> + * excluded by the schema's EXCEPT clause.
> + */
> + CheckExceptNotInTableList(except_rels, explicitrelids);
>
> We can have an ASSERT to ensure explicitrelids must not be NIL here
> i.e. we have not come here post first if-block (if
> (stmt->for_all_tables)). This is not a possibility but it is not
> vlaidated anywhere.

Added an assert for this in the beginning of "else if
(!stmt->for_all_sequences)" block to validate this.

> 5)
> RelationBuildPublicationDesc()
> - /*
> - * For a regular table or a root partitioned table, check exclusion on
> - * table itself.
> - */
>
> Is this intentional to remove this comment? It still makes sense.

I felt these comments should be there now also and added it back.

Apart from these, the rest of the comments are also fixed in the v26
version attached.
Additionally Peter's comments from [1] and Shveta's comments from [2]
to include an additional test are also addressed in this version.

[1] - https://www.postgresql.org/message-id/CAHut%2BPuMvpk-R1uv9dTiiLvDGfKuYBm1KaZP8%2B5xFNzxY9h8Pg%40mail...
[2] - https://www.postgresql.org/message-id/CAJpy0uCdp%3D5q2kW2KMYJ%2B2C3SQnPSpr5gn%2Be3J6jr_V-sjuTBg%40ma...

Regards,
Vignesh

Attachments: download all (4 files, .tar.gz)

v26-0003-Add-EXCEPT-support-to-ALTER-PUBLICATION-SET-TABL.patch (application/octet-stream, 27.4K) download From e47e4b136a68b75febdab4e356656327ec426e82 Mon Sep 17 00:00:00 2001 From: Vignesh C <c_vigneshwaran@apple.com> Date: Tue, 11 Aug 2026 14:08:31 +0530 Subject: [PATCH v26 3/3] Add EXCEPT support to ALTER PUBLICATION SET TABLES IN SCHEMA Extend AlterPublicationExceptTables() with the AP_SetObjects case, which redefines the publication and replaces the entire EXCEPT list. Syntax: ALTER PUBLICATION pub SET TABLES IN SCHEMA s EXCEPT (TABLE t1); This patch also cleans up EXCEPT entries when a schema is dropped from the publication. --- src/backend/commands/publicationcmds.c | 178 +++++++++++++++++++--- src/bin/psql/tab-complete.in.c | 17 +++ src/test/regress/expected/publication.out | 109 +++++++++++++ src/test/regress/sql/publication.sql | 47 ++++++ src/test/subscription/t/037_except.pl | 85 +++++++++++ 5 files changed, 411 insertions(+), 25 deletions(-) diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 84fd2514514..65481c26d90 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -67,7 +67,8 @@ static void CloseTableList(List *rels); static void LockSchemaList(List *schemalist); static void PublicationAddTables(Oid pubid, List *rels, bool if_not_exists, AlterPublicationStmt *stmt); -static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok); +static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok, + bool delete_excluded); static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); @@ -1454,7 +1455,7 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, PublicationAddTables(pubid, rels, false, stmt); } else if (stmt->action == AP_DropObjects) - PublicationDropTables(pubid, rels, false); + PublicationDropTables(pubid, rels, false, false); else /* AP_SetObjects */ { List *oldrelids = NIL; @@ -1589,7 +1590,7 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, } /* And drop them. */ - PublicationDropTables(pubid, delrels, true); + PublicationDropTables(pubid, delrels, true, true); /* * Don't bother calculating the difference for adding, we'll catch and @@ -1691,8 +1692,8 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, /* * Increment the command counter so that is_schema_publication() in - * GetExcludedPublicationTables() can see the just-inserted schema - * rows when AlterPublicationSchemaExceptTables runs next. + * GetExcludedPublicationTables() can see the just-inserted schema rows + * when AlterPublicationSchemaExceptTables runs next. */ if (stmt->action == AP_AddObjects || stmt->action == AP_SetObjects) CommandCounterIncrement(); @@ -1710,16 +1711,18 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, */ static void AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, - HeapTuple tup, List *except_pubtables, - List *schemaidlist) + HeapTuple tup, List *except_pubtables, + List *schemaidlist) { Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); Oid pubid = pubform->oid; /* - * Nothing to do if no EXCEPT entries. + * Nothing to do if there are no EXCEPT entries, unless handling the SET + * command, because if the user has removed all exceptions we need to drop + * any existing ones. */ - if (!except_pubtables) + if (!except_pubtables && stmt->action != AP_SetObjects) return; /* @@ -1740,16 +1743,6 @@ AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); - /* - * XXX EXCEPT with SET is not currently implemented. Workaround: DROP and - * re-ADD the schema with the desired EXCEPT list. - */ - if (stmt->action == AP_SetObjects) - ereport(ERROR, - (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"), - errhint("Drop and re-add the schema with the desired EXCEPT list."))); - if (stmt->action == AP_AddObjects) { List *rels; @@ -1768,6 +1761,72 @@ AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, PublicationAddTables(pubid, rels, false, stmt); + CloseTableList(rels); + } + else /* AP_SetObjects */ + { + List *oldexceptrelids = NIL; + List *newexceptrelids = NIL; + List *delrelids = NIL; + List *rels; + List *explicitrelids; + + rels = OpenTableList(except_pubtables); + + /* Collect OIDs of the desired new EXCEPT list. */ + foreach_ptr(PublicationRelInfo, pri, rels) + newexceptrelids = lappend_oid(newexceptrelids, + RelationGetRelid(pri->relation)); + + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + /* Check that there is no clash between included and excluded tables. */ + CheckExceptNotInTableList(rels, explicitrelids); + + /* + * Get the current set of EXCEPT entries. Only FOR ALL TABLES and + * schema-level publications can have EXCEPT entries; for any other + * publication type oldexceptrelids stays NIL. + * + * Note: we check is_schema_publication() against the current catalog + * state (before AlterPublicationSchemas has run), so if the caller is + * doing SET TABLE t1 to convert a schema publication into a plain + * table publication, is_schema_publication() still returns true here. + * That is intentional: it lets us discover and clean up any stale + * EXCEPT entries that belong to the old schema definition. + */ + if (GetPublication(pubid)->alltables || is_schema_publication(pubid)) + oldexceptrelids = GetExcludedPublicationTables(pubid, + PUBLICATION_PART_ROOT); + + /* Build a list of old EXCEPT entries not present in the new list. */ + foreach_oid(oldrelid, oldexceptrelids) + { + if (!list_member_oid(newexceptrelids, oldrelid)) + delrelids = lappend_oid(delrelids, oldrelid); + } + + /* Drop old EXCEPT entries not present in the new list. */ + foreach_oid(relid, delrelids) + { + Oid proid; + ObjectAddress obj; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + /* Add new EXCEPT entries, skipping any already present. */ + PublicationAddTables(pubid, rels, true, stmt); + CloseTableList(rels); } } @@ -2391,33 +2450,69 @@ PublicationAddTables(Oid pubid, List *rels, bool if_not_exists, /* * Remove listed tables from the publication. + * + * delete_excluded controls how EXCEPT (prexcept=true) rows are handled: + * true - delete them silently. Used by the SET path to clear stale + * EXCEPT rows when ALTER PUBLICATION ... SET replaces or removes + * the EXCEPT clause. + * false - treat them as "not a member". Used by ALTER ... DROP TABLE: an + * EXCEPT entry is not something DROP TABLE is expected to remove. */ static void -PublicationDropTables(Oid pubid, List *rels, bool missing_ok) +PublicationDropTables(Oid pubid, List *rels, bool missing_ok, + bool delete_excluded) { ObjectAddress obj; ListCell *lc; - Oid prid; foreach(lc, rels) { PublicationRelInfo *pubrel = (PublicationRelInfo *) lfirst(lc); Relation rel = pubrel->relation; Oid relid = RelationGetRelid(rel); + HeapTuple tup; + Form_pg_publication_rel pubrelform; + Oid prid = InvalidOid; + bool is_except = false; if (pubrel->columns) ereport(ERROR, errcode(ERRCODE_SYNTAX_ERROR), errmsg("column list must not be specified in ALTER PUBLICATION ... DROP")); - prid = GetSysCacheOid2(PUBLICATIONRELMAP, Anum_pg_publication_rel_oid, - ObjectIdGetDatum(relid), - ObjectIdGetDatum(pubid)); - if (!OidIsValid(prid)) + tup = SearchSysCache2(PUBLICATIONRELMAP, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (HeapTupleIsValid(tup)) + { + pubrelform = (Form_pg_publication_rel) GETSTRUCT(tup); + is_except = pubrelform->prexcept; + prid = pubrelform->oid; + ReleaseSysCache(tup); + } + + /* + * DROP TABLE operates only on regular member rows. A missing row and + * an EXCEPT row both mean the table isn't currently published, but we + * distinguish them so the EXCEPT case can carry a hint pointing the + * user at the EXCEPT clause. The SET-cleanup caller (delete_excluded + * = true) intends to remove EXCEPT rows and so bypasses the EXCEPT + * half of this check. + */ + if (!OidIsValid(prid) || (is_except && !delete_excluded)) { if (missing_ok) continue; + if (is_except) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("cannot drop table \"%s\" from publication \"%s\"", + RelationGetQualifiedRelationName(rel), + get_publication_name(pubid, false)), + errdetail("The table is currently named in an EXCEPT clause of the publication."), + errhint("Change the EXCEPT clause using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT."))); + ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("relation \"%s\" is not part of the publication", @@ -2473,6 +2568,7 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) foreach(lc, schemas) { Oid schemaid = lfirst_oid(lc); + List *except_relids; psid = GetSysCacheOid2(PUBLICATIONNAMESPACEMAP, Anum_pg_publication_namespace_oid, @@ -2489,8 +2585,40 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) get_namespace_name(schemaid)))); } + /* + * Collect EXCEPT entries for tables belonging to this schema before + * removing the schema entry. + */ + except_relids = GetExcludedPublicationTables(pubid, PUBLICATION_PART_ROOT); + ObjectAddressSet(obj, PublicationNamespaceRelationId, psid); performDeletion(&obj, DROP_CASCADE, 0); + + /* + * Drop any prexcept rows for tables belonging to this schema. These + * rows have no pg_depend entry pointing at the + * pg_publication_namespace row, so they are not cascaded by the + * performDeletion() call above and must be cleaned up explicitly. + */ + foreach_oid(relid, except_relids) + { + Oid proid; + + if (get_rel_namespace(relid) != schemaid) + continue; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + list_free(except_relids); } } diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index 6d857865d6b..d7a083ea871 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2376,6 +2376,23 @@ match_previous_words(int pattern_id, } else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) COMPLETE_WITH(")"); + /* After a single schema name in SET context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index c5e95491a8a..fd334d24c81 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -708,6 +708,115 @@ Except tables: "pub_test.testpub_tbl_s1" "pub_test.testpub_tbl_s2" +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s2" + +-- fail: table in EXCEPT clause also appears in the explicit table list +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot be both published and excluded +-- fail: explicit partition + EXCEPT-ed root, given in a single SET statement +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_part_s, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ERROR: partition "pub_test.testpub_part_s" cannot be both published and excluded +DETAIL: Partition root "pub_test.testpub_parted_s" is named in the publication's EXCEPT clause for schema "pub_test". +-- fail: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 1: ...xcept SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.tes... + ^ +-- SET: unqualified name in EXCEPT is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- SET without EXCEPT clears the existing except list +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + +-- SET to a different schema removes old schema's EXCEPT entries +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA public; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "public" + +-- fail: nonexistent table in EXCEPT clause (SET path) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- SET: multiple schemas each with their own EXCEPT clause +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- fail: ALTER PUBLICATION ... DROP TABLE on an excluded table is rejected +-- with an EXCEPT-specific error. +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_tbl_s1; +ERROR: cannot drop table "pub_test.testpub_tbl_s1" from publication "testpub_alter_except" +DETAIL: The table is currently named in an EXCEPT clause of the publication. +HINT: Change the EXCEPT clause using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT. +-- the EXCEPT entry is still present after the rejected DROP TABLE +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- fail: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +ERROR: EXCEPT clause is not supported with DROP in ALTER PUBLICATION +-- DROP TABLES IN SCHEMA removes associated EXCEPT entries +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "public" +Except tables: + "public.testpub_tbl1" + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 42b7c78f7fd..73598e1fb2b 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -371,6 +371,53 @@ ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_parted_s; ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); \dRp+ testpub_alter_except +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + +-- fail: table in EXCEPT clause also appears in the explicit table list +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: explicit partition + EXCEPT-ed root, given in a single SET statement +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_part_s, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); + +-- fail: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- SET: unqualified name in EXCEPT is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +\dRp+ testpub_alter_except + +-- SET without EXCEPT clears the existing except list +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + +-- SET to a different schema removes old schema's EXCEPT entries +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA public; +\dRp+ testpub_alter_except + +-- fail: nonexistent table in EXCEPT clause (SET path) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- SET: multiple schemas each with their own EXCEPT clause +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_alter_except + +-- fail: ALTER PUBLICATION ... DROP TABLE on an excluded table is rejected +-- with an EXCEPT-specific error. +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_tbl_s1; +-- the EXCEPT entry is still present after the rejected DROP TABLE +\dRp+ testpub_alter_except + +-- fail: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); + +-- DROP TABLES IN SCHEMA removes associated EXCEPT entries +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index ed931d0d970..f981bcd0003 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -376,6 +376,61 @@ $result = is($result, qq(0), 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); +# SET: replace the except list; tab_excluded is now included and tab_published is excluded. +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_published)" +); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (7); + INSERT INTO sch1.tab_excluded VALUES (7); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded WHERE a = 7"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: newly included table is replicated' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published WHERE a = 7"); +is($result, qq(0), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: now-excluded table is not replicated' +); + +# SET without EXCEPT: clears the except list; both tables are now published. +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1"); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (8); + INSERT INTO sch1.tab_excluded VALUES (8); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published WHERE a = 8"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_published replicated after except list cleared' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded WHERE a = 8"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_excluded replicated after except list cleared' +); + $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); @@ -571,6 +626,36 @@ $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub_sch_without_exc $node_publisher->safe_psql('postgres', 'DROP SCHEMA msch CASCADE'); $node_subscriber->safe_psql('postgres', 'DROP SCHEMA msch CASCADE'); +# OK when a table is excluded by a TABLES IN SCHEMA EXCEPT publication, +# but is included by another publication. +$node_publisher->safe_psql('postgres', 'TRUNCATE tab1'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE tab1'); + +$node_publisher->safe_psql( + 'postgres', qq( + CREATE PUBLICATION tap_pub1 FOR TABLES IN SCHEMA public EXCEPT (TABLE public.tab1); + CREATE PUBLICATION tap_pub2 FOR TABLE tab1; + INSERT INTO tab1 VALUES(1); +)); +$node_subscriber->psql('postgres', + "CREATE SUBSCRIPTION tap_sub CONNECTION '$publisher_connstr' PUBLICATION tap_pub1, tap_pub2" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'tap_sub'); + +$node_publisher->safe_psql('postgres', qq(INSERT INTO tab1 VALUES(2))); +$node_publisher->wait_for_catchup('tap_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT * FROM tab1 ORDER BY a"); +is( $result, qq(1 +2), + "TABLES IN SCHEMA EXCEPT: table excluded in schema pub but included by another pub is replicated" +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); + $node_publisher->stop('fast'); done_testing(); -- 2.55.0
v26-0001-Support-EXCEPT-clause-for-schema-level-publicati.patch (application/octet-stream, 87.7K) download From 8be4d5a0d9e89c2c3ec478331f5af7e371d48a7c Mon Sep 17 00:00:00 2001 From: Vignesh C <c_vigneshwaran@apple.com> Date: Mon, 10 Aug 2026 21:22:15 +0530 Subject: [PATCH v26 1/3] Support EXCEPT clause for schema-level publications Extend table exclusion support in publications to allow specific tables to be excluded from schema-level publications using an EXCEPT clause in CREATE PUBLICATION. Supported syntax: CREATE PUBLICATION pub FOR TABLES IN SCHEMA s EXCEPT (TABLE t1,...); This reuses the existing opt_pub_except_clause grammar and stores excluded tables as pg_publication_rel entries with prexcept = true, requiring no catalog changes. NOTES - Each EXCEPT clause applies only to its own schema; cross-schema references are rejected. - A schema may appear only once with an EXCEPT clause. - A table cannot be both explicitly published and excluded in the same statement. - Only partition roots may be excluded. Excluding a root excludes the entire partition tree, including partitions in other published schemas. Individual partitions cannot be added while their root is excluded, and ATTACH PARTITION is rejected if the attached table is excluded. - ALTER TABLE ... SET SCHEMA removes schema-scoped exclusions, matching existing schema-publication behavior. - psql describe output and tab completion are updated to support the new syntax. --- src/backend/catalog/pg_publication.c | 237 ++++++++++++++--- src/backend/commands/publicationcmds.c | 254 +++++++++++++++++- src/backend/commands/tablecmds.c | 24 +- src/backend/parser/gram.y | 27 +- src/backend/replication/pgoutput/pgoutput.c | 37 ++- src/backend/utils/cache/relcache.c | 26 +- src/bin/psql/describe.c | 44 +++- src/bin/psql/tab-complete.in.c | 35 ++- src/include/catalog/pg_publication.h | 1 + src/include/commands/publicationcmds.h | 2 + src/include/nodes/parsenodes.h | 2 + src/test/regress/expected/publication.out | 278 +++++++++++++++++++- src/test/regress/sql/publication.sql | 178 ++++++++++++- src/test/subscription/t/037_except.pl | 261 +++++++++++++++++- 14 files changed, 1319 insertions(+), 87 deletions(-) diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index 12af7d15536..9d8824f92e4 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -54,7 +54,7 @@ typedef struct * error if not. */ static void -check_publication_add_relation(PublicationRelInfo *pri) +check_publication_add_relation(PublicationRelInfo *pri, Oid pubid) { Relation targetrel = pri->relation; const char *relname; @@ -71,12 +71,51 @@ check_publication_add_relation(PublicationRelInfo *pri) errormsg = gettext_noop("cannot add relation \"%s\" to publication"); } - /* If in EXCEPT clause, must be root partitioned table */ - if (pri->except && targetrel->rd_rel->relispartition) - ereport(ERROR, - (errcode(ERRCODE_INVALID_PARAMETER_VALUE), - errmsg(errormsg, relname), - errdetail("This operation is not supported for individual partitions."))); + /* + * A partition cannot be added to a publication if its partition root is + * excluded by the publication. We follow the rule that excluding a + * partition root means that the entire partition tree is excluded. Thus, + * check whether the root is in the EXCEPT clause and reject adding the + * individual partition to the publication. + */ + if (targetrel->rd_rel->relispartition) + { + List *ancestors; + + if (pri->except) + { + /* If in EXCEPT clause, must be root partitioned table */ + ereport(ERROR, + (errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg(errormsg, relname), + errdetail("This operation is not supported for individual partitions."))); + } + + /* + * ancestors is NIL for a partition with a pending DETACH + * CONCURRENTLY, in which case there is no root to check. + */ + ancestors = get_partition_ancestors(RelationGetRelid(targetrel)); + if (ancestors != NIL) + { + Oid root = llast_oid(ancestors); + bool root_except; + + if (CheckPublicationRelEntry(pubid, root, &root_except) && root_except) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("cannot add partition \"%s\" to publication \"%s\"", + RelationGetQualifiedRelationName(targetrel), + get_publication_name(pubid, false)), + errdetail("Partition root \"%s\" is named in the publication's EXCEPT clause for schema \"%s\".", + quote_qualified_identifier(get_namespace_name(get_rel_namespace(root)), + get_rel_name(root)), + get_namespace_name(get_rel_namespace(root))), + errhint("Change the EXCEPT clause using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT.")); + } + + list_free(ancestors); + } /* Must be a regular or partitioned table */ if (RelationGetForm(targetrel)->relkind != RELKIND_RELATION && @@ -320,8 +359,7 @@ is_schema_publication(Oid pubid) } /* - * Returns true if the publication has explicitly included relation (i.e., - * not marked as EXCEPT). + * Returns true if the publication has a FOR TABLE clause. */ bool is_table_publication(Oid pubid) @@ -341,19 +379,23 @@ is_table_publication(Oid pubid) scan = systable_beginscan(pubrelsrel, PublicationRelPrpubidIndexId, true, NULL, 1, &scankey); - tup = systable_getnext(scan); - if (HeapTupleIsValid(tup)) - { - Form_pg_publication_rel pubrel; - pubrel = (Form_pg_publication_rel) GETSTRUCT(tup); - - /* - * For any publication, pg_publication_rel contains either only EXCEPT - * entries or only explicitly included tables. Therefore, examining - * the first tuple is sufficient to determine table inclusion. - */ - result = !pubrel->prexcept; + /* + * A publication can have both explicitly included (prexcept = false) and + * EXCEPT (prexcept = true) rows for the same pubid. For example: + * + * CREATE PUBLICATION pub1 FOR TABLE s1.t1, TABLES IN SCHEMA s2 EXCEPT + * (TABLE s2.t1); + * + * Scan until we find an explicitly included row. + */ + while (HeapTupleIsValid(tup = systable_getnext(scan))) + { + if (!((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept) + { + result = true; + break; + } } systable_endscan(scan); @@ -362,6 +404,27 @@ is_table_publication(Oid pubid) return result; } +/* + * Check whether a pg_publication_rel row exists for (pubid, relid); if so, + * set *is_except to its prexcept flag. + */ +bool +CheckPublicationRelEntry(Oid pubid, Oid relid, bool *is_except) +{ + HeapTuple tup; + + tup = SearchSysCache2(PUBLICATIONRELMAP, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (!HeapTupleIsValid(tup)) + return false; + + *is_except = ((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept; + ReleaseSysCache(tup); + + return true; +} + /* * Returns true if the relation has column list associated with the * publication, false otherwise. @@ -457,11 +520,26 @@ GetPubPartitionOptionRelations(List *result, PublicationPartOpt pub_partopt, * ancestor is at the end of the list. */ Oid -GetTopMostAncestorInPublication(Oid puboid, List *ancestors, int *ancestor_level) +GetTopMostAncestorInPublication(Oid puboid, List *ancestors, + int *ancestor_level) { ListCell *lc; Oid topmost_relid = InvalidOid; int level = 0; + bool root_except; + + if (ancestors == NIL) + return InvalidOid; + + /* + * If the partition root is excluded from this publication via an EXCEPT + * clause, the partition is not published through this publication, so + * return InvalidOid. Since only partition roots can appear in an EXCEPT + * clause, the root is the only ancestor worth a catalog lookup. + */ + if (CheckPublicationRelEntry(puboid, llast_oid(ancestors), &root_except) && + root_except) + return InvalidOid; /* * Find the "topmost" ancestor that is in this publication. @@ -548,6 +626,7 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, List *relids = NIL; int i; bool inval_except_table; + bool is_except; rel = table_open(PublicationRelRelationId, RowExclusiveLock); @@ -556,21 +635,30 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, * duplicates, it's here just to provide nicer error message in common * case. The real protection is the unique key on the catalog. */ - if (SearchSysCacheExists2(PUBLICATIONRELMAP, ObjectIdGetDatum(relid), - ObjectIdGetDatum(pubid))) + if (CheckPublicationRelEntry(pubid, relid, &is_except)) { table_close(rel, RowExclusiveLock); if (if_not_exists) return InvalidObjectAddress; - ereport(ERROR, - (errcode(ERRCODE_DUPLICATE_OBJECT), - errmsg("relation \"%s\" is already a member of publication \"%s\"", - RelationGetRelationName(targetrel), pub->name))); + if (is_except) + ereport(ERROR, + (errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("cannot add table \"%s\" to publication \"%s\"", + RelationGetQualifiedRelationName(targetrel), + pub->name), + errdetail("The table is named in the publication's EXCEPT clause for schema \"%s\".", + get_namespace_name(RelationGetNamespace(targetrel))), + errhint("Change the EXCEPT clause using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT."))); + else + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("relation \"%s\" is already a member of publication \"%s\"", + RelationGetRelationName(targetrel), pub->name))); } - check_publication_add_relation(pri); + check_publication_add_relation(pri, pubid); /* Validate and translate column names into a Bitmapset of attnums. */ attnums = pub_collist_validate(pri->relation, pri->columns); @@ -996,12 +1084,13 @@ GetIncludedPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) * Gets list of table oids that were specified in the EXCEPT clause for a * publication. * - * This should only be used FOR ALL TABLES publications. + * This is used for FOR ALL TABLES and FOR TABLES IN SCHEMA publications, + * both of which support EXCEPT TABLE. */ List * GetExcludedPublicationTables(Oid pubid, PublicationPartOpt pub_partopt) { - Assert(GetPublication(pubid)->alltables); + Assert(GetPublication(pubid)->alltables || is_schema_publication(pubid)); return get_publication_relations(pubid, pub_partopt, true); } @@ -1246,22 +1335,63 @@ GetSchemaPublicationRelations(Oid schemaid, PublicationPartOpt pub_partopt) /* * Gets the list of all relations published by FOR TABLES IN SCHEMA - * publication. + * publication, excluding any tables listed in EXCEPT clauses. */ List * GetAllSchemaPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) { List *result = NIL; List *pubschemalist = GetPublicationSchemas(pubid); + List *except_relids = NIL; ListCell *cell; + /* get the list of tables excluded via EXCEPT TABLE for this publication */ + if (pubschemalist != NIL) + except_relids = GetExcludedPublicationTables(pubid, pub_partopt); + foreach(cell, pubschemalist) { Oid schemaid = lfirst_oid(cell); List *schemaRels = NIL; schemaRels = GetSchemaPublicationRelations(schemaid, pub_partopt); - result = list_concat(result, schemaRels); + + if (except_relids != NIL) + { + /* filter out any tables that appear in the EXCEPT list */ + foreach_oid(relid, schemaRels) + { + bool excluded = list_member_oid(except_relids, relid); + + /* + * A partition whose root is excluded from the publication is + * also excluded, even if the partition itself lives in a + * different (included) schema. Only the topmost root of a + * partition hierarchy can ever appear in EXCEPT (see + * check_publication_add_relation()), so it's enough to check + * the last element of the ancestors list, rather than walking + * the whole chain. + */ + if (!excluded && get_rel_relispartition(relid)) + { + List *ancestors = get_partition_ancestors(relid); + + if (ancestors != NIL) + { + excluded = list_member_oid(except_relids, + llast_oid(ancestors)); + list_free(ancestors); + } + } + + if (!excluded) + result = lappend_oid(result, relid); + } + + list_free(schemaRels); + } + else + result = list_concat(result, schemaRels); } return result; @@ -1338,6 +1468,7 @@ is_table_publishable_in_publication(Oid relid, Publication *pub) { bool relispartition; List *ancestors = NIL; + bool is_except; /* * For non-pubviaroot publications, a partitioned table is never the @@ -1385,6 +1516,10 @@ is_table_publishable_in_publication(Oid relid, Publication *pub) */ /* + * If the partition root is excluded via the EXCEPT clause, the partition + * is never considered to be published through this publication. Check + * this before checking whether an ancestor is published. + * * If an ancestor is published, the partition's status depends on * publish_via_partition_root value. * @@ -1394,20 +1529,38 @@ is_table_publishable_in_publication(Oid relid, Publication *pub) * If it's false, the partition is covered by its ancestor's presence in * the publication, it should be included (return true). */ - if (relispartition && - OidIsValid(GetTopMostAncestorInPublication(pub->oid, ancestors, NULL))) - return !pub->pubviaroot; + if (relispartition) + { + /* + * ancestors can be NIL for a partition whose DETACH ... CONCURRENTLY + * is pending, in which case there is no ancestor to check. + */ + if (ancestors != NIL && + CheckPublicationRelEntry(pub->oid, llast_oid(ancestors), &is_except) && + is_except) + return false; + + if (OidIsValid(GetTopMostAncestorInPublication(pub->oid, ancestors, NULL))) + return !pub->pubviaroot; + } /* * Check whether the table is explicitly published via pg_publication_rel * or pg_publication_namespace. + * + * A pg_publication_rel row with prexcept=true means the table is + * explicitly excluded via EXCEPT and must not be reported as published, + * even if its schema is otherwise included. A row with prexcept=false + * means it is explicitly included. If no pg_publication_rel row exists, + * the table is published iff its schema appears in + * pg_publication_namespace. */ - return (SearchSysCacheExists2(PUBLICATIONRELMAP, - ObjectIdGetDatum(relid), - ObjectIdGetDatum(pub->oid)) || - SearchSysCacheExists2(PUBLICATIONNAMESPACEMAP, - ObjectIdGetDatum(get_rel_namespace(relid)), - ObjectIdGetDatum(pub->oid))); + if (CheckPublicationRelEntry(pub->oid, relid, &is_except)) + return !is_except; + else + return SearchSysCacheExists2(PUBLICATIONNAMESPACEMAP, + ObjectIdGetDatum(get_rel_namespace(relid)), + ObjectIdGetDatum(pub->oid)); } /* diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 440adb356ad..8c39950bcda 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -22,6 +22,7 @@ #include "catalog/namespace.h" #include "catalog/objectaccess.h" #include "catalog/objectaddress.h" +#include "catalog/partition.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" #include "catalog/pg_namespace.h" @@ -71,6 +72,11 @@ static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); static char defGetGeneratedColsOption(DefElem *def); +static void CheckExceptNotInTableList(List *except_rels, List *explicitrelids); +static void ProcessSchemaExceptTables(Oid schemaid, List *except_tables, + ParseState *pstate, List **schemas, + List **schemas_with_except, + List **except_pubtables); static void @@ -175,16 +181,87 @@ parse_publication_options(ParseState *pstate, } } +/* + * Also rejects a schema being mentioned more than once with an EXCEPT + * clause, even if the EXCEPT clauses are identical — much like + * OpenTableList() rejects "FOR TABLE t1(a), t1(a)" despite the column + * lists matching. A schema can still be mentioned multiple times, just + * not more than once with EXCEPT. + * + * Qualify unqualified EXCEPT table names with the given schema (rejecting + * any explicitly qualified with a different schema), and append them to + * *except_pubtables. + * + * schemaid: OID of the schema for this TABLES IN SCHEMA mention. + * except_tables: the EXCEPT list (or NIL) attached to this mention. + * pstate: parse state of the statement, used to report the error position of + * an offending EXCEPT entry. + * *schemas: accumulates all schema OIDs seen so far in this statement. + * *schemas_with_except: This is a subset of *schemas. Tracks which of + * the seen schemas of this statement had an EXCEPT clause. + * *except_pubtables: accumulates the (now schema-qualified) EXCEPT table + * entries across the whole statement. + */ +static void +ProcessSchemaExceptTables(Oid schemaid, List *except_tables, + ParseState *pstate, List **schemas, + List **schemas_with_except, List **except_pubtables) +{ + char *schema_name = get_namespace_name(schemaid); + bool schema_has_except = (except_tables != NIL); + + /* + * A repeating schema is only a problem if this mention has EXCEPT, or an + * earlier mention of the same schema did. + */ + if (list_member_oid(*schemas, schemaid)) + { + if (schema_has_except || + list_member_oid(*schemas_with_except, schemaid)) + ereport(ERROR, + errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("conflicting or redundant EXCEPT clauses for schema \"%s\"", + schema_name)); + } + + if (schema_has_except) + *schemas_with_except = lappend_oid(*schemas_with_except, schemaid); + + /* Filter out duplicates if the user specifies "sch1, sch1" */ + *schemas = list_append_unique_oid(*schemas, schemaid); + + if (!schema_has_except) + return; + + foreach_ptr(PublicationObjSpec, eobj, except_tables) + { + RangeVar *relation = eobj->pubtable->relation; + + if (relation->schemaname == NULL) + relation->schemaname = schema_name; + else if (strcmp(relation->schemaname, schema_name) != 0) + ereport(ERROR, + errcode(ERRCODE_INVALID_OBJECT_DEFINITION), + errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", + quote_qualified_identifier(relation->schemaname, relation->relname), + schema_name), + parser_errposition(pstate, eobj->location)); + + *except_pubtables = lappend(*except_pubtables, eobj->pubtable); + } +} + /* * Convert the PublicationObjSpecType list into schema oid list and * PublicationTable list. */ static void ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, - List **rels, List **exceptrels, List **schemas) + List **rels, List **except_pubtables, List **schemas) { ListCell *cell; PublicationObjSpec *pubobj; + List *schemas_with_except = NIL; if (!pubobjspec_list) return; @@ -200,7 +277,7 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, { case PUBLICATIONOBJ_EXCEPT_TABLE: pubobj->pubtable->except = true; - *exceptrels = lappend(*exceptrels, pubobj->pubtable); + *except_pubtables = lappend(*except_pubtables, pubobj->pubtable); break; case PUBLICATIONOBJ_TABLE: pubobj->pubtable->except = false; @@ -209,8 +286,10 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, case PUBLICATIONOBJ_TABLES_IN_SCHEMA: schemaid = get_namespace_oid(pubobj->name, false); - /* Filter out duplicates if user specifies "sch1, sch1" */ - *schemas = list_append_unique_oid(*schemas, schemaid); + ProcessSchemaExceptTables(schemaid, pubobj->except_tables, + pstate, schemas, + &schemas_with_except, + except_pubtables); break; case PUBLICATIONOBJ_TABLES_IN_CUR_SCHEMA: search_path = fetch_search_path(false); @@ -222,8 +301,10 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, schemaid = linitial_oid(search_path); list_free(search_path); - /* Filter out duplicates if user specifies "sch1, sch1" */ - *schemas = list_append_unique_oid(*schemas, schemaid); + ProcessSchemaExceptTables(schemaid, pubobj->except_tables, + pstate, schemas, + &schemas_with_except, + except_pubtables); break; default: /* shouldn't happen */ @@ -770,6 +851,68 @@ TransformPubWhereClauses(List *tables, const char *queryString, } } +/* + * Check that a table is not both excluded and published in the same DDL. + * + * Both checks are performed here, on the lists supplied by the statement, + * because at this point the catalog cannot answer either question. The + * corresponding checks in publication_add_relation() and + * check_publication_add_relation() rely on pg_publication_rel entries and + * ancestor lookups, neither of which is sufficient in the cases below: + * + * - CreatePublication() inserts the explicit tables and the EXCEPT tables in + * a single command, and rows inserted by the current command are not + * visible to later lookups within the same command. + * + * - In the partition case, the excluded root's row might not yet exist + * because the root may be added to the EXCEPT list later. Detecting such + * contradictions when adding the root to the EXCEPT clause would require + * traversing downward through the partition hierarchy, whereas the + * existing ancestor lookups only traverse upward from the relation being + * added. + */ +static void +CheckExceptNotInTableList(List *except_rels, List *explicitrelids) +{ + foreach_oid(explicitrelid, explicitrelids) + { + Oid root = InvalidOid; + + if (get_rel_relispartition(explicitrelid)) + { + List *ancestors = get_partition_ancestors(explicitrelid); + + /* + * ancestors is NIL for a partition with a pending DETACH + * CONCURRENTLY. + */ + if (ancestors != NIL) + root = llast_oid(ancestors); + list_free(ancestors); + } + + foreach_ptr(PublicationRelInfo, pri, except_rels) + { + Oid exceptrelid = RelationGetRelid(pri->relation); + + if (exceptrelid == explicitrelid) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" cannot be both published and excluded", + RelationGetQualifiedRelationName(pri->relation))); + + if (OidIsValid(root) && exceptrelid == root) + ereport(ERROR, + (errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("partition \"%s\" cannot be both published and excluded", + quote_qualified_identifier(get_namespace_name(get_rel_namespace(explicitrelid)), + get_rel_name(explicitrelid))), + errdetail("Partition root \"%s\" is named in the publication's EXCEPT clause for schema \"%s\".", + RelationGetQualifiedRelationName(pri->relation), + get_namespace_name(RelationGetNamespace(pri->relation))))); + } + } +} /* * Given a list of tables that are going to be added to a publication, @@ -849,7 +992,7 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) char publish_generated_columns; AclResult aclresult; List *relations = NIL; - List *exceptrelations = NIL; + List *except_pubtables = NIL; List *schemaidlist = NIL; /* must have CREATE privilege on database */ @@ -936,16 +1079,16 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) /* Associate objects with the publication. */ ObjectsInPublicationToOids(stmt->pubobjects, pstate, &relations, - &exceptrelations, &schemaidlist); + &except_pubtables, &schemaidlist); if (stmt->for_all_tables) { /* Process EXCEPT table list */ - if (exceptrelations != NIL) + if (except_pubtables != NIL) { List *rels; - rels = OpenTableList(exceptrelations); + rels = OpenTableList(except_pubtables); PublicationAddTables(puboid, rels, true, NULL); CloseTableList(rels); } @@ -959,6 +1102,11 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) } else if (!stmt->for_all_sequences) { + List *explicitrelids = NIL; + + /* EXCEPT tables here always belong to a schema in schemaidlist */ + Assert(except_pubtables == NIL || schemaidlist != NIL); + /* FOR TABLES IN SCHEMA requires superuser */ if (schemaidlist != NIL && !superuser()) ereport(ERROR, @@ -978,6 +1126,20 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) publish_via_partition_root); PublicationAddTables(puboid, rels, true, NULL); + + /* + * Collect explicit table OIDs now, before we close the relation + * list, so that the except-table validation for pub-included + * schemas below can check for contradictions without relying on a + * catalog scan that might not yet see the just-inserted rows. + */ + if (except_pubtables != NIL) + { + foreach_ptr(PublicationRelInfo, pri, rels) + explicitrelids = lappend_oid(explicitrelids, + RelationGetRelid(pri->relation)); + } + CloseTableList(rels); } @@ -989,6 +1151,22 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) */ LockSchemaList(schemaidlist); PublicationAddSchemas(puboid, schemaidlist, true, NULL); + + if (except_pubtables != NIL) + { + List *except_rels; + + except_rels = OpenTableList(except_pubtables); + + /* + * Validate that a table is not both explicitly included and + * excluded by the schema's EXCEPT clause. + */ + CheckExceptNotInTableList(except_rels, explicitrelids); + + PublicationAddTables(puboid, except_rels, true, NULL); + CloseTableList(except_rels); + } } } @@ -1829,6 +2007,62 @@ RemovePublicationSchemaById(Oid psoid) table_close(rel, RowExclusiveLock); } +/* + * Remove any EXCEPT clause entries for a relation from schema publications. + * Called when a table changes schema (ALTER TABLE ... SET SCHEMA), so that + * a schema-scoped exclusion does not silently follow the table to its new + * schema. + */ +void +RemoveSchemaPubExceptForRel(Oid relid, Oid oldNspOid, Oid newNspOid) +{ + List *pubids; + + /* + * If the table is not actually moving to a different schema (no-op ALTER + * TABLE ... SET SCHEMA <current_schema>), there is nothing to do. + */ + if (oldNspOid == newNspOid) + return; + + pubids = GetRelationExcludedPublications(relid); + + foreach_oid(pubid, pubids) + { + Oid proid; + + /* + * This problem does not apply to FOR ALL TABLES publications, because + * their EXCEPT clause is publication-scoped, not schema-scoped: the + * exclusion should persist regardless of what schema the table is in. + */ + if (!is_schema_publication(pubid)) + continue; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddress obj; + + ObjectAddressSet(obj, PublicationRelRelationId, proid); + + ereport(DEBUG2, + errmsg_internal("auto-remove exclusion of table \"%s.%s\" from publication \"%s\": table moved to schema \"%s\"", + get_namespace_name(oldNspOid), + get_rel_name(relid), + get_publication_name(pubid, false), + get_namespace_name(newNspOid))); + + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + list_free(pubids); +} + /* * Open relations specified by a PublicationTable list. * The returned tables are locked in ShareUpdateExclusiveLock mode in order to diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 6857315c071..d6620046b51 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -49,6 +49,7 @@ #include "catalog/pg_opclass.h" #include "catalog/pg_policy.h" #include "catalog/pg_proc.h" +#include "catalog/pg_publication.h" #include "catalog/pg_publication_rel.h" #include "catalog/pg_rewrite.h" #include "catalog/pg_statistic_ext.h" @@ -63,6 +64,7 @@ #include "commands/event_trigger.h" #include "commands/extension.h" #include "commands/repack.h" +#include "commands/publicationcmds.h" #include "commands/sequence.h" #include "commands/tablecmds.h" #include "commands/tablespace.h" @@ -19781,6 +19783,16 @@ AlterTableNamespaceInternal(Relation rel, Oid oldNspOid, Oid nspOid, AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid, false, objsMoved); + /* + * Remove any EXCEPT clause entries for this relation from schema + * publications. A schema-scoped exclusion is no longer meaningful once + * the table moves to a different schema. + */ + if (rel->rd_rel->relkind == RELKIND_RELATION || + rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE) + RemoveSchemaPubExceptForRel(RelationGetRelid(rel), oldNspOid, + nspOid); + table_close(classRel, RowExclusiveLock); } @@ -21114,6 +21126,7 @@ ATExecAttachPartition(List **wqueue, Relation rel, PartitionCmd *cmd, if (exceptpuboids != NIL) { bool first = true; + bool has_alltables_pub = false; StringInfoData pubnames; initStringInfo(&pubnames); @@ -21127,17 +21140,22 @@ ATExecAttachPartition(List **wqueue, Relation rel, PartitionCmd *cmd, else appendStringInfo(&pubnames, _(", \"%s\""), pubname); first = false; + + if (GetPublication(pubid)->alltables) + has_alltables_pub = true; } ereport(ERROR, errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), - errmsg_plural("cannot attach table \"%s\" as partition because it is referenced in publication %s EXCEPT clause", - "cannot attach table \"%s\" as partition because it is referenced in publications %s EXCEPT clause", + errmsg_plural("cannot attach table \"%s\" as partition because it is named in EXCEPT clause of publication %s", + "cannot attach table \"%s\" as partition because it is named in EXCEPT clause of publications %s", list_length(exceptpuboids), RelationGetRelationName(attachrel), pubnames.data), errdetail("The publication EXCEPT clause cannot contain tables that are partitions."), - errhint("Change the publication's EXCEPT clause using ALTER PUBLICATION ... SET ALL TABLES.")); + errhint("%s", has_alltables_pub ? + _("Change the EXCEPT clause using ALTER PUBLICATION ... SET ALL TABLES ... EXCEPT.") : + _("Change the EXCEPT clause using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT."))); } list_free(exceptpuboids); diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y index 17035fb4d15..14520a5ccab 100644 --- a/src/backend/parser/gram.y +++ b/src/backend/parser/gram.y @@ -58,6 +58,7 @@ #include "nodes/makefuncs.h" #include "nodes/nodeFuncs.h" #include "parser/parser.h" +#include "utils/builtins.h" #include "utils/datetime.h" #include "utils/xml.h" @@ -11282,7 +11283,7 @@ AlterOwnerStmt: ALTER AGGREGATE aggregate_with_argtypes OWNER TO RoleSpec * pub_obj is one of: * * TABLE table [, ...] - * TABLES IN SCHEMA schema [, ...] + * TABLES IN SCHEMA schema [EXCEPT (TABLE table [, ...] )] [, ...] * *****************************************************************************/ @@ -11342,23 +11343,26 @@ PublicationObjSpec: $$->pubtable->columns = $3; $$->pubtable->whereClause = $4; } - | TABLES IN_P SCHEMA ColId + | TABLES IN_P SCHEMA ColId opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_SCHEMA; $$->name = $4; + $$->except_tables = $5; $$->location = @4; } - | TABLES IN_P SCHEMA CURRENT_SCHEMA + | TABLES IN_P SCHEMA CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_CUR_SCHEMA; + $$->except_tables = $5; $$->location = @4; } - | ColId opt_column_list OptWhereClause + | ColId opt_column_list OptWhereClause opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $4; /* * If either a row filter or column list is specified, create * a PublicationTable object. @@ -11402,10 +11406,11 @@ PublicationObjSpec: $$->pubtable->columns = $2; $$->pubtable->whereClause = $3; } - | CURRENT_SCHEMA + | CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $2; $$->location = @1; } ; @@ -20867,6 +20872,11 @@ preprocess_pub_all_objtype_list(List *all_objects_list, List **pubobjects, /* * Process pubobjspec_list to check for errors in any of the objects and * convert PUBLICATIONOBJ_CONTINUATION into appropriate PublicationObjSpecType. + * + * The except_tables attached to TABLES IN SCHEMA nodes are left in place here; + * ObjectsInPublicationToOids() qualifies their names, validates schema + * membership, and merges the qualified tables into its except_pubtables + * output list once the schema OID is known. */ static void preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) @@ -20895,6 +20905,13 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLE) { + /* EXCEPT is not valid for table objects */ + if (pubobj->except_tables != NIL) + ereport(ERROR, + errcode(ERRCODE_SYNTAX_ERROR), + errmsg("EXCEPT is not allowed for TABLE publication objects"), + parser_errposition(pubobj->location)); + /* relation name or pubtable must be set for this type of object */ if (!pubobj->name && !pubobj->pubtable) ereport(ERROR, diff --git a/src/backend/replication/pgoutput/pgoutput.c b/src/backend/replication/pgoutput/pgoutput.c index 0afdb1432ca..ee2b997f82d 100644 --- a/src/backend/replication/pgoutput/pgoutput.c +++ b/src/backend/replication/pgoutput/pgoutput.c @@ -2281,10 +2281,41 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) } } - if (list_member_oid(pubids, pub->oid) || - list_member_oid(schemaPubids, pub->oid) || - ancestor_published) + if (list_member_oid(pubids, pub->oid) || ancestor_published) publish = true; + else if (list_member_oid(schemaPubids, pub->oid)) + { + Oid root_relid; + bool root_is_except = false; + + /* + * schemaPubids is the list of publications that include + * relid's own schema, independent of the ancestor walk + * above -- a partition can live in a different schema + * than its root. Still need to check for exclusion here, + * using the top-most ancestor since only a root + * (non-partition) table can appear in an EXCEPT clause. + */ + if (am_partition) + { + List *ancestors = get_partition_ancestors(relid); + + /* + * ancestors is NIL for a partition with a pending + * DETACH CONCURRENTLY; + */ + root_relid = (ancestors == NIL) ? relid : + llast_oid(ancestors); + list_free(ancestors); + } + else + root_relid = relid; + + CheckPublicationRelEntry(pub->oid, root_relid, &root_is_except); + + if (!root_is_except) + publish = true; + } } /* diff --git a/src/backend/utils/cache/relcache.c b/src/backend/utils/cache/relcache.c index 19c4ff6e75e..e4eb5e6d885 100644 --- a/src/backend/utils/cache/relcache.c +++ b/src/backend/utils/cache/relcache.c @@ -5807,7 +5807,6 @@ RelationBuildPublicationDesc(Relation relation, PublicationDesc *pubdesc) { List *puboids = NIL; List *exceptpuboids = NIL; - List *alltablespuboids; ListCell *lc; MemoryContext oldcxt; Oid schemaid; @@ -5851,12 +5850,9 @@ RelationBuildPublicationDesc(Relation relation, PublicationDesc *pubdesc) if (relation->rd_rel->relispartition) { - Oid last_ancestor_relid; - - /* Add publications that the ancestors are in too. */ ancestors = get_partition_ancestors(relid); - last_ancestor_relid = llast_oid(ancestors); + /* Add publications that the ancestors are in too. */ foreach(lc, ancestors) { Oid ancestor = lfirst_oid(lc); @@ -5869,11 +5865,13 @@ RelationBuildPublicationDesc(Relation relation, PublicationDesc *pubdesc) } /* - * Only the top-most ancestor can appear in the EXCEPT clause. - * Therefore, for a partition, exclusion must be evaluated at the - * top-most ancestor. + * Only the topmost root of a partition hierarchy can appear in an + * EXCEPT clause, so that is where exclusion has to be evaluated. + * ancestors is NIL for a partition with a pending DETACH + * CONCURRENTLY, in which case there is no root to consult. */ - exceptpuboids = GetRelationExcludedPublications(last_ancestor_relid); + if (ancestors != NIL) + exceptpuboids = GetRelationExcludedPublications(llast_oid(ancestors)); } else { @@ -5884,10 +5882,12 @@ RelationBuildPublicationDesc(Relation relation, PublicationDesc *pubdesc) exceptpuboids = GetRelationExcludedPublications(relid); } - alltablespuboids = GetAllTablesPublications(); - puboids = list_concat_unique_oid(puboids, - list_difference_oid(alltablespuboids, - exceptpuboids)); + puboids = list_concat_unique_oid(puboids, GetAllTablesPublications()); + + /* Ignore the publications that exclude this relation. */ + if (exceptpuboids != NIL) + puboids = list_difference_oid(puboids, exceptpuboids); + foreach(lc, puboids) { Oid pubid = lfirst_oid(lc); diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c index ad9c8affb4f..bb980fc1c91 100644 --- a/src/bin/psql/describe.c +++ b/src/bin/psql/describe.c @@ -3036,7 +3036,29 @@ describeOneTableDetails(const char *schemaname, "FROM pg_catalog.pg_publication p\n" " JOIN pg_catalog.pg_publication_namespace pn ON p.oid = pn.pnpubid\n" " JOIN pg_catalog.pg_class pc ON pc.relnamespace = pn.pnnspid\n" - "WHERE pc.oid ='%s' and pg_catalog.pg_relation_is_publishable('%s')\n" + "WHERE pc.oid ='%s' and pg_catalog.pg_relation_is_publishable('%s')\n", + oid, oid); + + if (pset.sversion >= 200000) + { + /* + * Publishing the schema does not publish a table named in the + * publication's EXCEPT clause, nor a partition whose root is + * named there, since excluding a root excludes the whole + * partition tree. Unlike the FOR ALL TABLES case below, a + * schema publication can have both kinds of + * pg_publication_rel row, so prexcept has to be tested. + */ + appendPQExpBuffer(&buf, + " AND NOT EXISTS (\n" + " SELECT 1\n" + " FROM pg_catalog.pg_publication_rel pr\n" + " WHERE pr.prpubid = p.oid AND pr.prexcept AND\n" + " (pr.prrelid = '%s' OR pr.prrelid = pg_catalog.pg_partition_root('%s')))\n", + oid, oid); + } + + appendPQExpBuffer(&buf, "UNION\n" "SELECT pubname\n" " , pg_catalog.pg_get_expr(pr.prqual, c.oid)\n" @@ -3060,7 +3082,7 @@ describeOneTableDetails(const char *schemaname, " FROM pg_catalog.pg_publication_namespace pn\n" " WHERE pn.pnpubid = p.oid\n" " AND pn.pnnspid = c.relnamespace)\n", - oid, oid, oid); + oid); if (pset.sversion >= 190000) { @@ -6839,6 +6861,24 @@ describePublications(const char *pattern) if (!addFooterToPublicationDesc(&buf, _("Tables from schemas:"), true, &cont)) goto error_return; + + if (pset.sversion >= 200000) + { + /* + * Get tables in the EXCEPT clause for this schema + * publication. + */ + printfPQExpBuffer(&buf, + "SELECT concat(c.relnamespace::regnamespace, '.', c.relname)\n" + "FROM pg_catalog.pg_class c\n" + " JOIN pg_catalog.pg_publication_rel pr ON c.oid = pr.prrelid\n" + "WHERE pr.prpubid = '%s'\n" + " AND pr.prexcept\n" + "ORDER BY 1", pubid); + if (!addFooterToPublicationDesc(&buf, _("Except tables:"), + true, &cont)) + goto error_return; + } } } else diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index 190fff7ea0e..f069e2654cc 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -1065,6 +1065,24 @@ static const SchemaQuery Query_for_trigger_of_table = { "SELECT nspname FROM pg_catalog.pg_namespace "\ " WHERE nspname LIKE '%s'" +#define Query_for_list_of_tables_in_schema \ +"SELECT n.nspname || '.' || c.relname "\ +" FROM pg_catalog.pg_class c "\ +" JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "\ +" WHERE c.relkind IN (" CppAsString2(RELKIND_RELATION) ", " \ + CppAsString2(RELKIND_PARTITIONED_TABLE) ") "\ +" AND (n.nspname || '.' || c.relname) LIKE '%s' "\ +" AND n.nspname = '%s'" + +#define Query_for_list_of_tables_in_current_schema \ +"SELECT c.relname "\ +" FROM pg_catalog.pg_class c "\ +" JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "\ +" WHERE c.relkind IN (" CppAsString2(RELKIND_RELATION) ", " \ + CppAsString2(RELKIND_PARTITIONED_TABLE) ") "\ +" AND c.relname LIKE '%s' "\ +" AND n.nspname = pg_catalog.current_schema()" + /* Use COMPLETE_WITH_QUERY_VERBATIM with these queries for GUC names: */ #define Query_for_list_of_alter_system_set_vars \ "SELECT pg_catalog.lower(name) FROM pg_catalog.pg_settings "\ @@ -3777,8 +3795,21 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); - else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && (!ends_with(prev_wd, ','))) - COMPLETE_WITH("WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE", "WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* Complete "CREATE PUBLICATION <name> [...] WITH" */ else if (Matches("CREATE", "PUBLICATION", MatchAnyN, "WITH", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/include/catalog/pg_publication.h b/src/include/catalog/pg_publication.h index 89b4bb14f62..d241b781ccc 100644 --- a/src/include/catalog/pg_publication.h +++ b/src/include/catalog/pg_publication.h @@ -192,6 +192,7 @@ extern List *GetPubPartitionOptionRelations(List *result, Oid relid); extern Oid GetTopMostAncestorInPublication(Oid puboid, List *ancestors, int *ancestor_level); +extern bool CheckPublicationRelEntry(Oid pubid, Oid relid, bool *is_except); extern bool is_publishable_relation(Relation rel); extern bool is_schema_publication(Oid pubid); diff --git a/src/include/commands/publicationcmds.h b/src/include/commands/publicationcmds.h index 4cf45c17cc5..fb1703aa675 100644 --- a/src/include/commands/publicationcmds.h +++ b/src/include/commands/publicationcmds.h @@ -27,6 +27,8 @@ extern void AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt); extern void RemovePublicationById(Oid pubid); extern void RemovePublicationRelById(Oid proid); extern void RemovePublicationSchemaById(Oid psoid); +extern void RemoveSchemaPubExceptForRel(Oid relid, Oid oldNspOid, + Oid newNspOid); extern ObjectAddress AlterPublicationOwner(const char *name, Oid newOwnerId); extern void AlterPublicationOwner_oid(Oid pubid, Oid newOwnerId); diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h index 8a9df884276..01fa90b9186 100644 --- a/src/include/nodes/parsenodes.h +++ b/src/include/nodes/parsenodes.h @@ -4531,6 +4531,8 @@ typedef struct PublicationObjSpec PublicationObjSpecType pubobjtype; /* type of this publication object */ char *name; PublicationTable *pubtable; + List *except_tables; /* tables specified in the EXCEPT clause (for + * TABLES IN SCHEMA) */ ParseLoc location; /* token location, or -1 if unknown */ } PublicationObjSpec; diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 4f21462cc17..c78a4a15696 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -279,6 +279,12 @@ CREATE PUBLICATION testpub_foralltables_excepttable2 FOR ALL TABLES EXCEPT (test ERROR: syntax error at or near "testpub_tbl1" LINE 1: ..._foralltables_excepttable2 FOR ALL TABLES EXCEPT (testpub_tb... ^ +-- fail - EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testpub_tbl3); +ERROR: EXCEPT is not allowed for TABLE publication objects +LINE 2: FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testp... + ^ --------------------------------------------- -- SET ALL TABLES/SEQUENCES --------------------------------------------- @@ -473,13 +479,186 @@ CREATE TABLE tab_main (a int) PARTITION BY RANGE(a); -- Attaching a partition is not allowed if the partitioned table appears in a -- publication's EXCEPT clause. ALTER TABLE tab_main ATTACH PARTITION testpub_root FOR VALUES FROM (0) TO (200); -ERROR: cannot attach table "testpub_root" as partition because it is referenced in publication "testpub8" EXCEPT clause +ERROR: cannot attach table "testpub_root" as partition because it is named in EXCEPT clause of publication "testpub8" DETAIL: The publication EXCEPT clause cannot contain tables that are partitions. -HINT: Change the publication's EXCEPT clause using ALTER PUBLICATION ... SET ALL TABLES. +HINT: Change the EXCEPT clause using ALTER PUBLICATION ... SET ALL TABLES ... EXCEPT. RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Create same-named tables in public to verify unqualified EXCEPT entries +-- are qualified with the named schema, not public +CREATE TABLE testpub_nopk (foo int, bar int); +CREATE TABLE testpub_tbl_s1 (a int primary key, b text); +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + Publication testpub_schema_except1 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- Exclude multiple tables using unqualified names; same-named tables exist in +-- public to confirm unqualified names resolve to pub_test, not public +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + Publication testpub_schema_except2 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_nopk" + "pub_test.testpub_tbl_s1" + +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testp... + ^ +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); +ERROR: table "pub_test.testpub_tbl_s1" in EXCEPT clause does not belong to schema "public" +LINE 2: ...R TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.t... + ^ +-- Multiple schemas each with their own EXCEPT clause +CREATE PUBLICATION testpub_schema_except_multi + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_schema_except_multi + Publication testpub_schema_except_multi + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- fail: same schema repeated with same EXCEPT clauses +CREATE PUBLICATION testpub_schema_except_conflict + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: conflicting or redundant EXCEPT clauses for schema "pub_test" +-- fail: same schema repeated with conflicting or no EXCEPT clauses +CREATE PUBLICATION testpub_schema_except_conflict2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2), + pub_test; +ERROR: conflicting or redundant EXCEPT clauses for schema "pub_test" +-- ALTER TABLE ... SET SCHEMA on a table excluded by a schema publication: +-- the schema-scoped exclusion is no longer meaningful once the table moves +-- out of its schema, so the exclusion is auto-removed. +CREATE PUBLICATION testpub_schema_except_setsch + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_schema_except_setsch + Publication testpub_schema_except_setsch + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s2" + +ALTER TABLE pub_test.testpub_tbl_s2 SET SCHEMA public; +\dRp+ testpub_schema_except_setsch + Publication testpub_schema_except_setsch + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + +DROP PUBLICATION testpub_schema_except_setsch; +-- Restore for further tests +ALTER TABLE public.testpub_tbl_s2 SET SCHEMA pub_test; +-- fail: table appears in both the explicit table list and the EXCEPT clause +CREATE PUBLICATION testpub_except_conflict + FOR TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot be both published and excluded +-- fail: nonexistent table in EXCEPT clause +CREATE PUBLICATION testpub_except_norel + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- fail: partition cannot appear in EXCEPT clause; only root tables are allowed +CREATE TABLE pub_test.testpub_parted_s (a int) PARTITION BY LIST (a); +CREATE TABLE pub_test.testpub_part_s PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (1); +CREATE PUBLICATION testpub_except_partition + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); +ERROR: cannot specify relation "pub_test.testpub_part_s" in the publication EXCEPT clause +DETAIL: This operation is not supported for individual partitions. +-- fail: TABLE keyword is required for the first entry in the EXCEPT clause +CREATE PUBLICATION testpub_except_nokw + FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +ERROR: syntax error at or near "testpub_nopk" +LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + ^ +-- Check that a table excluded from a schema publication is reported only as +-- excluded and not as published. +\d pub_test.testpub_nopk + Table "pub_test.testpub_nopk" + Column | Type | Collation | Nullable | Default +--------+---------+-----------+----------+--------- + foo | integer | | | + bar | integer | | | +Included in publications: + "testpub_schema_except1" + "testpub_schema_except_multi" +Excluded from publications: + "testpub_schema_except2" + +-- fail: ADD TABLE for a partition is rejected when a partition ancestor +-- is currently in the publication's EXCEPT list. +CREATE PUBLICATION testpub_except_ancestor + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ALTER PUBLICATION testpub_except_ancestor ADD TABLE pub_test.testpub_part_s; +ERROR: cannot add partition "pub_test.testpub_part_s" to publication "testpub_except_ancestor" +DETAIL: Partition root "pub_test.testpub_parted_s" is named in the publication's EXCEPT clause for schema "pub_test". +HINT: Change the EXCEPT clause using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT. +DROP PUBLICATION testpub_except_ancestor; +-- fail: same contradiction (explicit partition + EXCEPT-ed ancestor), but +-- given in a single statement instead of two separate ones +CREATE PUBLICATION testpub_except_ancestor_same_create + FOR TABLE pub_test.testpub_part_s, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ERROR: partition "pub_test.testpub_part_s" cannot be both published and excluded +DETAIL: Partition root "pub_test.testpub_parted_s" is named in the publication's EXCEPT clause for schema "pub_test". +-- fail: same contradiction as above, but the partition lives in a different +-- schema (public) than its EXCEPT-ed root (pub_test) +CREATE TABLE public.testpub_part_s2 PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (2); +CREATE PUBLICATION testpub_except_ancestor_cross_schema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s), + TABLE public.testpub_part_s2; +ERROR: partition "public.testpub_part_s2" cannot be both published and excluded +DETAIL: Partition root "pub_test.testpub_parted_s" is named in the publication's EXCEPT clause for schema "pub_test". +DROP TABLE public.testpub_part_s2; +-- Cleanup +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP TABLE pub_test.testpub_parted_s CASCADE; +DROP TABLE testpub_nopk, testpub_tbl_s1; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +--------------------------------------------- +-- Tests for publications with SEQUENCES +--------------------------------------------- CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; -- FOR ALL SEQUENCES @@ -1970,6 +2149,54 @@ ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b); ERROR: column specification not allowed for schema LINE 1: ...TION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b)... ^ +-- EXCEPT clause with CURRENT_SCHEMA: cross-schema entry must be rejected +SET search_path = pub_test1; +-- qualified name from wrong schema -> error +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.tbl1); +ERROR: table "pub_test2.tbl1" in EXCEPT clause does not belong to schema "pub_test1" +LINE 1: ...FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.... + ^ +-- unqualified name implicitly qualified with current schema (pub_test1.tbl) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl); +RESET client_min_messages; +\dRp+ testpub_cursch_except + Publication testpub_cursch_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test1" +Except tables: + "pub_test1.tbl" + +DROP PUBLICATION testpub_cursch_except; +-- succeeds: CURRENT_SCHEMA and pub_test1 (same schema) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_named_same + FOR TABLES IN SCHEMA CURRENT_SCHEMA, pub_test1; +RESET client_min_messages; +\dRp+ testpub_cursch_named_same + Publication testpub_cursch_named_same + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test1" + +DROP PUBLICATION testpub_cursch_named_same; +-- fail: CURRENT_SCHEMA and pub_test1 (same schema) have +-- conflicting EXCEPT clauses +CREATE PUBLICATION testpub_cursch_named_conflict + FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl), + pub_test1 EXCEPT (TABLE tbl1); +ERROR: conflicting or redundant EXCEPT clauses for schema "pub_test1" +-- fail: two CURRENT_SCHEMA mentions with conflicting EXCEPT clauses +CREATE PUBLICATION testpub_cursch_cursch_conflict + FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl), + CURRENT_SCHEMA EXCEPT (TABLE tbl1); +ERROR: conflicting or redundant EXCEPT clauses for schema "pub_test1" +RESET search_path; -- cleanup pub_test1 schema for invalidation tests ALTER PUBLICATION testpub2_forschema DROP TABLES IN SCHEMA pub_test1; DROP PUBLICATION testpub3_forschema, testpub4_forschema, testpub5_forschema, testpub6_forschema, testpub_fortable; @@ -2321,6 +2548,7 @@ DROP ROLE regress_publication_user_dummy; -- Test pg_get_publication_tables(text[], oid) function CREATE SCHEMA gpt_test_sch; CREATE TABLE gpt_test_sch.tbl_sch (id int); +CREATE TABLE gpt_test_sch.tbl_sch2 (id int); CREATE TABLE tbl_normal (id int); CREATE TABLE tbl_parent (id1 int, id2 int, id3 int) PARTITION BY RANGE (id1); CREATE TABLE tbl_part1 PARTITION OF tbl_parent FOR VALUES FROM (1) TO (10); @@ -2331,6 +2559,7 @@ CREATE PUBLICATION pub_all_no_viaroot FOR ALL TABLES WITH (publish_via_partition CREATE PUBLICATION pub_all_except FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = true); CREATE PUBLICATION pub_all_except_no_viaroot FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_schema FOR TABLES IN SCHEMA gpt_test_sch; +CREATE PUBLICATION pub_schema_except FOR TABLES IN SCHEMA gpt_test_sch EXCEPT (TABLE gpt_test_sch.tbl_sch); CREATE PUBLICATION pub_normal FOR TABLE tbl_normal WHERE (id < 10); CREATE PUBLICATION pub_part_leaf FOR TABLE tbl_part1 WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_part_parent FOR TABLE tbl_parent (id1, id2) WHERE (id1 = 10) WITH (publish_via_partition_root = true); @@ -2482,6 +2711,44 @@ SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_part1'); -- no r ---------+---------+-------+------ (0 rows) +-- test for EXCEPT clause with schema publication +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch'); -- no result (excluded) + pubname | relname | attrs | qual +---------+---------+-------+------ +(0 rows) + +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch2'); -- one row (included via schema) + pubname | relname | attrs | qual +-------------------+----------+-------+------ + pub_schema_except | tbl_sch2 | 1 | +(1 row) + +-- test for EXCEPT clause with schema publication, where the excluded root's +-- partition lives in a different schema that is separately, fully included +-- (no EXCEPT) in the same publication. The root's exclusion must cascade to +-- the partition regardless of the partition's own schema membership. +CREATE SCHEMA gpt_cross_sch1; +CREATE SCHEMA gpt_cross_sch2; +CREATE TABLE gpt_cross_sch1.croot (id int) PARTITION BY RANGE (id); +CREATE TABLE gpt_cross_sch2.cpart1 PARTITION OF gpt_cross_sch1.croot FOR VALUES FROM (1) TO (10); +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION pub_cross_schema_except FOR TABLES IN SCHEMA gpt_cross_sch1 EXCEPT (TABLE gpt_cross_sch1.croot), TABLES IN SCHEMA gpt_cross_sch2; +RESET client_min_messages; +SELECT * FROM test_gpt(ARRAY['pub_cross_schema_except'], 'gpt_cross_sch1.croot'); -- no result (excluded) + pubname | relname | attrs | qual +---------+---------+-------+------ +(0 rows) + +-- no result (excluded via cascading root exclusion, even though cpart1's own +-- schema gpt_cross_sch2 is separately, fully included with no EXCEPT) +SELECT * FROM test_gpt(ARRAY['pub_cross_schema_except'], 'gpt_cross_sch2.cpart1'); + pubname | relname | attrs | qual +---------+---------+-------+------ +(0 rows) + +DROP PUBLICATION pub_cross_schema_except; +DROP TABLE gpt_cross_sch2.cpart1, gpt_cross_sch1.croot; +DROP SCHEMA gpt_cross_sch1, gpt_cross_sch2; -- two rows with different row filter SELECT * FROM test_gpt(ARRAY['pub_all', 'pub_normal'], 'tbl_normal'); pubname | relname | attrs | qual @@ -2534,6 +2801,7 @@ DROP PUBLICATION pub_all_no_viaroot; DROP PUBLICATION pub_all_except; DROP PUBLICATION pub_all_except_no_viaroot; DROP PUBLICATION pub_schema; +DROP PUBLICATION pub_schema_except; DROP PUBLICATION pub_normal; DROP PUBLICATION pub_part_leaf; DROP PUBLICATION pub_part_parent; @@ -2542,7 +2810,9 @@ DROP PUBLICATION pub_part_parent_child; DROP VIEW gpt_test_view; DROP TABLE tbl_normal, tbl_parent, tbl_part1; DROP SCHEMA gpt_test_sch CASCADE; -NOTICE: drop cascades to table gpt_test_sch.tbl_sch +NOTICE: drop cascades to 2 other objects +DETAIL: drop cascades to table gpt_test_sch.tbl_sch +drop cascades to table gpt_test_sch.tbl_sch2 -- stage objects for pg_dump tests CREATE SCHEMA pubme CREATE TABLE t0 (c int, d int) CREATE TABLE t1 (c int); CREATE SCHEMA pubme2 CREATE TABLE t0 (c int, d int); diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index fac54b02e27..dcdc1eb5df9 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -125,6 +125,9 @@ CREATE PUBLICATION testpub_foralltables_excepttable1 FOR ALL TABLES EXCEPT (TABL \d testpub_tbl1 -- fail - first table in the EXCEPT list should use TABLE keyword CREATE PUBLICATION testpub_foralltables_excepttable2 FOR ALL TABLES EXCEPT (testpub_tbl1, testpub_tbl2); +-- fail - EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testpub_tbl3); --------------------------------------------- -- SET ALL TABLES/SEQUENCES @@ -222,7 +225,119 @@ RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Create same-named tables in public to verify unqualified EXCEPT entries +-- are qualified with the named schema, not public +CREATE TABLE testpub_nopk (foo int, bar int); +CREATE TABLE testpub_tbl_s1 (a int primary key, b text); + +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + +-- Exclude multiple tables using unqualified names; same-named tables exist in +-- public to confirm unqualified names resolve to pub_test, not public +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); + +-- Multiple schemas each with their own EXCEPT clause +CREATE PUBLICATION testpub_schema_except_multi + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_schema_except_multi + +-- fail: same schema repeated with same EXCEPT clauses +CREATE PUBLICATION testpub_schema_except_conflict + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: same schema repeated with conflicting or no EXCEPT clauses +CREATE PUBLICATION testpub_schema_except_conflict2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2), + pub_test; + +-- ALTER TABLE ... SET SCHEMA on a table excluded by a schema publication: +-- the schema-scoped exclusion is no longer meaningful once the table moves +-- out of its schema, so the exclusion is auto-removed. +CREATE PUBLICATION testpub_schema_except_setsch + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_schema_except_setsch +ALTER TABLE pub_test.testpub_tbl_s2 SET SCHEMA public; +\dRp+ testpub_schema_except_setsch +DROP PUBLICATION testpub_schema_except_setsch; +-- Restore for further tests +ALTER TABLE public.testpub_tbl_s2 SET SCHEMA pub_test; + +-- fail: table appears in both the explicit table list and the EXCEPT clause +CREATE PUBLICATION testpub_except_conflict + FOR TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: nonexistent table in EXCEPT clause +CREATE PUBLICATION testpub_except_norel + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- fail: partition cannot appear in EXCEPT clause; only root tables are allowed +CREATE TABLE pub_test.testpub_parted_s (a int) PARTITION BY LIST (a); +CREATE TABLE pub_test.testpub_part_s PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (1); +CREATE PUBLICATION testpub_except_partition + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); + +-- fail: TABLE keyword is required for the first entry in the EXCEPT clause +CREATE PUBLICATION testpub_except_nokw + FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + +-- Check that a table excluded from a schema publication is reported only as +-- excluded and not as published. +\d pub_test.testpub_nopk + +-- fail: ADD TABLE for a partition is rejected when a partition ancestor +-- is currently in the publication's EXCEPT list. +CREATE PUBLICATION testpub_except_ancestor + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ALTER PUBLICATION testpub_except_ancestor ADD TABLE pub_test.testpub_part_s; +DROP PUBLICATION testpub_except_ancestor; + +-- fail: same contradiction (explicit partition + EXCEPT-ed ancestor), but +-- given in a single statement instead of two separate ones +CREATE PUBLICATION testpub_except_ancestor_same_create + FOR TABLE pub_test.testpub_part_s, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); + +-- fail: same contradiction as above, but the partition lives in a different +-- schema (public) than its EXCEPT-ed root (pub_test) +CREATE TABLE public.testpub_part_s2 PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (2); +CREATE PUBLICATION testpub_except_ancestor_cross_schema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s), + TABLE public.testpub_part_s2; +DROP TABLE public.testpub_part_s2; + +-- Cleanup +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP TABLE pub_test.testpub_parted_s CASCADE; +DROP TABLE testpub_nopk, testpub_tbl_s1; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; + +--------------------------------------------- +-- Tests for publications with SEQUENCES +--------------------------------------------- CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; @@ -1194,6 +1309,38 @@ ALTER PUBLICATION testpub1_forschema SET TABLES IN SCHEMA pub_test1, pub_test1; ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo (a, b); ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b); +-- EXCEPT clause with CURRENT_SCHEMA: cross-schema entry must be rejected +SET search_path = pub_test1; +-- qualified name from wrong schema -> error +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.tbl1); +-- unqualified name implicitly qualified with current schema (pub_test1.tbl) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl); +RESET client_min_messages; +\dRp+ testpub_cursch_except +DROP PUBLICATION testpub_cursch_except; + +-- succeeds: CURRENT_SCHEMA and pub_test1 (same schema) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_named_same + FOR TABLES IN SCHEMA CURRENT_SCHEMA, pub_test1; +RESET client_min_messages; +\dRp+ testpub_cursch_named_same +DROP PUBLICATION testpub_cursch_named_same; + +-- fail: CURRENT_SCHEMA and pub_test1 (same schema) have +-- conflicting EXCEPT clauses +CREATE PUBLICATION testpub_cursch_named_conflict + FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl), + pub_test1 EXCEPT (TABLE tbl1); + +-- fail: two CURRENT_SCHEMA mentions with conflicting EXCEPT clauses +CREATE PUBLICATION testpub_cursch_cursch_conflict + FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl), + CURRENT_SCHEMA EXCEPT (TABLE tbl1); + +RESET search_path; + -- cleanup pub_test1 schema for invalidation tests ALTER PUBLICATION testpub2_forschema DROP TABLES IN SCHEMA pub_test1; DROP PUBLICATION testpub3_forschema, testpub4_forschema, testpub5_forschema, testpub6_forschema, testpub_fortable; @@ -1448,6 +1595,7 @@ DROP ROLE regress_publication_user_dummy; -- Test pg_get_publication_tables(text[], oid) function CREATE SCHEMA gpt_test_sch; CREATE TABLE gpt_test_sch.tbl_sch (id int); +CREATE TABLE gpt_test_sch.tbl_sch2 (id int); CREATE TABLE tbl_normal (id int); CREATE TABLE tbl_parent (id1 int, id2 int, id3 int) PARTITION BY RANGE (id1); CREATE TABLE tbl_part1 PARTITION OF tbl_parent FOR VALUES FROM (1) TO (10); @@ -1459,6 +1607,7 @@ CREATE PUBLICATION pub_all_no_viaroot FOR ALL TABLES WITH (publish_via_partition CREATE PUBLICATION pub_all_except FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = true); CREATE PUBLICATION pub_all_except_no_viaroot FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_schema FOR TABLES IN SCHEMA gpt_test_sch; +CREATE PUBLICATION pub_schema_except FOR TABLES IN SCHEMA gpt_test_sch EXCEPT (TABLE gpt_test_sch.tbl_sch); CREATE PUBLICATION pub_normal FOR TABLE tbl_normal WHERE (id < 10); CREATE PUBLICATION pub_part_leaf FOR TABLE tbl_part1 WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_part_parent FOR TABLE tbl_parent (id1, id2) WHERE (id1 = 10) WITH (publish_via_partition_root = true); @@ -1515,6 +1664,32 @@ SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'gpt_test_sch.tbl_sch SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_parent'); -- no result (excluded) SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_part1'); -- no result +-- test for EXCEPT clause with schema publication +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch'); -- no result (excluded) +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch2'); -- one row (included via schema) + +-- test for EXCEPT clause with schema publication, where the excluded root's +-- partition lives in a different schema that is separately, fully included +-- (no EXCEPT) in the same publication. The root's exclusion must cascade to +-- the partition regardless of the partition's own schema membership. +CREATE SCHEMA gpt_cross_sch1; +CREATE SCHEMA gpt_cross_sch2; +CREATE TABLE gpt_cross_sch1.croot (id int) PARTITION BY RANGE (id); +CREATE TABLE gpt_cross_sch2.cpart1 PARTITION OF gpt_cross_sch1.croot FOR VALUES FROM (1) TO (10); + +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION pub_cross_schema_except FOR TABLES IN SCHEMA gpt_cross_sch1 EXCEPT (TABLE gpt_cross_sch1.croot), TABLES IN SCHEMA gpt_cross_sch2; +RESET client_min_messages; + +SELECT * FROM test_gpt(ARRAY['pub_cross_schema_except'], 'gpt_cross_sch1.croot'); -- no result (excluded) +-- no result (excluded via cascading root exclusion, even though cpart1's own +-- schema gpt_cross_sch2 is separately, fully included with no EXCEPT) +SELECT * FROM test_gpt(ARRAY['pub_cross_schema_except'], 'gpt_cross_sch2.cpart1'); + +DROP PUBLICATION pub_cross_schema_except; +DROP TABLE gpt_cross_sch2.cpart1, gpt_cross_sch1.croot; +DROP SCHEMA gpt_cross_sch1, gpt_cross_sch2; + -- two rows with different row filter SELECT * FROM test_gpt(ARRAY['pub_all', 'pub_normal'], 'tbl_normal'); @@ -1543,6 +1718,7 @@ DROP PUBLICATION pub_all_no_viaroot; DROP PUBLICATION pub_all_except; DROP PUBLICATION pub_all_except_no_viaroot; DROP PUBLICATION pub_schema; +DROP PUBLICATION pub_schema_except; DROP PUBLICATION pub_normal; DROP PUBLICATION pub_part_leaf; DROP PUBLICATION pub_part_parent; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 43b51c8ff71..7e11061a594 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -24,14 +24,17 @@ my $result; sub test_except_root_partition { - my ($pubviaroot) = @_; + my ($pubviaroot, $pubsql) = @_; + $pubsql //= + "CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1)"; + $pubsql .= " WITH (publish_via_partition_root = $pubviaroot)"; # If the root partitioned table is in the EXCEPT clause, all its # partitions are excluded from publication, regardless of the # publish_via_partition_root setting. $node_publisher->safe_psql( 'postgres', qq( - CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1) WITH (publish_via_partition_root = $pubviaroot); + $pubsql; INSERT INTO root1 VALUES (1), (101); )); $node_subscriber->safe_psql('postgres', @@ -223,6 +226,206 @@ $node_subscriber->safe_psql( test_except_root_partition('false'); test_except_root_partition('true'); +# Same validation using TABLES IN SCHEMA instead of FOR ALL TABLES. +my $schema_pub = + "CREATE PUBLICATION tap_pub_part FOR TABLES IN SCHEMA public EXCEPT (TABLE public.root1)"; +test_except_root_partition('false', $schema_pub); +test_except_root_partition('true', $schema_pub); + +# ============================================ +# EXCEPT test cases for TABLES IN SCHEMA +# ============================================ + +# Create a dedicated schema with two tables: one to be published and one to be +# excluded. Also create inherited tables to verify ONLY semantics. +$node_publisher->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_published AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.tab_excluded AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.parent (a int); + CREATE TABLE sch1.child (b int) INHERITS (sch1.parent); +)); + +$node_subscriber->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_published (a int); + CREATE TABLE sch1.tab_excluded (a int); + CREATE TABLE sch1.parent (a int); + CREATE TABLE sch1.child (b int) INHERITS (sch1.parent); +)); + +# Basic test: initial sync respects EXCEPT. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_excluded)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: initial sync copies included table'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: initial sync skips excluded table'); + +# DML: only the included table should be replicated. +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (6); + INSERT INTO sch1.tab_excluded VALUES (6); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(6), + 'TABLES IN SCHEMA EXCEPT: DML on included table is replicated'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: DML on excluded table is not replicated'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Inherited tables: excluding the parent (without ONLY) also excludes the child. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.parent)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.child VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.child"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: excluding parent (without ONLY) also excludes child' +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Test that EXCEPT (TABLE ONLY parent) excludes only the parent itself, not its +# child. Truncate child first so rows from the previous test are not copied by +# the initial table sync of the next subscription. +$node_publisher->safe_psql('postgres', 'TRUNCATE sch1.child'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE sch1.child'); +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE ONLY sch1.parent)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.child VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.child"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: ONLY parent in EXCEPT does not exclude child'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Cleanup schema tables before the multi-publication section. +$node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); +$node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); + +# ============================================ +# EXCEPT test cases for TABLES IN SCHEMA with a cross-schema partition +# ============================================ + +# A partition can live in a different schema than its partitioned root. If +# the root is excluded via EXCEPT under its own schema's clause, the +# exclusion must cascade to all its partitions, even when the partition's +# own schema is separately, fully included (no EXCEPT) in the same +# publication. +$node_publisher->safe_psql( + 'postgres', qq( + CREATE SCHEMA csch1; + CREATE SCHEMA csch2; + CREATE TABLE csch1.croot(a int) PARTITION BY RANGE(a); + CREATE TABLE csch2.cpart1 PARTITION OF csch1.croot FOR VALUES FROM (0) TO (100); + INSERT INTO csch1.croot VALUES (generate_series(1,5)); +)); + +$node_subscriber->safe_psql( + 'postgres', qq( + CREATE SCHEMA csch1; + CREATE SCHEMA csch2; + CREATE TABLE csch1.croot(a int); + CREATE TABLE csch2.cpart1(a int); +)); + +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION cross_sch_pub FOR TABLES IN SCHEMA csch1 EXCEPT (TABLE csch1.croot), TABLES IN SCHEMA csch2 WITH (publish_via_partition_root = false)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION cross_sch_sub CONNECTION '$publisher_connstr' PUBLICATION cross_sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'cross_sch_sub'); + +# Baseline: the root itself, pre-populated with rows before the subscription +# was created, is excluded by its own schema's EXCEPT clause -- initial sync +# must not have copied it. +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM csch1.croot"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: cross-schema partition root is excluded by initial sync' +); + +# Regression case: the partition's own schema (csch2) is separately, fully +# included with no EXCEPT, but the root's exclusion must still cascade to it +# -- initial sync must not have copied the pre-existing rows routed into this +# partition via the root. +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM csch2.cpart1"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: cross-schema partition is excluded by initial sync via cascading root exclusion' +); + +# Insert distinct, identifiable data directly into the partition and verify +# it is not replicated either. +$node_publisher->safe_psql('postgres', + "INSERT INTO csch2.cpart1 VALUES (generate_series(1,5))"); +$node_publisher->wait_for_catchup('cross_sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM csch1.croot"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: cross-schema partition root remains excluded after DML' +); +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM csch2.cpart1"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: cross-schema partition remains excluded after DML via cascading root exclusion' +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION cross_sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION cross_sch_pub'); +$node_publisher->safe_psql('postgres', 'DROP SCHEMA csch1, csch2 CASCADE'); +$node_subscriber->safe_psql('postgres', 'DROP SCHEMA csch1, csch2 CASCADE'); + # ============================================ # Test when a subscription is subscribing to multiple publications # ============================================ @@ -254,6 +457,7 @@ $node_publisher->safe_psql( DROP PUBLICATION tap_pub2; TRUNCATE tab1; )); +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_subscriber->safe_psql('postgres', qq(TRUNCATE tab1)); # OK when a table is excluded by pub1 EXCEPT clause, but it is included by pub2 @@ -282,6 +486,59 @@ $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); +# OK when a table is excluded by the EXCEPT clause of one schema publication, +# but it is included by another publication that publishes the same schema in +# full. Inclusion wins, so the table is replicated. +$node_publisher->safe_psql( + 'postgres', qq( + CREATE SCHEMA msch; + CREATE TABLE msch.tab_excl (a int); + INSERT INTO msch.tab_excl VALUES (1); + CREATE PUBLICATION tap_pub_sch_with_except + FOR TABLES IN SCHEMA msch EXCEPT (TABLE msch.tab_excl); + CREATE PUBLICATION tap_pub_sch_without_except FOR TABLES IN SCHEMA msch; +)); + +$node_subscriber->safe_psql( + 'postgres', qq( + CREATE SCHEMA msch; + CREATE TABLE msch.tab_excl (a int); +)); + +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION tap_sub_multi CONNECTION '$publisher_connstr' PUBLICATION tap_pub_sch_with_except, tap_pub_sch_without_except" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, + 'tap_sub_multi'); + +# The initial table sync must copy the excluded table too, because +# tap_pub_sch_without_except publishes it. +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM msch.tab_excl"); +is($result, qq(1), + 'initial sync copies a table excluded by one publication but included by another' +); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO msch.tab_excl VALUES (2); +)); +$node_publisher->wait_for_catchup('tap_sub_multi'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM msch.tab_excl"); +is($result, qq(2), + 'DML on a table excluded by one publication but included by another is replicated' +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub_multi'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub_sch_with_except'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub_sch_without_except'); +$node_publisher->safe_psql('postgres', 'DROP SCHEMA msch CASCADE'); +$node_subscriber->safe_psql('postgres', 'DROP SCHEMA msch CASCADE'); + $node_publisher->stop('fast'); done_testing(); -- 2.55.0
v26-0004-Documentation-Patch.patch (application/octet-stream, 11.6K) download From b0b46b5f43107e52da3440d76db0da4aef4bb9fc Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Thu, 30 Jul 2026 10:15:42 +0530 Subject: [PATCH v26 4/4] Documentation Patch --- doc/src/sgml/logical-replication.sgml | 3 +- doc/src/sgml/ref/alter_publication.sgml | 56 +++++++++++++++++++++++- doc/src/sgml/ref/create_publication.sgml | 42 ++++++++++++++---- 3 files changed, 89 insertions(+), 12 deletions(-) diff --git a/doc/src/sgml/logical-replication.sgml b/doc/src/sgml/logical-replication.sgml index 3a61e2d6889..eaf2d814ac6 100644 --- a/doc/src/sgml/logical-replication.sgml +++ b/doc/src/sgml/logical-replication.sgml @@ -117,7 +117,8 @@ or <literal>FOR ALL SEQUENCES</literal>. Unlike tables, sequences can be synchronized at any time. For more information, see <xref linkend="logical-replication-sequences"/>. When a publication is - created with <literal>FOR ALL TABLES</literal>, a table or set of tables can + created with <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal>, a table or set of tables can be explicitly excluded from publication using the <link linkend="sql-createpublication-params-for-except-table"><literal>EXCEPT</literal></link> clause. diff --git a/doc/src/sgml/ref/alter_publication.sgml b/doc/src/sgml/ref/alter_publication.sgml index d2898d2633e..209b92935e9 100644 --- a/doc/src/sgml/ref/alter_publication.sgml +++ b/doc/src/sgml/ref/alter_publication.sgml @@ -31,7 +31,7 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA <replaceable class="parameter">tables_in_schema</replaceable> [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -47,6 +47,10 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <replaceable class="parameter">table_object</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] [ WHERE ( <replaceable class="parameter">expression</replaceable> ) ] +<phrase>and <replaceable class="parameter">tables_in_schema</replaceable> is:</phrase> + + { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] + <phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> TABLE <replaceable class="parameter">table_object</replaceable> [, ... ] @@ -69,6 +73,9 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r The first two variants modify which tables/schemas are part of the publication. The <literal>ADD</literal> and <literal>DROP</literal> clauses will add and remove one or more tables/schemas from the publication. + The <literal>EXCEPT</literal> clause can be used with + <literal>ADD TABLES IN SCHEMA</literal> to exclude specific tables from a + schema-level publication. </para> <para> @@ -93,7 +100,11 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r used with a publication defined with <literal>FOR TABLE</literal> or <literal>FOR TABLES IN SCHEMA</literal>, replaces the list of tables/schemas in the publication with the specified list; the existing tables or schemas - that were present in the publication will be removed. + that were present in the publication will be removed. When + <literal>SET TABLES IN SCHEMA</literal> is used with an + <literal>EXCEPT</literal> clause, the excluded tables for each schema are + replaced with the specified list; if <literal>EXCEPT</literal> is omitted + for a schema, any existing exclusions for that schema are cleared. </para> <para> @@ -210,6 +221,26 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r </listitem> </varlistentry> + <varlistentry id="sql-alterpublication-params-except"> + <term><literal>EXCEPT</literal></term> + <listitem> + <para> + When used with <literal>ADD TABLES IN SCHEMA</literal> + or <literal>SET TABLES IN SCHEMA</literal>, specifies tables to be + excluded from the publication. Each named table must belong to the + schema specified in the same <literal>TABLES IN SCHEMA</literal> clause. + Table names may be schema-qualified or unqualified; unqualified names + are implicitly qualified with the schema named in the same clause. See + <xref linkend="sql-createpublication"/> for further details on the + semantics of <literal>EXCEPT</literal>. + </para> + <para> + Dropping a table always removes it from the <literal>EXCEPT</literal> + clause. + </para> + </listitem> + </varlistentry> + <varlistentry id="sql-alterpublication-params-set"> <term><literal>SET ( <replaceable class="parameter">publication_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] )</literal></term> <listitem> @@ -300,6 +331,27 @@ ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA marketing, sales; </programlisting> </para> + <para> + Add schema <structname>sales</structname> to the publication + <structname>sales_publication</structname>, excluding the + <structname>sales.internal</structname> and + <structname>sales.drafts</structname> tables: +<programlisting> +ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA sales EXCEPT (TABLE internal, drafts); +</programlisting> + </para> + + <para> + Replace the schema list of <structname>sales_publication</structname> with + only schema <structname>sales</structname>, excluding only + <structname>sales.drafts</structname>. All other previously excluded tables + in schema <structname>sales</structname> are no longer excluded. Any schemas + previously in <structname>sales_publication</structname> are removed: +<programlisting> +ALTER PUBLICATION sales_publication SET TABLES IN SCHEMA sales EXCEPT (TABLE drafts); +</programlisting> + </para> + <para> Add tables <structname>users</structname>, <structname>departments</structname> and schema diff --git a/doc/src/sgml/ref/create_publication.sgml b/doc/src/sgml/ref/create_publication.sgml index 35c28006f60..5b128694ad0 100644 --- a/doc/src/sgml/ref/create_publication.sgml +++ b/doc/src/sgml/ref/create_publication.sgml @@ -28,7 +28,7 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA <replaceable class="parameter">tables_in_schema</replaceable> [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -39,6 +39,10 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <replaceable class="parameter">table_object</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] [ WHERE ( <replaceable class="parameter">expression</replaceable> ) ] +<phrase>and <replaceable class="parameter">tables_in_schema</replaceable> is:</phrase> + + { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] + <phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> TABLE <replaceable class="parameter">table_object</replaceable> [, ... ] @@ -172,6 +176,8 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <para> Marks the publication as one that replicates changes for all tables in the specified list of schemas, including tables created in the future. + Tables listed in the <literal>EXCEPT</literal> clause for a given schema + are excluded from the publication. </para> <para> @@ -203,7 +209,7 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <para> Marks the publication as one that replicates changes for all tables in the database, including tables created in the future. Tables listed in - <literal>EXCEPT</literal> clause are excluded from the publication. + the <literal>EXCEPT</literal> clause are excluded from the publication. </para> </listitem> </varlistentry> @@ -228,13 +234,21 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <listitem> <para> This clause specifies a list of tables to be excluded from the - publication. + publication. It can be used with <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal>. For <literal>FOR TABLES IN + SCHEMA</literal>, the exclusion applies only to tables in the schema + associated with the <literal>EXCEPT</literal> clause. </para> <para> - Once a table is excluded, the exclusion applies to that table - regardless of its name or schema. Renaming the table or moving it to - another schema using <command>ALTER TABLE ... SET SCHEMA</command> does - not remove the exclusion. + Once a table is excluded under <literal>FOR ALL TABLES</literal>, the + exclusion applies to that table regardless of its name or schema. + Renaming the table or moving it to another schema using + <command>ALTER TABLE ... SET SCHEMA</command> does not remove the + exclusion. However, for <literal>FOR TABLES IN SCHEMA</literal>, because + the <literal>EXCEPT</literal> is schema-scoped, moving a schema-excluded + table to another schema does remove the exclusion; if the table is later + moved back, the exclusion is not restored and must be re-established + with <command>ALTER PUBLICATION</command>. </para> <para> For inherited tables, if <literal>ONLY</literal> is specified before the @@ -247,8 +261,9 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> </para> <para> For partitioned tables, only the root partitioned table may be specified - in <literal>EXCEPT</literal>. Doing so excludes the root table and - all of its partitions from replication. The optional + in <literal>EXCEPT</literal>. Excluding the root table automatically + excludes all of its partitions from replication, even those in + schemas that are otherwise included in the publication. The optional <literal>ONLY</literal> and <literal>*</literal> has no effect for partitioned tables. </para> @@ -552,6 +567,15 @@ CREATE PUBLICATION production_publication FOR TABLE users, departments, TABLES I CREATE PUBLICATION sales_publication FOR TABLES IN SCHEMA marketing, sales; </programlisting></para> + <para> + Create a publication that publishes all changes for all the tables present in + the schema <structname>sales</structname>, except + <structname>internal</structname> and <structname>drafts</structname>: +<programlisting> +CREATE PUBLICATION sales_filtered FOR TABLES IN SCHEMA sales EXCEPT (TABLE internal, drafts); +</programlisting> + </para> + <para> Create a publication that publishes all changes for table <structname>users</structname>, but replicates only columns <structname>user_id</structname> and -- 2.55.0
v26-0002-Add-EXCEPT-support-to-ALTER-PUBLICATION-ADD-TABL.patch (application/octet-stream, 22.3K) download From 167932e8375a5f8b742e2365926f15c9386bd6a9 Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Thu, 23 Jul 2026 12:31:51 +0530 Subject: [PATCH v26 2/3] Add EXCEPT support to ALTER PUBLICATION ADD TABLES IN SCHEMA Extend the EXCEPT clause support to allow tables to be excluded when adding a schema to a publication via ALTER PUBLICATION ... ADD. Syntax: ALTER PUBLICATION pub ADD TABLES IN SCHEMA s EXCEPT (TABLE s.t1); Since pg_dump uses ALTER PUBLICATION ... ADD, support for it is included in this patch. --- src/backend/catalog/pg_publication.c | 19 ++-- src/backend/commands/publicationcmds.c | 102 ++++++++++++++++++++-- src/bin/pg_dump/pg_dump.c | 30 ++++++- src/bin/pg_dump/t/002_pg_dump.pl | 24 +++++ src/bin/psql/tab-complete.in.c | 17 ++++ src/test/regress/expected/publication.out | 60 ++++++++++++- src/test/regress/sql/publication.sql | 45 +++++++++- src/test/subscription/t/037_except.pl | 32 +++++++ 8 files changed, 313 insertions(+), 16 deletions(-) diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index 9d8824f92e4..1ca33aa9a92 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -733,15 +733,18 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, * here, as CreatePublication() function invalidates all relations as part * of defining a FOR ALL TABLES publication. * - * For ALTER PUBLICATION, invalidation is needed only when adding an - * EXCEPT table to a publication already marked as ALL TABLES. For - * publications that were originally empty or defined as ALL SEQUENCES and - * are being converted to ALL TABLES, invalidation is skipped here, as - * AlterPublicationAllFlags() function invalidates all relations while - * marking the publication as ALL TABLES publication. + * For ALTER PUBLICATION, invalidation is needed when adding an EXCEPT + * table to either a FOR ALL TABLES publication (pub->alltables is true) + * or a FOR TABLES IN SCHEMA publication (is_schema_publication is true). + * The exception: when a publication is being converted to FOR ALL TABLES + * (pub->alltables is still false at this point), + * AlterPublicationAllFlags() will perform a full invalidation, so we skip + * it here. */ - inval_except_table = (alter_stmt != NULL) && pub->alltables && - (alter_stmt->for_all_tables && pri->except); + inval_except_table = (alter_stmt != NULL) && pri->except && + (pub->alltables + ? alter_stmt->for_all_tables + : is_schema_publication(pubid)); if (!pri->except || inval_except_table) { diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 8c39950bcda..84fd2514514 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -71,6 +71,13 @@ static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok); static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); +static void AlterPublicationSchemas(AlterPublicationStmt *stmt, + HeapTuple tup, List *schemaidlist, + List *except_pubtables); +static void AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, + List *except_pubtables, + List *schemaidlist); static char defGetGeneratedColsOption(DefElem *def); static void CheckExceptNotInTableList(List *except_rels, List *explicitrelids); static void ProcessSchemaExceptTables(Oid schemaid, List *except_tables, @@ -1603,7 +1610,8 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, */ static void AlterPublicationSchemas(AlterPublicationStmt *stmt, - HeapTuple tup, List *schemaidlist) + HeapTuple tup, List *schemaidlist, + List *except_pubtables) { Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); @@ -1680,6 +1688,88 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, */ PublicationAddSchemas(pubform->oid, schemaidlist, true, stmt); } + + /* + * Increment the command counter so that is_schema_publication() in + * GetExcludedPublicationTables() can see the just-inserted schema + * rows when AlterPublicationSchemaExceptTables runs next. + */ + if (stmt->action == AP_AddObjects || stmt->action == AP_SetObjects) + CommandCounterIncrement(); + + AlterPublicationSchemaExceptTables(stmt, tup, except_pubtables, schemaidlist); +} + +/* + * Alter the EXCEPT list of a schema-level publication. + * + * Adds, removes, or replaces except-table entries in pg_publication_rel + * (rows with prexcept = true). These entries suppress publication of the + * named tables that would otherwise be covered by a FOR TABLES IN SCHEMA + * clause. + */ +static void +AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, List *except_pubtables, + List *schemaidlist) +{ + Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); + Oid pubid = pubform->oid; + + /* + * Nothing to do if no EXCEPT entries. + */ + if (!except_pubtables) + return; + + /* + * This function handles EXCEPT entries for schema-level publications + * only. For FOR ALL TABLES publications, EXCEPT entries are already + * processed by AlterPublicationTables(). + */ + if (schemaidlist == NIL && !is_schema_publication(pubid)) + return; + + /* + * Dropping a schema from a publication removes all its EXCEPT entries via + * cascade. The concept of "drop all schema tables from the publication + * EXCEPT these ones" is not supported. + */ + if (stmt->action == AP_DropObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); + + /* + * XXX EXCEPT with SET is not currently implemented. Workaround: DROP and + * re-ADD the schema with the desired EXCEPT list. + */ + if (stmt->action == AP_SetObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"), + errhint("Drop and re-add the schema with the desired EXCEPT list."))); + + if (stmt->action == AP_AddObjects) + { + List *rels; + List *explicitrelids; + + rels = OpenTableList(except_pubtables); + + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + /* + * Validate that each excluded table is not also in the explicit table + * list (which would be contradictory). + */ + CheckExceptNotInTableList(rels, explicitrelids); + + PublicationAddTables(pubid, rels, false, stmt); + + CloseTableList(rels); + } } /* @@ -1861,12 +1951,12 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) else { List *relations = NIL; - List *exceptrelations = NIL; + List *except_pubtables = NIL; List *schemaidlist = NIL; Oid pubid = pubform->oid; ObjectsInPublicationToOids(stmt->pubobjects, pstate, &relations, - &exceptrelations, &schemaidlist); + &except_pubtables, &schemaidlist); CheckAlterPublication(stmt, tup, relations, schemaidlist); @@ -1889,10 +1979,12 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) errmsg("publication \"%s\" does not exist", stmt->pubname)); - relations = list_concat(relations, exceptrelations); + if (stmt->for_all_tables) + relations = list_concat(relations, except_pubtables); + AlterPublicationTables(stmt, tup, relations, pstate->p_sourcetext, schemaidlist != NIL); - AlterPublicationSchemas(stmt, tup, schemaidlist); + AlterPublicationSchemas(stmt, tup, schemaidlist, except_pubtables); AlterPublicationAllFlags(stmt, rel, tup); } diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c index feed88f9854..ddbd5e40285 100644 --- a/src/bin/pg_dump/pg_dump.c +++ b/src/bin/pg_dump/pg_dump.c @@ -4973,6 +4973,7 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) PublicationInfo *pubinfo = pubsinfo->publication; PQExpBuffer query; char *tag; + bool has_except = false; /* Do nothing if not dumping schema */ if (!dopt->dumpSchema) @@ -4983,7 +4984,34 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) query = createPQExpBuffer(); appendPQExpBuffer(query, "ALTER PUBLICATION %s ", fmtId(pubinfo->dobj.name)); - appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s;\n", fmtId(schemainfo->dobj.name)); + appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s", fmtId(schemainfo->dobj.name)); + + /* + * Append EXCEPT clause for any tables that belong to this schema + * and are excluded from the publication. + */ + for (SimplePtrListCell *cell = pubinfo->except_tables.head; cell; cell = cell->next) + { + TableInfo *tbinfo = (TableInfo *) cell->ptr; + + if (strcmp(tbinfo->dobj.namespace->dobj.name, schemainfo->dobj.name) == 0) + { + if (!has_except) + { + appendPQExpBufferStr(query, " EXCEPT ("); + has_except = true; + } + else + appendPQExpBufferStr(query, ", "); + + appendPQExpBuffer(query, "TABLE ONLY %s", fmtId(tbinfo->dobj.name)); + } + } + + if (has_except) + appendPQExpBufferStr(query, ")"); + + appendPQExpBufferStr(query, ";\n"); /* * There is no point in creating drop query as the drop is done by schema diff --git a/src/bin/pg_dump/t/002_pg_dump.pl b/src/bin/pg_dump/t/002_pg_dump.pl index 9258948b583..d18b3b0d7b9 100644 --- a/src/bin/pg_dump/t/002_pg_dump.pl +++ b/src/bin/pg_dump/t/002_pg_dump.pl @@ -3283,6 +3283,30 @@ my %tests = ( like => { %full_runs, section_post_data => 1, }, }, + 'CREATE PUBLICATION pub11' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub11 FOR TABLES IN SCHEMA dump_test EXCEPT (TABLE test_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub11 WITH (publish = 'insert, update, delete, truncate');\E + .*? + \QALTER PUBLICATION pub11 ADD TABLES IN SCHEMA dump_test EXCEPT (TABLE ONLY test_table);\E + /xms, + like => { %full_runs, section_post_data => 1, }, + }, + + 'CREATE PUBLICATION pub12' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub12 FOR TABLES IN SCHEMA dump_test EXCEPT (TABLE test_table, dump_test.test_second_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub12 WITH (publish = 'insert, update, delete, truncate');\E + .*? + \QALTER PUBLICATION pub12 ADD TABLES IN SCHEMA dump_test EXCEPT (TABLE ONLY test_table, TABLE ONLY test_second_table);\E + /xms, + like => { %full_runs, section_post_data => 1, }, + }, + 'CREATE SUBSCRIPTION sub1' => { create_order => 50, create_sql => 'CREATE SUBSCRIPTION sub1 diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index f069e2654cc..6d857865d6b 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2359,6 +2359,23 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); + /* After a single schema name in ADD context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index c78a4a15696..c5e95491a8a 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -650,12 +650,70 @@ CREATE PUBLICATION testpub_except_ancestor_cross_schema ERROR: partition "public.testpub_part_s2" cannot be both published and excluded DETAIL: Partition root "pub_test.testpub_parted_s" is named in the publication's EXCEPT clause for schema "pub_test". DROP TABLE public.testpub_part_s2; +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; +-- fail: non-existing table in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- fail: EXCEPT table belongs to a different schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 1: ...xcept ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.tes... + ^ +-- fail: TABLE keyword is required for the first entry in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +ERROR: syntax error at or near "testpub_nopk" +LINE 1: ...lter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_no... + ^ +-- fail: exact same table given as both explicitly published and excluded +-- in a single ALTER ... ADD +ALTER PUBLICATION testpub_alter_except + ADD TABLE pub_test.testpub_tbl_s1, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot be both published and excluded +-- fail: add explicit partition and EXCEPT ancestor, given in a +-- single ALTER ... ADD statement +ALTER PUBLICATION testpub_alter_except + ADD TABLE pub_test.testpub_part_s, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ERROR: partition "pub_test.testpub_part_s" cannot be both published and excluded +DETAIL: Partition root "pub_test.testpub_parted_s" is named in the publication's EXCEPT clause for schema "pub_test". +-- fail: partition already explicitly published, then its root is EXCEPT-ed +-- via a later, separate ALTER ... ADD +ALTER PUBLICATION testpub_alter_except ADD TABLE pub_test.testpub_part_s; +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ERROR: partition "pub_test.testpub_part_s" cannot be both published and excluded +DETAIL: Partition root "pub_test.testpub_parted_s" is named in the publication's EXCEPT clause for schema "pub_test". +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_part_s; +-- fail: root already explicitly published, then its partition is rejected +-- from EXCEPT via a later, separate ALTER ... ADD (partitions can never +-- appear in EXCEPT, independent of the root's state) +ALTER PUBLICATION testpub_alter_except ADD TABLE pub_test.testpub_parted_s; +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); +ERROR: cannot specify relation "pub_test.testpub_part_s" in the publication EXCEPT clause +DETAIL: This operation is not supported for individual partitions. +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_parted_s; +-- ADD: qualified and unqualified names; unqualified is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + "pub_test.testpub_tbl_s2" + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP TABLE pub_test.testpub_parted_s CASCADE; DROP TABLE testpub_nopk, testpub_tbl_s1; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi, testpub_alter_except; --------------------------------------------- -- Tests for publications with SEQUENCES --------------------------------------------- diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index dcdc1eb5df9..42b7c78f7fd 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -328,12 +328,55 @@ CREATE PUBLICATION testpub_except_ancestor_cross_schema TABLE public.testpub_part_s2; DROP TABLE public.testpub_part_s2; +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; + +-- fail: non-existing table in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- fail: EXCEPT table belongs to a different schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- fail: TABLE keyword is required for the first entry in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + +-- fail: exact same table given as both explicitly published and excluded +-- in a single ALTER ... ADD +ALTER PUBLICATION testpub_alter_except + ADD TABLE pub_test.testpub_tbl_s1, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: add explicit partition and EXCEPT ancestor, given in a +-- single ALTER ... ADD statement +ALTER PUBLICATION testpub_alter_except + ADD TABLE pub_test.testpub_part_s, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); + +-- fail: partition already explicitly published, then its root is EXCEPT-ed +-- via a later, separate ALTER ... ADD +ALTER PUBLICATION testpub_alter_except ADD TABLE pub_test.testpub_part_s; +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_part_s; + +-- fail: root already explicitly published, then its partition is rejected +-- from EXCEPT via a later, separate ALTER ... ADD (partitions can never +-- appear in EXCEPT, independent of the root's state) +ALTER PUBLICATION testpub_alter_except ADD TABLE pub_test.testpub_parted_s; +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_parted_s; + +-- ADD: qualified and unqualified names; unqualified is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); +\dRp+ testpub_alter_except + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP TABLE pub_test.testpub_parted_s CASCADE; DROP TABLE testpub_nopk, testpub_tbl_s1; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi, testpub_alter_except; --------------------------------------------- -- Tests for publications with SEQUENCES diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 7e11061a594..ed931d0d970 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -347,6 +347,38 @@ is($result, qq(5), $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); +# ============================================ +# ALTER PUBLICATION EXCEPT for TABLES IN SCHEMA +# ============================================ + +# Truncate subscriber tables to remove data accumulated from previous tests. +$node_subscriber->safe_psql('postgres', + 'TRUNCATE sch1.tab_published, sch1.tab_excluded, sch1.parent, sch1.child'); + +# ADD: add a schema with an excepted table; verify the except entry takes effect. +$node_publisher->safe_psql('postgres', "CREATE PUBLICATION sch_pub"); +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub ADD TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_excluded)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(6), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: included table synced'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + # Cleanup schema tables before the multi-publication section. $node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); $node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); -- 2.55.0
^ permalink raw reply [nested|flat] 196+ messages in thread

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-11 14:41  vignesh C <vignesh21@gmail.com>
  parent: vignesh C <vignesh21@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: vignesh C @ 2026-08-11 14:41 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Peter Smith <smithpb2250@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Fri, 7 Aug 2026 at 17:26, vignesh C <vignesh21@gmail.com> wrote:
>
> I noticed what appears to be an unexpected behavior with publications
> involving inherited tables and wanted to check whether this is
> intentional. The following steps reproduce the behavior:
> CREATE SCHEMA s1;
> CREATE SCHEMA s2;
> CREATE TABLE s1.parent (a int);
> CREATE TABLE s2.child (b int) INHERITS (s1.parent);
>
> -- Create a publication excluding the parent table
> CREATE PUBLICATION p FOR TABLES IN SCHEMA s1 EXCEPT (TABLE s1.parent);
>
> The publication excludes both the parent and child tables:
> postgres=# \dRp+
>                                                            Publication p
>      Owner      | All tables | All sequences | Inserts | Updates |
> Deletes | Truncates | Generated columns | Via root | Description
> ----------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+-------------
>  test           | f          | f             | t       | t       | t
>     | t         | none              | f        |
> Tables from schemas:
>     "s1"
> Except tables:
>     "s1.parent"
>     "s2.child"

For this issue, I compared the behavior of inherited tables across
schemas with the behavior of the existing 'TABLES IN SCHEMA'
publications.
-- Inherited tables across different schemas
CREATE SCHEMA s1;
CREATE SCHEMA s2;
CREATE TABLE s1.parent (a int);
CREATE TABLE s2.child (b int) INHERITS (s1.parent);

-- Initial data
INSERT INTO s2.child VALUES (10, 20);
INSERT INTO s1.parent VALUES (100);

### Test 1
Create a publication that includes only schema s1:
CREATE PUBLICATION pub1 FOR TABLES IN SCHEMA s1;

On the subscriber, the initial synchronization gives:
postgres=# SELECT * FROM s1.parent;
  a
-----
 100
(1 row)

postgres=# SELECT * FROM s2.child;
 a | b
---+---
(0 rows)

Here, s1.parent is included because it belongs to schema s1, which is
part of the publication pub1. s2.child is not replicated because it
belongs to schema s2, which is not part of the publication pub1.

Similarly, in the proposed patch for the following scenario-1:
CREATE PUBLICATION pub1 FOR TABLES IN SCHEMA s1 EXCEPT (TABLE s1.parent);

We can exclude s1.parent. The resulting publication state would have
s1.parent represented with prexcept = true, while s2.child would not
be present in pg_publication_rel because schema s2 was not selected.

I was not sure about the behavior when both schemas are explicitly
selected in the following scenario-2:
CREATE PUBLICATION pub1 FOR TABLES IN SCHEMA s1 EXCEPT (TABLE
s1.parent), TABLES IN SCHEMA s2;

Should the EXCEPT clause be scoped to the tables selected by the
corresponding TABLES IN SCHEMA s1 clause, or should it apply globally
to related tables selected through other TABLES IN SCHEMA clauses as
well?

In other words, should s2.child remain included because it is
explicitly selected through TABLES IN SCHEMA s2, or should excluding
its parent s1.parent also cause the inherited child s2.child to be
excluded?

Thoughts?

Regards,
Vignesh






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-12 04:01  shveta malik <shveta.malik@gmail.com>
  parent: vignesh C <vignesh21@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: shveta malik @ 2026-08-12 04:01 UTC (permalink / raw)
  To: vignesh C <vignesh21@gmail.com>; +Cc: Nisha Moond <nisha.moond412@gmail.com>; Peter Smith <smithpb2250@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; shveta malik <shveta.malik@gmail.com>

On Tue, Aug 11, 2026 at 8:11 PM vignesh C <vignesh21@gmail.com> wrote:
>
> On Fri, 7 Aug 2026 at 17:26, vignesh C <vignesh21@gmail.com> wrote:
> >
> > I noticed what appears to be an unexpected behavior with publications
> > involving inherited tables and wanted to check whether this is
> > intentional. The following steps reproduce the behavior:
> > CREATE SCHEMA s1;
> > CREATE SCHEMA s2;
> > CREATE TABLE s1.parent (a int);
> > CREATE TABLE s2.child (b int) INHERITS (s1.parent);
> >
> > -- Create a publication excluding the parent table
> > CREATE PUBLICATION p FOR TABLES IN SCHEMA s1 EXCEPT (TABLE s1.parent);
> >
> > The publication excludes both the parent and child tables:
> > postgres=# \dRp+
> >                                                            Publication p
> >      Owner      | All tables | All sequences | Inserts | Updates |
> > Deletes | Truncates | Generated columns | Via root | Description
> > ----------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+-------------
> >  test           | f          | f             | t       | t       | t
> >     | t         | none              | f        |
> > Tables from schemas:
> >     "s1"
> > Except tables:
> >     "s1.parent"
> >     "s2.child"
>
> For this issue, I compared the behavior of inherited tables across
> schemas with the behavior of the existing 'TABLES IN SCHEMA'
> publications.
> -- Inherited tables across different schemas
> CREATE SCHEMA s1;
> CREATE SCHEMA s2;
> CREATE TABLE s1.parent (a int);
> CREATE TABLE s2.child (b int) INHERITS (s1.parent);
>
> -- Initial data
> INSERT INTO s2.child VALUES (10, 20);
> INSERT INTO s1.parent VALUES (100);
>
> ### Test 1
> Create a publication that includes only schema s1:
> CREATE PUBLICATION pub1 FOR TABLES IN SCHEMA s1;
>
> On the subscriber, the initial synchronization gives:
> postgres=# SELECT * FROM s1.parent;
>   a
> -----
>  100
> (1 row)
>
> postgres=# SELECT * FROM s2.child;
>  a | b
> ---+---
> (0 rows)
>
> Here, s1.parent is included because it belongs to schema s1, which is
> part of the publication pub1. s2.child is not replicated because it
> belongs to schema s2, which is not part of the publication pub1.
>
> Similarly, in the proposed patch for the following scenario-1:
> CREATE PUBLICATION pub1 FOR TABLES IN SCHEMA s1 EXCEPT (TABLE s1.parent);
>
> We can exclude s1.parent. The resulting publication state would have
> s1.parent represented with prexcept = true, while s2.child would not
> be present in pg_publication_rel because schema s2 was not selected.

Yes, this looks like the obvious choice since the user included only
s1. But even though it's the obvious choice, it could be slightly
misleading because users expect all children to be excluded too
(default * behaviour for inherited tables), which isn't the case.

The behaviour you mentioned on HEAD does not resemble our case because
the user specified 'TABLES IN SCHEMA s1' which doesn't clarify the
expected behaviour when an inherited child table exists in another
schema. The more obvious choice seems to be including only the tables
from the schema as instructed by the user, and thus the behavior is
not misleading. However, in our case, the behaviour could be
misleading.

> I was not sure about the behavior when both schemas are explicitly
> selected in the following scenario-2:
> CREATE PUBLICATION pub1 FOR TABLES IN SCHEMA s1 EXCEPT (TABLE
> s1.parent), TABLES IN SCHEMA s2;

Ideally, this should result in an error: 'conflicting except'. We are
trying to exclude s1.parent and all its descendants explicitly through
the first using EXCEPT s1.parent* while we are trying to include
schema s2 and all its tables which include the excluded children. But
could it complicate implementation and understanding of behaviour? I
am thinking about it.

This is somewhat similar to case discussed in [1], where we concluded
that all partitions should also be excluded. But I am rethinking on
all these scenarios now wrt inherited tables. Parition and inherited
tables are different in a way that user may give direct instruction
for inherited tables by giving */ONLY for the depth of
inclusion/exclusion while that is not the case for paritions and thus
2 can not be compared directly.

[1]: https://www.postgresql.org/message-id/CABdArM4nVk-umQ_VXoGCrb7gQ_VcM5gHFcDOOa9EQbiUC-0EsA%40mail.gma...


thanks
Shveta






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-12 06:11  shveta malik <shveta.malik@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  0 siblings, 3 replies; 196+ messages in thread

From: shveta malik @ 2026-08-12 06:11 UTC (permalink / raw)
  To: vignesh C <vignesh21@gmail.com>; Nisha Moond <nisha.moond412@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; shveta malik <shveta.malik@gmail.com>

I thought some more. Please find my analysis and opinion on all
related scenarios:

Metadata:
schema s1:   parent
schema s2:    parition/child of parent.

Scenarios:
a) s1.s1.parent is a partitioned table, and its partitions live in
another schema. Or
b) s1.parent is a parent table, and its descendants/inherited tables
live in another schema.

~~

Now consider the exclusion cases:

Case 1: No contradiction in EXCEPT
-----------------------------------------
CREATE PUBLICATION pub1 FOR TABLES IN SCHEMA s1 EXCEPT (TABLE s1.parent*);

My opinion:
In both cases a) and b), s1.parent will be included in the
publication. Its partitions or descendants, however, will not be
included because they belong to another schema (s2), which is not
included in the publication. Thus, they are effectively excluded due
to the absence of a schema inclusion rule, rather than by the EXCEPT
clause.


Case 2: Indirect contradiction in EXCEPT
--------------------------------------------------------
CREATE PUBLICATION pub1 FOR TABLES IN SCHEMA s1 EXCEPT (TABLE
s1.parent*), TABLES IN SCHEMA s2;

The above command creates an indirect logical contradiction. The
child/partition is explicitly brought into the publication pool
through the schema inclusion rule (TABLES IN SCHEMA s2), while at the
same time being excluded by the recursive EXCEPT (TABLE s1.parent*)
clause of another schema. I believe this should result in the same
error that we have already concluded and implemented in the following
case:


Case 3: Direct contradiction in EXCEPT
--------------------------------------------------------
CREATE PUBLICATION pub1 FOR TABLES IN SCHEMA s1 EXCEPT (TABLE
s1.parent*), s2.partition/child;

It gives error as per current implementation. See [3].

~~

If we implement what I suggested above, Case 2's implementation for
partitions would be contrary to what we decided at [2] earlier for the
scenario at [1]. However, after reconsidering all scenarios, I feel
the new approach (suggested above) makes more sense and is also
consistent with Case 3. Case 2 and Case 3 are logically the same and
should have the same behaviour, IMO. Thoughts?

[1]: https://www.postgresql.org/message-id/CABdArM4nVk-umQ_VXoGCrb7gQ_VcM5gHFcDOOa9EQbiUC-0EsA%40mail.gma...
[2]: https://www.postgresql.org/message-id/CAA4eK1%2BNmQRjSHPLr0X8YBuC6joivFqgsY3_qJ5-RnuuwNGkRQ%40mail.g...

[3]: Case 3 tests:

CREATE SCHEMA s1;
CREATE SCHEMA s2;
--partition case
CREATE TABLE s1.parent (id int) PARTITION BY LIST (id);
CREATE TABLE s2.part PARTITION OF s1.parent FOR VALUES IN (1, 2, 3);

postgres=# CREATE PUBLICATION pub1 FOR TABLES IN SCHEMA s1 EXCEPT
(TABLE s1.parent), TABLE s2.part;
ERROR:  partition "s2.part" cannot be both published and excluded
DETAIL:  Partition root "s1.parent" is named in the publication's
EXCEPT clause for schema "s1".

--inheritance case
drop table s1.parent;
CREATE TABLE s1.parent (a int);
CREATE TABLE s2.child (b int) INHERITS (s1.parent);

postgres=# CREATE PUBLICATION pub1 FOR TABLES IN SCHEMA s1 EXCEPT
(TABLE s1.parent*), TABLE s2.child;
ERROR:  table "s2.child" cannot be both published and excluded

~~

Are there any other similar cases that need discussion along with the above?

thanks
Shveta






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-12 09:10  shveta malik <shveta.malik@gmail.com>
  parent: vignesh C <vignesh21@gmail.com>
  1 sibling, 1 reply; 196+ messages in thread

From: shveta malik @ 2026-08-12 09:10 UTC (permalink / raw)
  To: vignesh C <vignesh21@gmail.com>; +Cc: Nisha Moond <nisha.moond412@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; Peter Smith <smithpb2250@gmail.com>; shveta malik <shveta.malik@gmail.com>

On Tue, Aug 11, 2026 at 2:28 PM vignesh C <vignesh21@gmail.com> wrote:
>
>
> Apart from these, the rest of the comments are also fixed in the v26
> version attached.

Thanks Vignesh. A few comments on v26-0001:

1)

publication_add_relation() accepts 'if_not_exists' i.e. add the new
entry 'if already not present' else skip it (no error if it is a
duplicate addition). Most flows pass it as 'true'. The current code
skips raising error if if_not_exists=true and entry exists. It made
sense earlier, but in our implementation, I feel it should still raise
an error if entries are cross wired (i.e., if an exclusion is present
and we are trying to add it as an inclusion, or vice versa). The
'if_not_exists' based 'skip logic' should only be exercised if the
nature of existing entity is of same kind as user is trying to add.

Let me know if you have different understanding.

2)
ProcessSchemaExceptTables:

+ * Also rejects a schema being mentioned more than once with an EXCEPT
+ * clause, even if the EXCEPT clauses are identical — much like
+ * OpenTableList() rejects "FOR TABLE t1(a), t1(a)" despite the column
+ * lists matching. A schema can still be mentioned multiple times, just
+ * not more than once with EXCEPT.
+ *
+ * Qualify unqualified EXCEPT table names with the given schema (rejecting
+ * any explicitly qualified with a different schema), and append them to
+ * *except_pubtables.

We changed the order of comments above, but missed to change these:

'Also rejects a schema ' -> Reject a schema
Qualify unqualified -> 'Also qualify unqualified EXCEPT table..'


3)
CheckExceptNotInTableList:
+ * Both checks are performed here, on the lists supplied by the statement,
+ * because at this point the catalog cannot answer either question. The
+ * corresponding checks in publication_add_relation() and
+ * check_publication_add_relation() rely on pg_publication_rel entries and
+ * ancestor lookups, neither of which is sufficient in the cases below:

Since we have changed comment prior to it, this too needs to be
changed as 'Both checks' does not make much sense.

Suggestion:
Similar checks are present in publication_add_relation() and
check_publication_add_relation(), but they rely on pg_publication_rel
entries and ancestor lookups. Here, the checks are performed on the
object lists collected during the statement, as the catalog state is
not sufficient in the cases below:

thanks
Shveta






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-13 07:22  Peter Smith <smithpb2250@gmail.com>
  parent: vignesh C <vignesh21@gmail.com>
  1 sibling, 1 reply; 196+ messages in thread

From: Peter Smith @ 2026-08-13 07:22 UTC (permalink / raw)
  To: vignesh C <vignesh21@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Nisha Moond <nisha.moond412@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

Some review comments for v26*

======

//////////
Patch v26-0001
//////////

src/backend/commands/publicationcmds.c

ProcessSchemaExceptTables:

1.
+/*
+ * Also rejects a schema being mentioned more than once with an EXCEPT
+ * clause, even if the EXCEPT clauses are identical — much like
+ * OpenTableList() rejects "FOR TABLE t1(a), t1(a)" despite the column
+ * lists matching. A schema can still be mentioned multiple times, just
+ * not more than once with EXCEPT.
+ *
+ * Qualify unqualified EXCEPT table names with the given schema (rejecting
+ * any explicitly qualified with a different schema), and append them to
+ * *except_pubtables.
+ *
+ * schemaid: OID of the schema for this TABLES IN SCHEMA mention.
+ * except_tables: the EXCEPT list (or NIL) attached to this mention.
+ * pstate: parse state of the statement, used to report the error position of
+ * an offending EXCEPT entry.
+ * *schemas: accumulates all schema OIDs seen so far in this statement.
+ * *schemas_with_except: This is a subset of *schemas. Tracks which of
+ * the seen schemas of this statement had an EXCEPT clause.
+ * *except_pubtables: accumulates the (now schema-qualified) EXCEPT table
+ * entries across the whole statement.
+ */

Needs some adjustment. It doesn't make sense for the function comment
to start with "Also ..."

~~~

2.
+ * - CreatePublication() inserts the explicit tables and the EXCEPT tables in
+ *   a single command, and rows inserted by the current command are not
+ *   visible to later lookups within the same command.
+ *
+ * - In the partition case, the excluded root's row might not yet exist
+ *   because the root may be added to the EXCEPT list later. Detecting such
+ *   contradictions when adding the root to the EXCEPT clause would require
+ *   traversing downward through the partition hierarchy, whereas the
+ *   existing ancestor lookups only traverse upward from the relation being
+ *   added.

2a.
/, and rows inserted/, but rows inserted/

~

2b.
/In the partition case/For partitions/

AFAICT this case is referring to something like:  "FOR TABLE part,
TABLES IN SCHEMA EXCEPT (part_root)"

But, isn't that just a variation of the 1st case issue? e.g. where
table "part" is not yet visible for later lookup of "root", then you
wont be able to check integrity of the partition tree regardless of
the up/down traversal logic, so I wasn't sure why this 2nd case was
separately mentioned at all.

======

//////////
Patch v26-0004 (docs)
//////////

1.
+  <para>
+   Replace the schema list of <structname>sales_publication</structname> with
+   only schema <structname>sales</structname>, excluding only
+   <structname>sales.drafts</structname>. All other previously excluded tables
+   in schema <structname>sales</structname> are no longer excluded. Any schemas
+   previously in <structname>sales_publication</structname> are removed:
+<programlisting>
+ALTER PUBLICATION sales_publication SET TABLES IN SCHEMA sales EXCEPT
(TABLE drafts);
+</programlisting>
+  </para>

The last modification missed the point of my previous review comment.
My point was now that the first sentence is modified it should just
end with a colon (:), because and all the rest is redundant since IMO
it is just repeating the same.

e.g.

BEFORE
Replace the schema list of <structname>sales_publication</structname>
with only schema <structname>sales</structname>, excluding only
<structname>sales.drafts</structname>. All other previously excluded
tables in schema <structname>sales</structname> are no longer
excluded. Any schemas  previously in
<structname>sales_publication</structname> are removed:

SUGGESTION
Replace the schema list of <structname>sales_publication</structname>
with only schema <structname>sales</structname>, excluding only
<structname>sales.drafts</structname>:

======
Kind Regards,
Peter Smith.
Fujitsu Australia






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-13 09:41  Amit Kapila <amit.kapila16@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  2 siblings, 1 reply; 196+ messages in thread

From: Amit Kapila @ 2026-08-13 09:41 UTC (permalink / raw)
  To: shveta malik <shveta.malik@gmail.com>; +Cc: vignesh C <vignesh21@gmail.com>; Nisha Moond <nisha.moond412@gmail.com>; Peter Smith <smithpb2250@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Wed, Aug 12, 2026 at 11:42 AM shveta malik <shveta.malik@gmail.com> wrote:
>
> I thought some more. Please find my analysis and opinion on all
> related scenarios:
>
> Metadata:
> schema s1:   parent
> schema s2:    parition/child of parent.
>
> Scenarios:
> a) s1.s1.parent is a partitioned table, and its partitions live in
> another schema. Or
> b) s1.parent is a parent table, and its descendants/inherited tables
> live in another schema.
>
> ~~
>
> Now consider the exclusion cases:
>
> Case 1: No contradiction in EXCEPT
> -----------------------------------------
> CREATE PUBLICATION pub1 FOR TABLES IN SCHEMA s1 EXCEPT (TABLE s1.parent*);
>
> My opinion:
> In both cases a) and b), s1.parent will be included in the
> publication. Its partitions or descendants, however, will not be
> included because they belong to another schema (s2), which is not
> included in the publication. Thus, they are effectively excluded due
> to the absence of a schema inclusion rule, rather than by the EXCEPT
> clause.
>
>
> Case 2: Indirect contradiction in EXCEPT
> --------------------------------------------------------
> CREATE PUBLICATION pub1 FOR TABLES IN SCHEMA s1 EXCEPT (TABLE
> s1.parent*), TABLES IN SCHEMA s2;
>
> The above command creates an indirect logical contradiction. The
> child/partition is explicitly brought into the publication pool
> through the schema inclusion rule (TABLES IN SCHEMA s2), while at the
> same time being excluded by the recursive EXCEPT (TABLE s1.parent*)
> clause of another schema. I believe this should result in the same
> error that we have already concluded and implemented in the following
> case:
>
>
> Case 3: Direct contradiction in EXCEPT
> --------------------------------------------------------
> CREATE PUBLICATION pub1 FOR TABLES IN SCHEMA s1 EXCEPT (TABLE
> s1.parent*), s2.partition/child;
>
> It gives error as per current implementation. See [3].
>
> ~~
>
> If we implement what I suggested above, Case 2's implementation for
> partitions would be contrary to what we decided at [2] earlier for the
> scenario at [1]. However, after reconsidering all scenarios, I feel
> the new approach (suggested above) makes more sense and is also
> consistent with Case 3. Case 2 and Case 3 are logically the same and
> should have the same behaviour, IMO. Thoughts?
>

Though this will block the case where one has partition/inheritance
hierarchy across schema's especially if the user wants to exclude just
those partitions/inherited_tables and allow other tables from those
schemas, still I feel it is okay to be restrictive in the first
version of the feature for this case and follow what you are
proposing.

BTW, I have also considered diverging the behavior of partition and
inheritance tables for this case (such that for partitions, all
hierarchy to be excluded irrespective of the schema in which they are
and for inherit tables give error as you suggested) because inherit
tables could be excluded via following syntax:
CREATE PUBLICATION pub FOR
   TABLES IN SCHEMA s1 EXCEPT (TABLE s1.parent),
   TABLES IN SCHEMA s2 EXCEPT (TABLE s2.child);
But I feel this could even be done separately if there is a real need
in the field for such cases. So, let's follow consistency and
simplicity of behavior for both partition and inherited tables.

-- 
With Regards,
Amit Kapila.





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-13 09:53  shveta malik <shveta.malik@gmail.com>
  parent: Amit Kapila <amit.kapila16@gmail.com>
  0 siblings, 0 replies; 196+ messages in thread

From: shveta malik @ 2026-08-13 09:53 UTC (permalink / raw)
  To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: vignesh C <vignesh21@gmail.com>; Nisha Moond <nisha.moond412@gmail.com>; Peter Smith <smithpb2250@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; shveta malik <shveta.malik@gmail.com>

On Thu, Aug 13, 2026 at 3:11 PM Amit Kapila <amit.kapila16@gmail.com> wrote:
>
> On Wed, Aug 12, 2026 at 11:42 AM shveta malik <shveta.malik@gmail.com> wrote:
> >
> > I thought some more. Please find my analysis and opinion on all
> > related scenarios:
> >
> > Metadata:
> > schema s1:   parent
> > schema s2:    parition/child of parent.
> >
> > Scenarios:
> > a) s1.s1.parent is a partitioned table, and its partitions live in
> > another schema. Or
> > b) s1.parent is a parent table, and its descendants/inherited tables
> > live in another schema.
> >
> > ~~
> >
> > Now consider the exclusion cases:
> >
> > Case 1: No contradiction in EXCEPT
> > -----------------------------------------
> > CREATE PUBLICATION pub1 FOR TABLES IN SCHEMA s1 EXCEPT (TABLE s1.parent*);
> >
> > My opinion:
> > In both cases a) and b), s1.parent will be included in the
> > publication. Its partitions or descendants, however, will not be
> > included because they belong to another schema (s2), which is not
> > included in the publication. Thus, they are effectively excluded due
> > to the absence of a schema inclusion rule, rather than by the EXCEPT
> > clause.
> >
> >
> > Case 2: Indirect contradiction in EXCEPT
> > --------------------------------------------------------
> > CREATE PUBLICATION pub1 FOR TABLES IN SCHEMA s1 EXCEPT (TABLE
> > s1.parent*), TABLES IN SCHEMA s2;
> >
> > The above command creates an indirect logical contradiction. The
> > child/partition is explicitly brought into the publication pool
> > through the schema inclusion rule (TABLES IN SCHEMA s2), while at the
> > same time being excluded by the recursive EXCEPT (TABLE s1.parent*)
> > clause of another schema. I believe this should result in the same
> > error that we have already concluded and implemented in the following
> > case:
> >
> >
> > Case 3: Direct contradiction in EXCEPT
> > --------------------------------------------------------
> > CREATE PUBLICATION pub1 FOR TABLES IN SCHEMA s1 EXCEPT (TABLE
> > s1.parent*), s2.partition/child;
> >
> > It gives error as per current implementation. See [3].
> >
> > ~~
> >
> > If we implement what I suggested above, Case 2's implementation for
> > partitions would be contrary to what we decided at [2] earlier for the
> > scenario at [1]. However, after reconsidering all scenarios, I feel
> > the new approach (suggested above) makes more sense and is also
> > consistent with Case 3. Case 2 and Case 3 are logically the same and
> > should have the same behaviour, IMO. Thoughts?
> >
>
> Though this will block the case where one has partition/inheritance
> hierarchy across schema's especially if the user wants to exclude just
> those partitions/inherited_tables and allow other tables from those
> schemas, still I feel it is okay to be restrictive in the first
> version of the feature for this case and follow what you are
> proposing.

Okay.

> BTW, I have also considered diverging the behavior of partition and
> inheritance tables for this case (such that for partitions, all
> hierarchy to be excluded irrespective of the schema in which they are
> and for inherit tables give error as you suggested) because inherit
> tables could be excluded via following syntax:
> CREATE PUBLICATION pub FOR
>    TABLES IN SCHEMA s1 EXCEPT (TABLE s1.parent),
>    TABLES IN SCHEMA s2 EXCEPT (TABLE s2.child);
> But I feel this could even be done separately if there is a real need
> in the field for such cases. So, let's follow consistency and
> simplicity of behavior for both partition and inherited tables.
>

I had also considered having partitions and inherited tables behave
differently as they are logically distinct. But it may cause some
confusion in first version and thus as you suggested it will be better
to stick to consistent behaviour in version1 and then decide based on
user's feedback.

thanks
Shveta






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-14 05:58  shveta malik <shveta.malik@gmail.com>
  parent: Peter Smith <smithpb2250@gmail.com>
  0 siblings, 2 replies; 196+ messages in thread

From: shveta malik @ 2026-08-14 05:58 UTC (permalink / raw)
  To: Peter Smith <smithpb2250@gmail.com>; +Cc: vignesh C <vignesh21@gmail.com>; Nisha Moond <nisha.moond412@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; shveta malik <shveta.malik@gmail.com>

On Thu, Aug 13, 2026 at 12:52 PM Peter Smith <smithpb2250@gmail.com> wrote:
>
>
> 2b.
> /In the partition case/For partitions/
>
> AFAICT this case is referring to something like:  "FOR TABLE part,
> TABLES IN SCHEMA EXCEPT (part_root)"
>
> But, isn't that just a variation of the 1st case issue? e.g. where
> table "part" is not yet visible for later lookup of "root", then you
> wont be able to check integrity of the partition tree regardless of
> the up/down traversal logic, so I wasn't sure why this 2nd case was
> separately mentioned at all.

The second point is different from the first. Consider this case:

CREATE PUBLICATION pub1 FOR s2.tab_part;
ALTER PUBLICATION pub1 ADD TABLES IN SCHEMA s2 EXCEPT (TABLE tab_root);

Here, the partition entry in pg_publication_rel is visible to the
second command in publication_add_relation() and in
check_publication_add_relation(). But the checks there are not
sufficient to identify the error. If we try to detect the error while
adding tab_root in publication_add_relation(),
we would need to perform a full descendant search to determine whether
any of its descendants are already present in pg_publication_rel. This
downward traversal is what we are trying to avoid in
publication_add_relation(). Geenrally we rely on ancestor-lookup and
we want to stick to that instead of introducing a new logic.
Thus the logic in CheckExceptNotInTableList() is needed here. It reads
all explicitly added entries from pg_publication_rel, looks up their
ancestors to find the root, and checks the EXCEPT entries against that
root.

This is my understanding, let's wait for Nisha's comments as well.

I feel the comment about the second case should be moved to patch002,
where it actually makes sense and explains why it is needed even after
point 1.

thanks
Shveta






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-14 06:55  Peter Smith <smithpb2250@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  1 sibling, 2 replies; 196+ messages in thread

From: Peter Smith @ 2026-08-14 06:55 UTC (permalink / raw)
  To: shveta malik <shveta.malik@gmail.com>; +Cc: vignesh C <vignesh21@gmail.com>; Nisha Moond <nisha.moond412@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Fri, Aug 14, 2026 at 3:59 PM shveta malik <shveta.malik@gmail.com> wrote:
>
> On Thu, Aug 13, 2026 at 12:52 PM Peter Smith <smithpb2250@gmail.com> wrote:
> >
> >
> > 2b.
> > /In the partition case/For partitions/
> >
> > AFAICT this case is referring to something like:  "FOR TABLE part,
> > TABLES IN SCHEMA EXCEPT (part_root)"
> >
> > But, isn't that just a variation of the 1st case issue? e.g. where
> > table "part" is not yet visible for later lookup of "root", then you
> > wont be able to check integrity of the partition tree regardless of
> > the up/down traversal logic, so I wasn't sure why this 2nd case was
> > separately mentioned at all.
>
> The second point is different from the first. Consider this case:
>
> CREATE PUBLICATION pub1 FOR s2.tab_part;
> ALTER PUBLICATION pub1 ADD TABLES IN SCHEMA s2 EXCEPT (TABLE tab_root);
>
> Here, the partition entry in pg_publication_rel is visible to the
> second command in publication_add_relation() and in
> check_publication_add_relation(). But the checks there are not
> sufficient to identify the error. If we try to detect the error while
> adding tab_root in publication_add_relation(),
> we would need to perform a full descendant search to determine whether
> any of its descendants are already present in pg_publication_rel. This
> downward traversal is what we are trying to avoid in
> publication_add_relation(). Geenrally we rely on ancestor-lookup and
> we want to stick to that instead of introducing a new logic.
> Thus the logic in CheckExceptNotInTableList() is needed here. It reads
> all explicitly added entries from pg_publication_rel, looks up their
> ancestors to find the root, and checks the EXCEPT entries against that
> root.
>
> This is my understanding, let's wait for Nisha's comments as well.
>

Shveta, thanks for the explanation.

In hindsight, my confusion was due to the comment wording -- the 1st
case was referring to "a single command", and the 2nd case just said,
"root may be added to the EXCEPT list later."....
I misinterpreted "later" as meaning later in the *same* command, like:
CREATE PUBLICATION pub1 FOR TABLE s2.tab_part, TABLES IN SHEMA s2
EXCEPT(TABLE tab_root);
which is entirely a different horse....

Perhaps the comments for these tricky cases should include tiny SQL
examples (just like you wrote) to clarify exactly what the comment is
trying to say.

======
Kind Regards,
Peter Smith.
Fujitsu Australia






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-14 10:22  shveta malik <shveta.malik@gmail.com>
  parent: Peter Smith <smithpb2250@gmail.com>
  1 sibling, 0 replies; 196+ messages in thread

From: shveta malik @ 2026-08-14 10:22 UTC (permalink / raw)
  To: Peter Smith <smithpb2250@gmail.com>; +Cc: vignesh C <vignesh21@gmail.com>; Nisha Moond <nisha.moond412@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; shveta malik <shveta.malik@gmail.com>

On Fri, Aug 14, 2026 at 12:25 PM Peter Smith <smithpb2250@gmail.com> wrote:
>
> On Fri, Aug 14, 2026 at 3:59 PM shveta malik <shveta.malik@gmail.com> wrote:
> >
> > On Thu, Aug 13, 2026 at 12:52 PM Peter Smith <smithpb2250@gmail.com> wrote:
> > >
> > >
> > > 2b.
> > > /In the partition case/For partitions/
> > >
> > > AFAICT this case is referring to something like:  "FOR TABLE part,
> > > TABLES IN SCHEMA EXCEPT (part_root)"
> > >
> > > But, isn't that just a variation of the 1st case issue? e.g. where
> > > table "part" is not yet visible for later lookup of "root", then you
> > > wont be able to check integrity of the partition tree regardless of
> > > the up/down traversal logic, so I wasn't sure why this 2nd case was
> > > separately mentioned at all.
> >
> > The second point is different from the first. Consider this case:
> >
> > CREATE PUBLICATION pub1 FOR s2.tab_part;
> > ALTER PUBLICATION pub1 ADD TABLES IN SCHEMA s2 EXCEPT (TABLE tab_root);
> >
> > Here, the partition entry in pg_publication_rel is visible to the
> > second command in publication_add_relation() and in
> > check_publication_add_relation(). But the checks there are not
> > sufficient to identify the error. If we try to detect the error while
> > adding tab_root in publication_add_relation(),
> > we would need to perform a full descendant search to determine whether
> > any of its descendants are already present in pg_publication_rel. This
> > downward traversal is what we are trying to avoid in
> > publication_add_relation(). Geenrally we rely on ancestor-lookup and
> > we want to stick to that instead of introducing a new logic.
> > Thus the logic in CheckExceptNotInTableList() is needed here. It reads
> > all explicitly added entries from pg_publication_rel, looks up their
> > ancestors to find the root, and checks the EXCEPT entries against that
> > root.
> >
> > This is my understanding, let's wait for Nisha's comments as well.
> >
>
> Shveta, thanks for the explanation.
>
> In hindsight, my confusion was due to the comment wording -- the 1st
> case was referring to "a single command", and the 2nd case just said,
> "root may be added to the EXCEPT list later."....
> I misinterpreted "later" as meaning later in the *same* command, like:
> CREATE PUBLICATION pub1 FOR TABLE s2.tab_part, TABLES IN SHEMA s2
> EXCEPT(TABLE tab_root);
> which is entirely a different horse....
>
> Perhaps the comments for these tricky cases should include tiny SQL
> examples (just like you wrote) to clarify exactly what the comment is
> trying to say.
>

Yes, that makes sense. Otherwise, reviewers might have doubts about
it. It is a somewhat tricky comment.

thanks
Shveta






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-14 14:15  vignesh C <vignesh21@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  2 siblings, 1 reply; 196+ messages in thread

From: vignesh C @ 2026-08-14 14:15 UTC (permalink / raw)
  To: shveta malik <shveta.malik@gmail.com>; +Cc: Nisha Moond <nisha.moond412@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Peter Smith <smithpb2250@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Wed, 12 Aug 2026 at 11:42, shveta malik <shveta.malik@gmail.com> wrote:
>
> I thought some more. Please find my analysis and opinion on all
> related scenarios:
>
> Metadata:
> schema s1:   parent
> schema s2:    parition/child of parent.
>
> Scenarios:
> a) s1.s1.parent is a partitioned table, and its partitions live in
> another schema. Or
> b) s1.parent is a parent table, and its descendants/inherited tables
> live in another schema.
>
> ~~
>
> Now consider the exclusion cases:
>
> Case 1: No contradiction in EXCEPT
> -----------------------------------------
> CREATE PUBLICATION pub1 FOR TABLES IN SCHEMA s1 EXCEPT (TABLE s1.parent*);
>
> My opinion:
> In both cases a) and b), s1.parent will be included in the
> publication. Its partitions or descendants, however, will not be
> included because they belong to another schema (s2), which is not
> included in the publication. Thus, they are effectively excluded due
> to the absence of a schema inclusion rule, rather than by the EXCEPT
> clause.
>
>
> Case 2: Indirect contradiction in EXCEPT
> --------------------------------------------------------
> CREATE PUBLICATION pub1 FOR TABLES IN SCHEMA s1 EXCEPT (TABLE
> s1.parent*), TABLES IN SCHEMA s2;
>
> The above command creates an indirect logical contradiction. The
> child/partition is explicitly brought into the publication pool
> through the schema inclusion rule (TABLES IN SCHEMA s2), while at the
> same time being excluded by the recursive EXCEPT (TABLE s1.parent*)
> clause of another schema. I believe this should result in the same
> error that we have already concluded and implemented in the following
> case:

Thanks for the feedback. I have made the changes to handle inheritance
tables. I will address the partition table case in a follow-up patch.
The attached v27 patch has the changes for the same.

Regards,
Vignesh

Attachments: download all (4 files, .tar.gz)

v27-0001-Support-EXCEPT-clause-for-schema-level-publicati.patch (application/octet-stream, 106.6K) download From fd2804a83105c4d5278e70fe3515b712b724d01e Mon Sep 17 00:00:00 2001 From: Vignesh C <c_vigneshwaran@apple.com> Date: Mon, 10 Aug 2026 21:22:15 +0530 Subject: [PATCH v27 1/4] Support EXCEPT clause for schema-level publications Extend table exclusion support in publications to allow specific tables to be excluded from schema-level publications using an EXCEPT clause in CREATE PUBLICATION. Supported syntax: CREATE PUBLICATION pub FOR TABLES IN SCHEMA s EXCEPT (TABLE t1,...); This reuses the existing opt_pub_except_clause grammar and stores excluded tables as pg_publication_rel entries with prexcept = true, requiring no catalog changes. NOTES - Each EXCEPT clause applies only to its own schema; cross-schema references are rejected. - A schema may appear only once with an EXCEPT clause. - A table cannot be both explicitly published and excluded in the same statement. - Only partition roots may be excluded. Excluding a root excludes the entire partition tree, including partitions in other published schemas. Individual partitions cannot be added while their root is excluded, and ATTACH PARTITION is rejected if the attached table is excluded. - ALTER TABLE ... SET SCHEMA removes schema-scoped exclusions, matching existing schema-publication behavior. - psql describe output and tab completion are updated to support the new syntax. --- src/backend/catalog/pg_publication.c | 274 +++++++++++--- src/backend/commands/publicationcmds.c | 385 +++++++++++++++++++- src/backend/commands/tablecmds.c | 24 +- src/backend/parser/gram.y | 27 +- src/backend/replication/pgoutput/pgoutput.c | 37 +- src/backend/utils/cache/relcache.c | 26 +- src/bin/psql/describe.c | 44 ++- src/bin/psql/tab-complete.in.c | 35 +- src/include/catalog/pg_publication.h | 3 + src/include/commands/publicationcmds.h | 2 + src/include/nodes/parsenodes.h | 5 + src/test/regress/expected/publication.out | 384 ++++++++++++++++++- src/test/regress/sql/publication.sql | 236 +++++++++++- src/test/subscription/t/037_except.pl | 261 ++++++++++++- 14 files changed, 1647 insertions(+), 96 deletions(-) diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index 12af7d15536..81e4166cfee 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -54,7 +54,7 @@ typedef struct * error if not. */ static void -check_publication_add_relation(PublicationRelInfo *pri) +check_publication_add_relation(PublicationRelInfo *pri, Oid pubid) { Relation targetrel = pri->relation; const char *relname; @@ -71,12 +71,51 @@ check_publication_add_relation(PublicationRelInfo *pri) errormsg = gettext_noop("cannot add relation \"%s\" to publication"); } - /* If in EXCEPT clause, must be root partitioned table */ - if (pri->except && targetrel->rd_rel->relispartition) - ereport(ERROR, - (errcode(ERRCODE_INVALID_PARAMETER_VALUE), - errmsg(errormsg, relname), - errdetail("This operation is not supported for individual partitions."))); + /* + * A partition cannot be added to a publication if its partition root is + * excluded by the publication. We follow the rule that excluding a + * partition root means that the entire partition tree is excluded. Thus, + * check whether the root is in the EXCEPT clause and reject adding the + * individual partition to the publication. + */ + if (targetrel->rd_rel->relispartition) + { + List *ancestors; + + if (pri->except) + { + /* If in EXCEPT clause, must be root partitioned table */ + ereport(ERROR, + (errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg(errormsg, relname), + errdetail("This operation is not supported for individual partitions."))); + } + + /* + * ancestors is NIL for a partition with a pending DETACH + * CONCURRENTLY, in which case there is no root to check. + */ + ancestors = get_partition_ancestors(RelationGetRelid(targetrel)); + if (ancestors != NIL) + { + Oid root = llast_oid(ancestors); + bool root_except; + + if (CheckPublicationRelEntry(pubid, root, &root_except) && root_except) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("cannot add partition \"%s\" to publication \"%s\"", + RelationGetQualifiedRelationName(targetrel), + get_publication_name(pubid, false)), + errdetail("Partition root \"%s\" is named in the publication's EXCEPT clause for schema \"%s\".", + quote_qualified_identifier(get_namespace_name(get_rel_namespace(root)), + get_rel_name(root)), + get_namespace_name(get_rel_namespace(root))), + errhint("Change the EXCEPT clause using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT.")); + } + + list_free(ancestors); + } /* Must be a regular or partitioned table */ if (RelationGetForm(targetrel)->relkind != RELKIND_RELATION && @@ -320,8 +359,7 @@ is_schema_publication(Oid pubid) } /* - * Returns true if the publication has explicitly included relation (i.e., - * not marked as EXCEPT). + * Returns true if the publication has a FOR TABLE clause. */ bool is_table_publication(Oid pubid) @@ -341,19 +379,23 @@ is_table_publication(Oid pubid) scan = systable_beginscan(pubrelsrel, PublicationRelPrpubidIndexId, true, NULL, 1, &scankey); - tup = systable_getnext(scan); - if (HeapTupleIsValid(tup)) - { - Form_pg_publication_rel pubrel; - - pubrel = (Form_pg_publication_rel) GETSTRUCT(tup); - /* - * For any publication, pg_publication_rel contains either only EXCEPT - * entries or only explicitly included tables. Therefore, examining - * the first tuple is sufficient to determine table inclusion. - */ - result = !pubrel->prexcept; + /* + * A publication can have both explicitly included (prexcept = false) and + * EXCEPT (prexcept = true) rows for the same pubid. For example: + * + * CREATE PUBLICATION pub1 FOR TABLE s1.t1, TABLES IN SCHEMA s2 EXCEPT + * (TABLE s2.t1); + * + * Scan until we find an explicitly included row. + */ + while (HeapTupleIsValid(tup = systable_getnext(scan))) + { + if (!((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept) + { + result = true; + break; + } } systable_endscan(scan); @@ -362,6 +404,27 @@ is_table_publication(Oid pubid) return result; } +/* + * Check whether a pg_publication_rel row exists for (pubid, relid); if so, + * set *is_except to its prexcept flag. + */ +bool +CheckPublicationRelEntry(Oid pubid, Oid relid, bool *is_except) +{ + HeapTuple tup; + + tup = SearchSysCache2(PUBLICATIONRELMAP, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (!HeapTupleIsValid(tup)) + return false; + + *is_except = ((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept; + ReleaseSysCache(tup); + + return true; +} + /* * Returns true if the relation has column list associated with the * publication, false otherwise. @@ -457,11 +520,26 @@ GetPubPartitionOptionRelations(List *result, PublicationPartOpt pub_partopt, * ancestor is at the end of the list. */ Oid -GetTopMostAncestorInPublication(Oid puboid, List *ancestors, int *ancestor_level) +GetTopMostAncestorInPublication(Oid puboid, List *ancestors, + int *ancestor_level) { ListCell *lc; Oid topmost_relid = InvalidOid; int level = 0; + bool root_except; + + if (ancestors == NIL) + return InvalidOid; + + /* + * If the partition root is excluded from this publication via an EXCEPT + * clause, the partition is not published through this publication, so + * return InvalidOid. Since only partition roots can appear in an EXCEPT + * clause, the root is the only ancestor worth a catalog lookup. + */ + if (CheckPublicationRelEntry(puboid, llast_oid(ancestors), &root_except) && + root_except) + return InvalidOid; /* * Find the "topmost" ancestor that is in this publication. @@ -548,6 +626,7 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, List *relids = NIL; int i; bool inval_except_table; + bool is_except; rel = table_open(PublicationRelRelationId, RowExclusiveLock); @@ -556,21 +635,46 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, * duplicates, it's here just to provide nicer error message in common * case. The real protection is the unique key on the catalog. */ - if (SearchSysCacheExists2(PUBLICATIONRELMAP, ObjectIdGetDatum(relid), - ObjectIdGetDatum(pubid))) + if (CheckPublicationRelEntry(pubid, relid, &is_except)) { table_close(rel, RowExclusiveLock); - if (if_not_exists) + /* + * if_not_exists asks us to skip an entry that is already present. An + * existing entry of the opposite kind is not the entry the caller + * asked for, though: skipping it would silently leave the relation + * excluded when the caller wanted it published, or published when the + * caller wanted it excluded. So only skip when the existing entry is + * of the same kind, and report the conflict otherwise. + */ + if (if_not_exists && is_except == pri->except) return InvalidObjectAddress; - ereport(ERROR, - (errcode(ERRCODE_DUPLICATE_OBJECT), - errmsg("relation \"%s\" is already a member of publication \"%s\"", - RelationGetRelationName(targetrel), pub->name))); + if (is_except) + ereport(ERROR, + (errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("cannot add table \"%s\" to publication \"%s\"", + RelationGetQualifiedRelationName(targetrel), + pub->name), + errdetail("The table is named in the publication's EXCEPT clause for schema \"%s\".", + get_namespace_name(RelationGetNamespace(targetrel))), + errhint("Change the EXCEPT clause using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT."))); + else if (pri->except) + ereport(ERROR, + (errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("cannot exclude table \"%s\" from publication \"%s\"", + RelationGetQualifiedRelationName(targetrel), + pub->name), + errdetail("The table is a member of the publication."), + errhint("Remove the table from the publication using ALTER PUBLICATION ... DROP TABLE."))); + else + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("relation \"%s\" is already a member of publication \"%s\"", + RelationGetRelationName(targetrel), pub->name))); } - check_publication_add_relation(pri); + check_publication_add_relation(pri, pubid); /* Validate and translate column names into a Bitmapset of attnums. */ attnums = pub_collist_validate(pri->relation, pri->columns); @@ -996,16 +1100,36 @@ GetIncludedPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) * Gets list of table oids that were specified in the EXCEPT clause for a * publication. * - * This should only be used FOR ALL TABLES publications. + * This is used for FOR ALL TABLES and FOR TABLES IN SCHEMA publications, + * both of which support EXCEPT TABLE. */ List * GetExcludedPublicationTables(Oid pubid, PublicationPartOpt pub_partopt) { - Assert(GetPublication(pubid)->alltables); + Assert(GetPublication(pubid)->alltables || is_schema_publication(pubid)); return get_publication_relations(pubid, pub_partopt, true); } +/* + * Gets list of relation oids associated with a publication, covering both + * explicitly included relations and relations named in an EXCEPT clause. + * + * This is used by ALTER PUBLICATION ... SET to replaces a publication's entire + * relation list. + */ +List * +GetPublicationRelationsOfAnyKind(Oid pubid, PublicationPartOpt pub_partopt) +{ + List *result; + + result = get_publication_relations(pubid, pub_partopt, false); + + return list_concat_unique_oid(result, + get_publication_relations(pubid, pub_partopt, + true)); +} + /* * Gets list of publication oids for publications marked as FOR ALL TABLES. */ @@ -1246,22 +1370,63 @@ GetSchemaPublicationRelations(Oid schemaid, PublicationPartOpt pub_partopt) /* * Gets the list of all relations published by FOR TABLES IN SCHEMA - * publication. + * publication, excluding any tables listed in EXCEPT clauses. */ List * GetAllSchemaPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) { List *result = NIL; List *pubschemalist = GetPublicationSchemas(pubid); + List *except_relids = NIL; ListCell *cell; + /* get the list of tables excluded via EXCEPT TABLE for this publication */ + if (pubschemalist != NIL) + except_relids = GetExcludedPublicationTables(pubid, pub_partopt); + foreach(cell, pubschemalist) { Oid schemaid = lfirst_oid(cell); List *schemaRels = NIL; schemaRels = GetSchemaPublicationRelations(schemaid, pub_partopt); - result = list_concat(result, schemaRels); + + if (except_relids != NIL) + { + /* filter out any tables that appear in the EXCEPT list */ + foreach_oid(relid, schemaRels) + { + bool excluded = list_member_oid(except_relids, relid); + + /* + * A partition whose root is excluded from the publication is + * also excluded, even if the partition itself lives in a + * different (included) schema. Only the topmost root of a + * partition hierarchy can ever appear in EXCEPT (see + * check_publication_add_relation()), so it's enough to check + * the last element of the ancestors list, rather than walking + * the whole chain. + */ + if (!excluded && get_rel_relispartition(relid)) + { + List *ancestors = get_partition_ancestors(relid); + + if (ancestors != NIL) + { + excluded = list_member_oid(except_relids, + llast_oid(ancestors)); + list_free(ancestors); + } + } + + if (!excluded) + result = lappend_oid(result, relid); + } + + list_free(schemaRels); + } + else + result = list_concat(result, schemaRels); } return result; @@ -1338,6 +1503,7 @@ is_table_publishable_in_publication(Oid relid, Publication *pub) { bool relispartition; List *ancestors = NIL; + bool is_except; /* * For non-pubviaroot publications, a partitioned table is never the @@ -1385,6 +1551,10 @@ is_table_publishable_in_publication(Oid relid, Publication *pub) */ /* + * If the partition root is excluded via the EXCEPT clause, the partition + * is never considered to be published through this publication. Check + * this before checking whether an ancestor is published. + * * If an ancestor is published, the partition's status depends on * publish_via_partition_root value. * @@ -1394,20 +1564,38 @@ is_table_publishable_in_publication(Oid relid, Publication *pub) * If it's false, the partition is covered by its ancestor's presence in * the publication, it should be included (return true). */ - if (relispartition && - OidIsValid(GetTopMostAncestorInPublication(pub->oid, ancestors, NULL))) - return !pub->pubviaroot; + if (relispartition) + { + /* + * ancestors can be NIL for a partition whose DETACH ... CONCURRENTLY + * is pending, in which case there is no ancestor to check. + */ + if (ancestors != NIL && + CheckPublicationRelEntry(pub->oid, llast_oid(ancestors), &is_except) && + is_except) + return false; + + if (OidIsValid(GetTopMostAncestorInPublication(pub->oid, ancestors, NULL))) + return !pub->pubviaroot; + } /* * Check whether the table is explicitly published via pg_publication_rel * or pg_publication_namespace. + * + * A pg_publication_rel row with prexcept=true means the table is + * explicitly excluded via EXCEPT and must not be reported as published, + * even if its schema is otherwise included. A row with prexcept=false + * means it is explicitly included. If no pg_publication_rel row exists, + * the table is published iff its schema appears in + * pg_publication_namespace. */ - return (SearchSysCacheExists2(PUBLICATIONRELMAP, - ObjectIdGetDatum(relid), - ObjectIdGetDatum(pub->oid)) || - SearchSysCacheExists2(PUBLICATIONNAMESPACEMAP, - ObjectIdGetDatum(get_rel_namespace(relid)), - ObjectIdGetDatum(pub->oid))); + if (CheckPublicationRelEntry(pub->oid, relid, &is_except)) + return !is_except; + else + return SearchSysCacheExists2(PUBLICATIONNAMESPACEMAP, + ObjectIdGetDatum(get_rel_namespace(relid)), + ObjectIdGetDatum(pub->oid)); } /* diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 96838730fe1..77a829bc1bd 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -22,6 +22,7 @@ #include "catalog/namespace.h" #include "catalog/objectaccess.h" #include "catalog/objectaddress.h" +#include "catalog/partition.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" #include "catalog/pg_namespace.h" @@ -61,7 +62,7 @@ typedef struct rf_context Oid parentid; /* relid of the parent relation */ } rf_context; -static List *OpenTableList(List *tables); +static List *OpenTableList(List *tables, List **cross_schema_children); static void CloseTableList(List *rels); static void LockSchemaList(List *schemalist); static void PublicationAddTables(Oid pubid, List *rels, bool if_not_exists, @@ -71,6 +72,16 @@ static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); static char defGetGeneratedColsOption(DefElem *def); +static void CheckExceptNotInTableList(List *except_rels, + List *cross_schema_children, + List *explicitrelids); +static void CheckExceptChildNotInSchemaList(List *cross_schema_children, + List *schemaidlist, + List *except_rels); +static void ProcessSchemaExceptTables(Oid schemaid, List *except_tables, + ParseState *pstate, List **schemas, + List **schemas_with_except, + List **except_pubtables); static void @@ -175,16 +186,93 @@ parse_publication_options(ParseState *pstate, } } +/* + * Reject a schema being mentioned more than once with an EXCEPT clause, even + * if the EXCEPT clauses are identical — much like OpenTableList() rejects + * "FOR TABLE t1(a), t1(a)" despite the column lists matching. A schema can + * still be mentioned multiple times, just not more than once with EXCEPT. + * + * Also qualify unqualified EXCEPT table names with the given schema (rejecting + * any explicitly qualified with a different schema), and append them to + * *except_pubtables. + * + * schemaid: OID of the schema for this TABLES IN SCHEMA mention. + * except_tables: the EXCEPT list (or NIL) attached to this mention. + * pstate: parse state of the statement, used to report the error position of + * an offending EXCEPT entry. + * *schemas: accumulates all schema OIDs seen so far in this statement. + * *schemas_with_except: This is a subset of *schemas. Tracks which of + * the seen schemas of this statement had an EXCEPT clause. + * *except_pubtables: accumulates the (now schema-qualified) EXCEPT table + * entries across the whole statement. + */ +static void +ProcessSchemaExceptTables(Oid schemaid, List *except_tables, + ParseState *pstate, List **schemas, + List **schemas_with_except, List **except_pubtables) +{ + char *schema_name = get_namespace_name(schemaid); + bool schema_has_except = (except_tables != NIL); + + /* + * A repeating schema is only a problem if this mention has EXCEPT, or an + * earlier mention of the same schema did. + */ + if (list_member_oid(*schemas, schemaid)) + { + if (schema_has_except || + list_member_oid(*schemas_with_except, schemaid)) + ereport(ERROR, + errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("conflicting or redundant EXCEPT clauses for schema \"%s\"", + schema_name)); + } + + if (schema_has_except) + *schemas_with_except = lappend_oid(*schemas_with_except, schemaid); + + /* Filter out duplicates if the user specifies "sch1, sch1" */ + *schemas = list_append_unique_oid(*schemas, schemaid); + + if (!schema_has_except) + return; + + foreach_ptr(PublicationObjSpec, eobj, except_tables) + { + RangeVar *relation = eobj->pubtable->relation; + + if (relation->schemaname == NULL) + relation->schemaname = schema_name; + else if (strcmp(relation->schemaname, schema_name) != 0) + ereport(ERROR, + errcode(ERRCODE_INVALID_OBJECT_DEFINITION), + errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", + quote_qualified_identifier(relation->schemaname, relation->relname), + schema_name), + parser_errposition(pstate, eobj->location)); + + /* + * Remember that this EXCEPT entry is associated with a schema. This is + * used by OpenTableList() to skip inheritance children outside that + * schema. + */ + eobj->pubtable->except_in_schema = true; + + *except_pubtables = lappend(*except_pubtables, eobj->pubtable); + } +} + /* * Convert the PublicationObjSpecType list into schema oid list and * PublicationTable list. */ static void ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, - List **rels, List **exceptrels, List **schemas) + List **rels, List **except_pubtables, List **schemas) { ListCell *cell; PublicationObjSpec *pubobj; + List *schemas_with_except = NIL; if (!pubobjspec_list) return; @@ -200,7 +288,7 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, { case PUBLICATIONOBJ_EXCEPT_TABLE: pubobj->pubtable->except = true; - *exceptrels = lappend(*exceptrels, pubobj->pubtable); + *except_pubtables = lappend(*except_pubtables, pubobj->pubtable); break; case PUBLICATIONOBJ_TABLE: pubobj->pubtable->except = false; @@ -209,8 +297,10 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, case PUBLICATIONOBJ_TABLES_IN_SCHEMA: schemaid = get_namespace_oid(pubobj->name, false); - /* Filter out duplicates if user specifies "sch1, sch1" */ - *schemas = list_append_unique_oid(*schemas, schemaid); + ProcessSchemaExceptTables(schemaid, pubobj->except_tables, + pstate, schemas, + &schemas_with_except, + except_pubtables); break; case PUBLICATIONOBJ_TABLES_IN_CUR_SCHEMA: search_path = fetch_search_path(false); @@ -222,8 +312,10 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, schemaid = linitial_oid(search_path); list_free(search_path); - /* Filter out duplicates if user specifies "sch1, sch1" */ - *schemas = list_append_unique_oid(*schemas, schemaid); + ProcessSchemaExceptTables(schemaid, pubobj->except_tables, + pstate, schemas, + &schemas_with_except, + except_pubtables); break; default: /* shouldn't happen */ @@ -770,6 +862,133 @@ TransformPubWhereClauses(List *tables, const char *queryString, } } +/* + * Check that a table is not both excluded and published in the same DDL. + * + * Similar checks are present in publication_add_relation() and + * check_publication_add_relation(), but they rely on pg_publication_rel + * entries and ancestor lookups. Here, the checks are performed on the + * object lists collected during the statement, as the catalog state is + * not sufficient in the cases below: + * + * - CreatePublication() inserts the explicit tables and the EXCEPT tables in + * a single command, but rows inserted by the current command are not + * visible to later lookups within the same command. + * + * - For partitions, the excluded root's row might not yet exist because the + * root may be added to the EXCEPT list later. Detecting such contradictions + * when adding the root to the EXCEPT clause would require traversing + * downward through the partition hierarchy, whereas the existing ancestor + * lookups only traverse upward from the relation being added. + */ +static void +CheckExceptNotInTableList(List *except_rels, List *cross_schema_children, + List *explicitrelids) +{ + foreach_oid(explicitrelid, explicitrelids) + { + Oid root = InvalidOid; + + if (get_rel_relispartition(explicitrelid)) + { + List *ancestors = get_partition_ancestors(explicitrelid); + + /* + * ancestors is NIL for a partition with a pending DETACH + * CONCURRENTLY. + */ + if (ancestors != NIL) + root = llast_oid(ancestors); + list_free(ancestors); + } + + foreach_ptr(PublicationRelInfo, pri, except_rels) + { + Oid exceptrelid = RelationGetRelid(pri->relation); + + if (exceptrelid == explicitrelid) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" cannot be both published and excluded", + RelationGetQualifiedRelationName(pri->relation))); + + if (OidIsValid(root) && exceptrelid == root) + ereport(ERROR, + (errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("partition \"%s\" cannot be both published and excluded", + quote_qualified_identifier(get_namespace_name(get_rel_namespace(explicitrelid)), + get_rel_name(explicitrelid))), + errdetail("Partition root \"%s\" is named in the publication's EXCEPT clause for schema \"%s\".", + RelationGetQualifiedRelationName(pri->relation), + get_namespace_name(RelationGetNamespace(pri->relation))))); + } + + /* + * An EXCEPT clause also applies to inheritance children of a parent + * named without ONLY. Children in other schemas are not added to + * except_rels, but are still excluded by the EXCEPT clause. Explicitly + * publishing such a child therefore conflicts with the EXCEPT clause. + */ + if (list_member_oid(cross_schema_children, explicitrelid)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" cannot be both published and excluded", + quote_qualified_identifier(get_namespace_name(get_rel_namespace(explicitrelid)), + get_rel_name(explicitrelid))), + errdetail("It inherits from a table named in an EXCEPT clause of this statement."), + errhint("Use ONLY in the EXCEPT clause to exclude just the parent, or do not publish this table explicitly.")); + } +} + +/* + * Check that an EXCEPT clause does not conflict with a TABLES IN SCHEMA + * clause in the same statement. + * + * cross_schema_children contains inheritance children excluded through a + * parent in another schema. If such a child is also included through a + * TABLES IN SCHEMA clause in the same statement, report the conflict. + * + * If the child's schema also has an EXCEPT clause specified through TABLES + * IN SCHEMA, there is no conflict, since both clauses exclude the child. + * + * Conflicts with explicitly listed tables are handled by + * CheckExceptNotInTableList(). + */ +static void +CheckExceptChildNotInSchemaList(List *cross_schema_children, List *schemaidlist, + List *except_rels) +{ + foreach_oid(childrelid, cross_schema_children) + { + Oid childnsp = get_rel_namespace(childrelid); + bool excluded = false; + + if (!list_member_oid(schemaidlist, childnsp)) + continue; + + foreach_ptr(PublicationRelInfo, pri, except_rels) + { + if (RelationGetRelid(pri->relation) == childrelid) + { + excluded = true; + break; + } + } + + if (excluded) + continue; + + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" cannot be both published and excluded", + quote_qualified_identifier(get_namespace_name(childnsp), + get_rel_name(childrelid))), + errdetail("It inherits from a table named in the EXCEPT clause of another schema, and its own schema \"%s\" is published in full.", + get_namespace_name(childnsp)), + errhint("Use ONLY in the EXCEPT clause to exclude just the parent, or name this table in the EXCEPT clause of schema \"%s\".", + get_namespace_name(childnsp))); + } +} /* * Given a list of tables that are going to be added to a publication, @@ -849,7 +1068,7 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) char publish_generated_columns; AclResult aclresult; List *relations = NIL; - List *exceptrelations = NIL; + List *except_pubtables = NIL; List *schemaidlist = NIL; /* must have CREATE privilege on database */ @@ -936,16 +1155,16 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) /* Associate objects with the publication. */ ObjectsInPublicationToOids(stmt->pubobjects, pstate, &relations, - &exceptrelations, &schemaidlist); + &except_pubtables, &schemaidlist); if (stmt->for_all_tables) { /* Process EXCEPT table list */ - if (exceptrelations != NIL) + if (except_pubtables != NIL) { List *rels; - rels = OpenTableList(exceptrelations); + rels = OpenTableList(except_pubtables, NULL); PublicationAddTables(puboid, rels, true, NULL); CloseTableList(rels); } @@ -959,6 +1178,11 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) } else if (!stmt->for_all_sequences) { + List *explicitrelids = NIL; + + /* EXCEPT tables here always belong to a schema in schemaidlist */ + Assert(except_pubtables == NIL || schemaidlist != NIL); + /* FOR TABLES IN SCHEMA requires superuser */ if (schemaidlist != NIL && !superuser()) ereport(ERROR, @@ -969,7 +1193,7 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) { List *rels; - rels = OpenTableList(relations); + rels = OpenTableList(relations, NULL); TransformPubWhereClauses(rels, pstate->p_sourcetext, publish_via_partition_root); @@ -978,6 +1202,20 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) publish_via_partition_root); PublicationAddTables(puboid, rels, true, NULL); + + /* + * Collect explicit table OIDs now, before we close the relation + * list, so that the except-table validation for pub-included + * schemas below can check for contradictions without relying on a + * catalog scan that might not yet see the just-inserted rows. + */ + if (except_pubtables != NIL) + { + foreach_ptr(PublicationRelInfo, pri, rels) + explicitrelids = lappend_oid(explicitrelids, + RelationGetRelid(pri->relation)); + } + CloseTableList(rels); } @@ -989,6 +1227,32 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) */ LockSchemaList(schemaidlist); PublicationAddSchemas(puboid, schemaidlist, true, NULL); + + if (except_pubtables != NIL) + { + List *except_rels; + List *cross_schema_children = NIL; + + except_rels = OpenTableList(except_pubtables, + &cross_schema_children); + + /* + * Validate that a table is not both explicitly included and + * excluded by the schema's EXCEPT clause. + */ + CheckExceptNotInTableList(except_rels, cross_schema_children, + explicitrelids); + + /* + * Validate that an inheritance child is not both excluded by + * an EXCEPT clause and included by its schema. + */ + CheckExceptChildNotInSchemaList(cross_schema_children, + schemaidlist, except_rels); + + PublicationAddTables(puboid, except_rels, false, NULL); + CloseTableList(except_rels); + } } } @@ -1255,7 +1519,7 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, if (!tables && stmt->action != AP_SetObjects) return; - rels = OpenTableList(tables); + rels = OpenTableList(tables, NULL); if (stmt->action == AP_AddObjects) { @@ -1295,8 +1559,15 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, } else { - oldrelids = GetIncludedPublicationRelations(pubid, - PUBLICATION_PART_ROOT); + /* + * SET replaces the publication's whole relation list, so every + * existing entry has to be reconciled against the new one -- an + * EXCEPT entry included. If the same relation is now requested + * with the opposite kind, the old entry is dropped below and the + * new one added, rather than the old one being silently kept. + */ + oldrelids = GetPublicationRelationsOfAnyKind(pubid, + PUBLICATION_PART_ROOT); TransformPubWhereClauses(rels, queryString, pubform->pubviaroot); @@ -1317,6 +1588,7 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, HeapTuple rftuple; Node *oldrelwhereclause = NULL; Bitmapset *oldcolumns = NULL; + bool oldexcept = false; /* look up the cache for the old relmap */ rftuple = SearchSysCache2(PUBLICATIONRELMAP, @@ -1348,6 +1620,8 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, if (!isnull) oldcolumns = pub_collist_to_bitmapset(NULL, columnListDatum, NULL); + oldexcept = ((Form_pg_publication_rel) GETSTRUCT(rftuple))->prexcept; + ReleaseSysCache(rftuple); } @@ -1371,14 +1645,17 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, /* * Check if any of the new set of relations matches with the - * existing relations in the publication. Additionally, if the + * existing relations in the publication. An entry matches + * only if it is of the same kind, that is, both are ordinary + * members or both are EXCEPT entries. Additionally, if the * relation has an associated WHERE clause, check the WHERE * expressions also match. Same for the column list. Drop the * rest. */ if (newrelid == oldrelid) { - if (equal(oldrelwhereclause, newpubrel->whereClause) && + if (newpubrel->except == oldexcept && + equal(oldrelwhereclause, newpubrel->whereClause) && bms_equal(oldcolumns, newcolumns)) { found = true; @@ -1829,13 +2106,69 @@ RemovePublicationSchemaById(Oid psoid) table_close(rel, RowExclusiveLock); } +/* + * Remove any EXCEPT clause entries for a relation from schema publications. + * Called when a table changes schema (ALTER TABLE ... SET SCHEMA), so that + * a schema-scoped exclusion does not silently follow the table to its new + * schema. + */ +void +RemoveSchemaPubExceptForRel(Oid relid, Oid oldNspOid, Oid newNspOid) +{ + List *pubids; + + /* + * If the table is not actually moving to a different schema (no-op ALTER + * TABLE ... SET SCHEMA <current_schema>), there is nothing to do. + */ + if (oldNspOid == newNspOid) + return; + + pubids = GetRelationExcludedPublications(relid); + + foreach_oid(pubid, pubids) + { + Oid proid; + + /* + * This problem does not apply to FOR ALL TABLES publications, because + * their EXCEPT clause is publication-scoped, not schema-scoped: the + * exclusion should persist regardless of what schema the table is in. + */ + if (!is_schema_publication(pubid)) + continue; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddress obj; + + ObjectAddressSet(obj, PublicationRelRelationId, proid); + + ereport(DEBUG2, + errmsg_internal("auto-remove exclusion of table \"%s.%s\" from publication \"%s\": table moved to schema \"%s\"", + get_namespace_name(oldNspOid), + get_rel_name(relid), + get_publication_name(pubid, false), + get_namespace_name(newNspOid))); + + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + list_free(pubids); +} + /* * Open relations specified by a PublicationTable list. * The returned tables are locked in ShareUpdateExclusiveLock mode in order to * add them to a publication. */ static List * -OpenTableList(List *tables) +OpenTableList(List *tables, List **cross_schema_children) { List *relids = NIL; List *rels = NIL; @@ -1911,6 +2244,7 @@ OpenTableList(List *tables) { List *children; ListCell *child; + Oid parentnsp = RelationGetNamespace(rel); children = find_all_inheritors(myrelid, ShareUpdateExclusiveLock, NULL); @@ -1922,6 +2256,21 @@ OpenTableList(List *tables) /* Allow query cancel in case this takes a long time */ CHECK_FOR_INTERRUPTS(); + /* + * An EXCEPT clause also excludes inheritance children in other + * schemas. Keep track of such children separately so the + * caller can detect if the same statement also includes them + * through another table or schema clause. + */ + if (t->except_in_schema && + get_rel_namespace(childrelid) != parentnsp) + { + if (cross_schema_children) + *cross_schema_children = lappend_oid(*cross_schema_children, + childrelid); + continue; + } + /* * Skip duplicates if user specified both parent and child * tables. diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 8349e724c2b..64c49f69123 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -49,6 +49,7 @@ #include "catalog/pg_opclass.h" #include "catalog/pg_policy.h" #include "catalog/pg_proc.h" +#include "catalog/pg_publication.h" #include "catalog/pg_publication_rel.h" #include "catalog/pg_rewrite.h" #include "catalog/pg_statistic_ext.h" @@ -63,6 +64,7 @@ #include "commands/event_trigger.h" #include "commands/extension.h" #include "commands/repack.h" +#include "commands/publicationcmds.h" #include "commands/sequence.h" #include "commands/tablecmds.h" #include "commands/tablespace.h" @@ -19803,6 +19805,16 @@ AlterTableNamespaceInternal(Relation rel, Oid oldNspOid, Oid nspOid, AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid, false, objsMoved); + /* + * Remove any EXCEPT clause entries for this relation from schema + * publications. A schema-scoped exclusion is no longer meaningful once + * the table moves to a different schema. + */ + if (rel->rd_rel->relkind == RELKIND_RELATION || + rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE) + RemoveSchemaPubExceptForRel(RelationGetRelid(rel), oldNspOid, + nspOid); + table_close(classRel, RowExclusiveLock); } @@ -21136,6 +21148,7 @@ ATExecAttachPartition(List **wqueue, Relation rel, PartitionCmd *cmd, if (exceptpuboids != NIL) { bool first = true; + bool has_alltables_pub = false; StringInfoData pubnames; initStringInfo(&pubnames); @@ -21149,17 +21162,22 @@ ATExecAttachPartition(List **wqueue, Relation rel, PartitionCmd *cmd, else appendStringInfo(&pubnames, _(", \"%s\""), pubname); first = false; + + if (GetPublication(pubid)->alltables) + has_alltables_pub = true; } ereport(ERROR, errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), - errmsg_plural("cannot attach table \"%s\" as partition because it is referenced in publication %s EXCEPT clause", - "cannot attach table \"%s\" as partition because it is referenced in publications %s EXCEPT clause", + errmsg_plural("cannot attach table \"%s\" as partition because it is named in EXCEPT clause of publication %s", + "cannot attach table \"%s\" as partition because it is named in EXCEPT clause of publications %s", list_length(exceptpuboids), RelationGetRelationName(attachrel), pubnames.data), errdetail("The publication EXCEPT clause cannot contain tables that are partitions."), - errhint("Change the publication's EXCEPT clause using ALTER PUBLICATION ... SET ALL TABLES.")); + errhint("%s", has_alltables_pub ? + _("Change the EXCEPT clause using ALTER PUBLICATION ... SET ALL TABLES ... EXCEPT.") : + _("Change the EXCEPT clause using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT."))); } list_free(exceptpuboids); diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y index 17035fb4d15..14520a5ccab 100644 --- a/src/backend/parser/gram.y +++ b/src/backend/parser/gram.y @@ -58,6 +58,7 @@ #include "nodes/makefuncs.h" #include "nodes/nodeFuncs.h" #include "parser/parser.h" +#include "utils/builtins.h" #include "utils/datetime.h" #include "utils/xml.h" @@ -11282,7 +11283,7 @@ AlterOwnerStmt: ALTER AGGREGATE aggregate_with_argtypes OWNER TO RoleSpec * pub_obj is one of: * * TABLE table [, ...] - * TABLES IN SCHEMA schema [, ...] + * TABLES IN SCHEMA schema [EXCEPT (TABLE table [, ...] )] [, ...] * *****************************************************************************/ @@ -11342,23 +11343,26 @@ PublicationObjSpec: $$->pubtable->columns = $3; $$->pubtable->whereClause = $4; } - | TABLES IN_P SCHEMA ColId + | TABLES IN_P SCHEMA ColId opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_SCHEMA; $$->name = $4; + $$->except_tables = $5; $$->location = @4; } - | TABLES IN_P SCHEMA CURRENT_SCHEMA + | TABLES IN_P SCHEMA CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_CUR_SCHEMA; + $$->except_tables = $5; $$->location = @4; } - | ColId opt_column_list OptWhereClause + | ColId opt_column_list OptWhereClause opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $4; /* * If either a row filter or column list is specified, create * a PublicationTable object. @@ -11402,10 +11406,11 @@ PublicationObjSpec: $$->pubtable->columns = $2; $$->pubtable->whereClause = $3; } - | CURRENT_SCHEMA + | CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $2; $$->location = @1; } ; @@ -20867,6 +20872,11 @@ preprocess_pub_all_objtype_list(List *all_objects_list, List **pubobjects, /* * Process pubobjspec_list to check for errors in any of the objects and * convert PUBLICATIONOBJ_CONTINUATION into appropriate PublicationObjSpecType. + * + * The except_tables attached to TABLES IN SCHEMA nodes are left in place here; + * ObjectsInPublicationToOids() qualifies their names, validates schema + * membership, and merges the qualified tables into its except_pubtables + * output list once the schema OID is known. */ static void preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) @@ -20895,6 +20905,13 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLE) { + /* EXCEPT is not valid for table objects */ + if (pubobj->except_tables != NIL) + ereport(ERROR, + errcode(ERRCODE_SYNTAX_ERROR), + errmsg("EXCEPT is not allowed for TABLE publication objects"), + parser_errposition(pubobj->location)); + /* relation name or pubtable must be set for this type of object */ if (!pubobj->name && !pubobj->pubtable) ereport(ERROR, diff --git a/src/backend/replication/pgoutput/pgoutput.c b/src/backend/replication/pgoutput/pgoutput.c index 0afdb1432ca..ee2b997f82d 100644 --- a/src/backend/replication/pgoutput/pgoutput.c +++ b/src/backend/replication/pgoutput/pgoutput.c @@ -2281,10 +2281,41 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) } } - if (list_member_oid(pubids, pub->oid) || - list_member_oid(schemaPubids, pub->oid) || - ancestor_published) + if (list_member_oid(pubids, pub->oid) || ancestor_published) publish = true; + else if (list_member_oid(schemaPubids, pub->oid)) + { + Oid root_relid; + bool root_is_except = false; + + /* + * schemaPubids is the list of publications that include + * relid's own schema, independent of the ancestor walk + * above -- a partition can live in a different schema + * than its root. Still need to check for exclusion here, + * using the top-most ancestor since only a root + * (non-partition) table can appear in an EXCEPT clause. + */ + if (am_partition) + { + List *ancestors = get_partition_ancestors(relid); + + /* + * ancestors is NIL for a partition with a pending + * DETACH CONCURRENTLY; + */ + root_relid = (ancestors == NIL) ? relid : + llast_oid(ancestors); + list_free(ancestors); + } + else + root_relid = relid; + + CheckPublicationRelEntry(pub->oid, root_relid, &root_is_except); + + if (!root_is_except) + publish = true; + } } /* diff --git a/src/backend/utils/cache/relcache.c b/src/backend/utils/cache/relcache.c index 19c4ff6e75e..e4eb5e6d885 100644 --- a/src/backend/utils/cache/relcache.c +++ b/src/backend/utils/cache/relcache.c @@ -5807,7 +5807,6 @@ RelationBuildPublicationDesc(Relation relation, PublicationDesc *pubdesc) { List *puboids = NIL; List *exceptpuboids = NIL; - List *alltablespuboids; ListCell *lc; MemoryContext oldcxt; Oid schemaid; @@ -5851,12 +5850,9 @@ RelationBuildPublicationDesc(Relation relation, PublicationDesc *pubdesc) if (relation->rd_rel->relispartition) { - Oid last_ancestor_relid; - - /* Add publications that the ancestors are in too. */ ancestors = get_partition_ancestors(relid); - last_ancestor_relid = llast_oid(ancestors); + /* Add publications that the ancestors are in too. */ foreach(lc, ancestors) { Oid ancestor = lfirst_oid(lc); @@ -5869,11 +5865,13 @@ RelationBuildPublicationDesc(Relation relation, PublicationDesc *pubdesc) } /* - * Only the top-most ancestor can appear in the EXCEPT clause. - * Therefore, for a partition, exclusion must be evaluated at the - * top-most ancestor. + * Only the topmost root of a partition hierarchy can appear in an + * EXCEPT clause, so that is where exclusion has to be evaluated. + * ancestors is NIL for a partition with a pending DETACH + * CONCURRENTLY, in which case there is no root to consult. */ - exceptpuboids = GetRelationExcludedPublications(last_ancestor_relid); + if (ancestors != NIL) + exceptpuboids = GetRelationExcludedPublications(llast_oid(ancestors)); } else { @@ -5884,10 +5882,12 @@ RelationBuildPublicationDesc(Relation relation, PublicationDesc *pubdesc) exceptpuboids = GetRelationExcludedPublications(relid); } - alltablespuboids = GetAllTablesPublications(); - puboids = list_concat_unique_oid(puboids, - list_difference_oid(alltablespuboids, - exceptpuboids)); + puboids = list_concat_unique_oid(puboids, GetAllTablesPublications()); + + /* Ignore the publications that exclude this relation. */ + if (exceptpuboids != NIL) + puboids = list_difference_oid(puboids, exceptpuboids); + foreach(lc, puboids) { Oid pubid = lfirst_oid(lc); diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c index afe4b323a7b..51f70aaff23 100644 --- a/src/bin/psql/describe.c +++ b/src/bin/psql/describe.c @@ -3036,7 +3036,29 @@ describeOneTableDetails(const char *schemaname, "FROM pg_catalog.pg_publication p\n" " JOIN pg_catalog.pg_publication_namespace pn ON p.oid = pn.pnpubid\n" " JOIN pg_catalog.pg_class pc ON pc.relnamespace = pn.pnnspid\n" - "WHERE pc.oid ='%s' and pg_catalog.pg_relation_is_publishable('%s')\n" + "WHERE pc.oid ='%s' and pg_catalog.pg_relation_is_publishable('%s')\n", + oid, oid); + + if (pset.sversion >= 200000) + { + /* + * Publishing the schema does not publish a table named in the + * publication's EXCEPT clause, nor a partition whose root is + * named there, since excluding a root excludes the whole + * partition tree. Unlike the FOR ALL TABLES case below, a + * schema publication can have both kinds of + * pg_publication_rel row, so prexcept has to be tested. + */ + appendPQExpBuffer(&buf, + " AND NOT EXISTS (\n" + " SELECT 1\n" + " FROM pg_catalog.pg_publication_rel pr\n" + " WHERE pr.prpubid = p.oid AND pr.prexcept AND\n" + " (pr.prrelid = '%s' OR pr.prrelid = pg_catalog.pg_partition_root('%s')))\n", + oid, oid); + } + + appendPQExpBuffer(&buf, "UNION\n" "SELECT pubname\n" " , pg_catalog.pg_get_expr(pr.prqual, c.oid)\n" @@ -3060,7 +3082,7 @@ describeOneTableDetails(const char *schemaname, " FROM pg_catalog.pg_publication_namespace pn\n" " WHERE pn.pnpubid = p.oid\n" " AND pn.pnnspid = c.relnamespace)\n", - oid, oid, oid); + oid); if (pset.sversion >= 190000) { @@ -6839,6 +6861,24 @@ describePublications(const char *pattern) if (!addFooterToPublicationDesc(&buf, _("Tables from schemas:"), true, &cont)) goto error_return; + + if (pset.sversion >= 200000) + { + /* + * Get tables in the EXCEPT clause for this schema + * publication. + */ + printfPQExpBuffer(&buf, + "SELECT concat(c.relnamespace::regnamespace, '.', c.relname)\n" + "FROM pg_catalog.pg_class c\n" + " JOIN pg_catalog.pg_publication_rel pr ON c.oid = pr.prrelid\n" + "WHERE pr.prpubid = '%s'\n" + " AND pr.prexcept\n" + "ORDER BY 1", pubid); + if (!addFooterToPublicationDesc(&buf, _("Except tables:"), + true, &cont)) + goto error_return; + } } } else diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index 190fff7ea0e..f069e2654cc 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -1065,6 +1065,24 @@ static const SchemaQuery Query_for_trigger_of_table = { "SELECT nspname FROM pg_catalog.pg_namespace "\ " WHERE nspname LIKE '%s'" +#define Query_for_list_of_tables_in_schema \ +"SELECT n.nspname || '.' || c.relname "\ +" FROM pg_catalog.pg_class c "\ +" JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "\ +" WHERE c.relkind IN (" CppAsString2(RELKIND_RELATION) ", " \ + CppAsString2(RELKIND_PARTITIONED_TABLE) ") "\ +" AND (n.nspname || '.' || c.relname) LIKE '%s' "\ +" AND n.nspname = '%s'" + +#define Query_for_list_of_tables_in_current_schema \ +"SELECT c.relname "\ +" FROM pg_catalog.pg_class c "\ +" JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "\ +" WHERE c.relkind IN (" CppAsString2(RELKIND_RELATION) ", " \ + CppAsString2(RELKIND_PARTITIONED_TABLE) ") "\ +" AND c.relname LIKE '%s' "\ +" AND n.nspname = pg_catalog.current_schema()" + /* Use COMPLETE_WITH_QUERY_VERBATIM with these queries for GUC names: */ #define Query_for_list_of_alter_system_set_vars \ "SELECT pg_catalog.lower(name) FROM pg_catalog.pg_settings "\ @@ -3777,8 +3795,21 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); - else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && (!ends_with(prev_wd, ','))) - COMPLETE_WITH("WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE", "WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* Complete "CREATE PUBLICATION <name> [...] WITH" */ else if (Matches("CREATE", "PUBLICATION", MatchAnyN, "WITH", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/include/catalog/pg_publication.h b/src/include/catalog/pg_publication.h index 89b4bb14f62..451559552ad 100644 --- a/src/include/catalog/pg_publication.h +++ b/src/include/catalog/pg_publication.h @@ -179,6 +179,8 @@ extern List *GetIncludedPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt); extern List *GetExcludedPublicationTables(Oid pubid, PublicationPartOpt pub_partopt); +extern List *GetPublicationRelationsOfAnyKind(Oid pubid, + PublicationPartOpt pub_partopt); extern List *GetAllTablesPublications(void); extern List *GetAllPublicationRelations(Oid pubid, char relkind, bool pubviaroot); extern List *GetPublicationSchemas(Oid pubid); @@ -192,6 +194,7 @@ extern List *GetPubPartitionOptionRelations(List *result, Oid relid); extern Oid GetTopMostAncestorInPublication(Oid puboid, List *ancestors, int *ancestor_level); +extern bool CheckPublicationRelEntry(Oid pubid, Oid relid, bool *is_except); extern bool is_publishable_relation(Relation rel); extern bool is_schema_publication(Oid pubid); diff --git a/src/include/commands/publicationcmds.h b/src/include/commands/publicationcmds.h index 4cf45c17cc5..fb1703aa675 100644 --- a/src/include/commands/publicationcmds.h +++ b/src/include/commands/publicationcmds.h @@ -27,6 +27,8 @@ extern void AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt); extern void RemovePublicationById(Oid pubid); extern void RemovePublicationRelById(Oid proid); extern void RemovePublicationSchemaById(Oid psoid); +extern void RemoveSchemaPubExceptForRel(Oid relid, Oid oldNspOid, + Oid newNspOid); extern ObjectAddress AlterPublicationOwner(const char *name, Oid newOwnerId); extern void AlterPublicationOwner_oid(Oid pubid, Oid newOwnerId); diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h index 8a9df884276..d8b6ca132cf 100644 --- a/src/include/nodes/parsenodes.h +++ b/src/include/nodes/parsenodes.h @@ -4510,6 +4510,9 @@ typedef struct PublicationTable Node *whereClause; /* qualifications */ List *columns; /* List of columns in a publication table */ bool except; /* True if listed in the EXCEPT clause */ + bool except_in_schema; /* True if listed in the EXCEPT clause of a + * TABLES IN SCHEMA clause, whose scope is + * limited to that schema */ } PublicationTable; /* @@ -4531,6 +4534,8 @@ typedef struct PublicationObjSpec PublicationObjSpecType pubobjtype; /* type of this publication object */ char *name; PublicationTable *pubtable; + List *except_tables; /* tables specified in the EXCEPT clause (for + * TABLES IN SCHEMA) */ ParseLoc location; /* token location, or -1 if unknown */ } PublicationObjSpec; diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 4f21462cc17..6befa549ae6 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -279,6 +279,12 @@ CREATE PUBLICATION testpub_foralltables_excepttable2 FOR ALL TABLES EXCEPT (test ERROR: syntax error at or near "testpub_tbl1" LINE 1: ..._foralltables_excepttable2 FOR ALL TABLES EXCEPT (testpub_tb... ^ +-- fail - EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testpub_tbl3); +ERROR: EXCEPT is not allowed for TABLE publication objects +LINE 2: FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testp... + ^ --------------------------------------------- -- SET ALL TABLES/SEQUENCES --------------------------------------------- @@ -473,13 +479,292 @@ CREATE TABLE tab_main (a int) PARTITION BY RANGE(a); -- Attaching a partition is not allowed if the partitioned table appears in a -- publication's EXCEPT clause. ALTER TABLE tab_main ATTACH PARTITION testpub_root FOR VALUES FROM (0) TO (200); -ERROR: cannot attach table "testpub_root" as partition because it is referenced in publication "testpub8" EXCEPT clause +ERROR: cannot attach table "testpub_root" as partition because it is named in EXCEPT clause of publication "testpub8" DETAIL: The publication EXCEPT clause cannot contain tables that are partitions. -HINT: Change the publication's EXCEPT clause using ALTER PUBLICATION ... SET ALL TABLES. +HINT: Change the EXCEPT clause using ALTER PUBLICATION ... SET ALL TABLES ... EXCEPT. RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Create same-named tables in public to verify unqualified EXCEPT entries +-- are qualified with the named schema, not public +CREATE TABLE testpub_nopk (foo int, bar int); +CREATE TABLE testpub_tbl_s1 (a int primary key, b text); +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + Publication testpub_schema_except1 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- Exclude multiple tables using unqualified names; same-named tables exist in +-- public to confirm unqualified names resolve to pub_test, not public +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + Publication testpub_schema_except2 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_nopk" + "pub_test.testpub_tbl_s1" + +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testp... + ^ +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); +ERROR: table "pub_test.testpub_tbl_s1" in EXCEPT clause does not belong to schema "public" +LINE 2: ...R TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.t... + ^ +-- Multiple schemas each with their own EXCEPT clause +CREATE PUBLICATION testpub_schema_except_multi + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_schema_except_multi + Publication testpub_schema_except_multi + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- fail: same schema repeated with same EXCEPT clauses +CREATE PUBLICATION testpub_schema_except_conflict + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: conflicting or redundant EXCEPT clauses for schema "pub_test" +-- fail: same schema repeated with conflicting or no EXCEPT clauses +CREATE PUBLICATION testpub_schema_except_conflict2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2), + pub_test; +ERROR: conflicting or redundant EXCEPT clauses for schema "pub_test" +-- ALTER TABLE ... SET SCHEMA on a table excluded by a schema publication: +-- the schema-scoped exclusion is no longer meaningful once the table moves +-- out of its schema, so the exclusion is auto-removed. +CREATE PUBLICATION testpub_schema_except_setsch + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_schema_except_setsch + Publication testpub_schema_except_setsch + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s2" + +ALTER TABLE pub_test.testpub_tbl_s2 SET SCHEMA public; +\dRp+ testpub_schema_except_setsch + Publication testpub_schema_except_setsch + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + +DROP PUBLICATION testpub_schema_except_setsch; +-- Restore for further tests +ALTER TABLE public.testpub_tbl_s2 SET SCHEMA pub_test; +-- fail: table appears in both the explicit table list and the EXCEPT clause +CREATE PUBLICATION testpub_except_conflict + FOR TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot be both published and excluded +-- fail: nonexistent table in EXCEPT clause +CREATE PUBLICATION testpub_except_norel + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- fail: partition cannot appear in EXCEPT clause; only root tables are allowed +CREATE TABLE pub_test.testpub_parted_s (a int) PARTITION BY LIST (a); +CREATE TABLE pub_test.testpub_part_s PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (1); +CREATE PUBLICATION testpub_except_partition + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); +ERROR: cannot specify relation "pub_test.testpub_part_s" in the publication EXCEPT clause +DETAIL: This operation is not supported for individual partitions. +-- fail: TABLE keyword is required for the first entry in the EXCEPT clause +CREATE PUBLICATION testpub_except_nokw + FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +ERROR: syntax error at or near "testpub_nopk" +LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + ^ +-- Check that a table excluded from a schema publication is reported only as +-- excluded and not as published. +\d pub_test.testpub_nopk + Table "pub_test.testpub_nopk" + Column | Type | Collation | Nullable | Default +--------+---------+-----------+----------+--------- + foo | integer | | | + bar | integer | | | +Included in publications: + "testpub_schema_except1" + "testpub_schema_except_multi" +Excluded from publications: + "testpub_schema_except2" + +-- fail: ADD TABLE for a partition is rejected when a partition ancestor +-- is currently in the publication's EXCEPT list. +CREATE PUBLICATION testpub_except_ancestor + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ALTER PUBLICATION testpub_except_ancestor ADD TABLE pub_test.testpub_part_s; +ERROR: cannot add partition "pub_test.testpub_part_s" to publication "testpub_except_ancestor" +DETAIL: Partition root "pub_test.testpub_parted_s" is named in the publication's EXCEPT clause for schema "pub_test". +HINT: Change the EXCEPT clause using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT. +DROP PUBLICATION testpub_except_ancestor; +-- fail: same contradiction (explicit partition + EXCEPT-ed ancestor), but +-- given in a single statement instead of two separate ones +CREATE PUBLICATION testpub_except_ancestor_same_create + FOR TABLE pub_test.testpub_part_s, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ERROR: partition "pub_test.testpub_part_s" cannot be both published and excluded +DETAIL: Partition root "pub_test.testpub_parted_s" is named in the publication's EXCEPT clause for schema "pub_test". +-- fail: same contradiction as above, but the partition lives in a different +-- schema (public) than its EXCEPT-ed root (pub_test) +CREATE TABLE public.testpub_part_s2 PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (2); +CREATE PUBLICATION testpub_except_ancestor_cross_schema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s), + TABLE public.testpub_part_s2; +ERROR: partition "public.testpub_part_s2" cannot be both published and excluded +DETAIL: Partition root "pub_test.testpub_parted_s" is named in the publication's EXCEPT clause for schema "pub_test". +DROP TABLE public.testpub_part_s2; +-- ALTER PUBLICATION ... SET replaces the publication's whole relation list, so +-- an existing entry for a relation now requested with the opposite kind must be +-- dropped and re-added, not silently left in place. +CREATE PUBLICATION testpub_except_alter1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +-- the excluded table becomes an ordinary member: one non-EXCEPT entry, no +-- EXCEPT entry, and no schema left in the publication +ALTER PUBLICATION testpub_except_alter1 SET TABLE pub_test.testpub_tbl_s1; +\dRp+ testpub_except_alter1 + Publication testpub_except_alter1 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables: + "pub_test.testpub_tbl_s1" + +DROP PUBLICATION testpub_except_alter1; +-- and the reverse direction: an ordinary member becomes an EXCEPT entry +CREATE PUBLICATION testpub_except_alter2 FOR TABLE pub_test.testpub_tbl_s1; +ALTER PUBLICATION testpub_except_alter2 + SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_except_alter2 + Publication testpub_except_alter2 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +DROP PUBLICATION testpub_except_alter2; +-- Cross-schema inheritance children and EXCEPT. An EXCEPT clause also +-- excludes inheritance children of a parent named without ONLY. +CREATE TABLE pub_test.testpub_inh_parent (a int); +CREATE TABLE pub_test.testpub_inh_sibling (b int) INHERITS (pub_test.testpub_inh_parent); +CREATE TABLE testpub_inh_child (b int) INHERITS (pub_test.testpub_inh_parent); +CREATE PUBLICATION testpub_inh + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_inh_parent); +-- Two EXCEPT entries: the parent and the child in pub_test. +\dRp+ testpub_inh + Publication testpub_inh + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_inh_parent" + "pub_test.testpub_inh_sibling" + +DROP PUBLICATION testpub_inh; +-- fail: the child testpub_inh_child is also included through TABLES IN SCHEM +-- public +CREATE PUBLICATION testpub_inh + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_inh_parent), + TABLES IN SCHEMA public; +ERROR: table "public.testpub_inh_child" cannot be both published and excluded +DETAIL: It inherits from a table named in the EXCEPT clause of another schema, and its own schema "public" is published in full. +HINT: Use ONLY in the EXCEPT clause to exclude just the parent, or name this table in the EXCEPT clause of schema "public". +-- fail: the child is also explicitly included by the same statement +CREATE PUBLICATION testpub_inh + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_inh_parent), + TABLE testpub_inh_child; +ERROR: table "public.testpub_inh_child" cannot be both published and excluded +DETAIL: It inherits from a table named in an EXCEPT clause of this statement. +HINT: Use ONLY in the EXCEPT clause to exclude just the parent, or do not publish this table explicitly. +-- ONLY resolves the conflict: only the parent is excluded, so the child can +-- be published explicitly +CREATE PUBLICATION testpub_inh + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE ONLY pub_test.testpub_inh_parent), + TABLE testpub_inh_child; +\dRp+ testpub_inh + Publication testpub_inh + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables: + "public.testpub_inh_child" +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_inh_parent" + +DROP PUBLICATION testpub_inh; +-- An EXCEPT clause in the child's schema also excludes the child explicitly, +-- so both clauses agree and there is no conflict. +CREATE PUBLICATION testpub_inh + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_inh_parent), + TABLES IN SCHEMA public EXCEPT (TABLE testpub_inh_child); +\dRp+ testpub_inh + Publication testpub_inh + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_inh_parent" + "pub_test.testpub_inh_sibling" + "public.testpub_inh_child" + +DROP PUBLICATION testpub_inh; +DROP TABLE testpub_inh_child, pub_test.testpub_inh_sibling, + pub_test.testpub_inh_parent; +-- Cleanup +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP TABLE pub_test.testpub_parted_s CASCADE; +DROP TABLE testpub_nopk, testpub_tbl_s1; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +--------------------------------------------- +-- Tests for publications with SEQUENCES +--------------------------------------------- CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; -- FOR ALL SEQUENCES @@ -1970,6 +2255,54 @@ ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b); ERROR: column specification not allowed for schema LINE 1: ...TION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b)... ^ +-- EXCEPT clause with CURRENT_SCHEMA: cross-schema entry must be rejected +SET search_path = pub_test1; +-- qualified name from wrong schema -> error +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.tbl1); +ERROR: table "pub_test2.tbl1" in EXCEPT clause does not belong to schema "pub_test1" +LINE 1: ...FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.... + ^ +-- unqualified name implicitly qualified with current schema (pub_test1.tbl) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl); +RESET client_min_messages; +\dRp+ testpub_cursch_except + Publication testpub_cursch_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test1" +Except tables: + "pub_test1.tbl" + +DROP PUBLICATION testpub_cursch_except; +-- succeeds: CURRENT_SCHEMA and pub_test1 (same schema) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_named_same + FOR TABLES IN SCHEMA CURRENT_SCHEMA, pub_test1; +RESET client_min_messages; +\dRp+ testpub_cursch_named_same + Publication testpub_cursch_named_same + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test1" + +DROP PUBLICATION testpub_cursch_named_same; +-- fail: CURRENT_SCHEMA and pub_test1 (same schema) have +-- conflicting EXCEPT clauses +CREATE PUBLICATION testpub_cursch_named_conflict + FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl), + pub_test1 EXCEPT (TABLE tbl1); +ERROR: conflicting or redundant EXCEPT clauses for schema "pub_test1" +-- fail: two CURRENT_SCHEMA mentions with conflicting EXCEPT clauses +CREATE PUBLICATION testpub_cursch_cursch_conflict + FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl), + CURRENT_SCHEMA EXCEPT (TABLE tbl1); +ERROR: conflicting or redundant EXCEPT clauses for schema "pub_test1" +RESET search_path; -- cleanup pub_test1 schema for invalidation tests ALTER PUBLICATION testpub2_forschema DROP TABLES IN SCHEMA pub_test1; DROP PUBLICATION testpub3_forschema, testpub4_forschema, testpub5_forschema, testpub6_forschema, testpub_fortable; @@ -2321,6 +2654,7 @@ DROP ROLE regress_publication_user_dummy; -- Test pg_get_publication_tables(text[], oid) function CREATE SCHEMA gpt_test_sch; CREATE TABLE gpt_test_sch.tbl_sch (id int); +CREATE TABLE gpt_test_sch.tbl_sch2 (id int); CREATE TABLE tbl_normal (id int); CREATE TABLE tbl_parent (id1 int, id2 int, id3 int) PARTITION BY RANGE (id1); CREATE TABLE tbl_part1 PARTITION OF tbl_parent FOR VALUES FROM (1) TO (10); @@ -2331,6 +2665,7 @@ CREATE PUBLICATION pub_all_no_viaroot FOR ALL TABLES WITH (publish_via_partition CREATE PUBLICATION pub_all_except FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = true); CREATE PUBLICATION pub_all_except_no_viaroot FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_schema FOR TABLES IN SCHEMA gpt_test_sch; +CREATE PUBLICATION pub_schema_except FOR TABLES IN SCHEMA gpt_test_sch EXCEPT (TABLE gpt_test_sch.tbl_sch); CREATE PUBLICATION pub_normal FOR TABLE tbl_normal WHERE (id < 10); CREATE PUBLICATION pub_part_leaf FOR TABLE tbl_part1 WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_part_parent FOR TABLE tbl_parent (id1, id2) WHERE (id1 = 10) WITH (publish_via_partition_root = true); @@ -2482,6 +2817,44 @@ SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_part1'); -- no r ---------+---------+-------+------ (0 rows) +-- test for EXCEPT clause with schema publication +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch'); -- no result (excluded) + pubname | relname | attrs | qual +---------+---------+-------+------ +(0 rows) + +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch2'); -- one row (included via schema) + pubname | relname | attrs | qual +-------------------+----------+-------+------ + pub_schema_except | tbl_sch2 | 1 | +(1 row) + +-- test for EXCEPT clause with schema publication, where the excluded root's +-- partition lives in a different schema that is separately, fully included +-- (no EXCEPT) in the same publication. The root's exclusion must cascade to +-- the partition regardless of the partition's own schema membership. +CREATE SCHEMA gpt_cross_sch1; +CREATE SCHEMA gpt_cross_sch2; +CREATE TABLE gpt_cross_sch1.croot (id int) PARTITION BY RANGE (id); +CREATE TABLE gpt_cross_sch2.cpart1 PARTITION OF gpt_cross_sch1.croot FOR VALUES FROM (1) TO (10); +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION pub_cross_schema_except FOR TABLES IN SCHEMA gpt_cross_sch1 EXCEPT (TABLE gpt_cross_sch1.croot), TABLES IN SCHEMA gpt_cross_sch2; +RESET client_min_messages; +SELECT * FROM test_gpt(ARRAY['pub_cross_schema_except'], 'gpt_cross_sch1.croot'); -- no result (excluded) + pubname | relname | attrs | qual +---------+---------+-------+------ +(0 rows) + +-- no result (excluded via cascading root exclusion, even though cpart1's own +-- schema gpt_cross_sch2 is separately, fully included with no EXCEPT) +SELECT * FROM test_gpt(ARRAY['pub_cross_schema_except'], 'gpt_cross_sch2.cpart1'); + pubname | relname | attrs | qual +---------+---------+-------+------ +(0 rows) + +DROP PUBLICATION pub_cross_schema_except; +DROP TABLE gpt_cross_sch2.cpart1, gpt_cross_sch1.croot; +DROP SCHEMA gpt_cross_sch1, gpt_cross_sch2; -- two rows with different row filter SELECT * FROM test_gpt(ARRAY['pub_all', 'pub_normal'], 'tbl_normal'); pubname | relname | attrs | qual @@ -2534,6 +2907,7 @@ DROP PUBLICATION pub_all_no_viaroot; DROP PUBLICATION pub_all_except; DROP PUBLICATION pub_all_except_no_viaroot; DROP PUBLICATION pub_schema; +DROP PUBLICATION pub_schema_except; DROP PUBLICATION pub_normal; DROP PUBLICATION pub_part_leaf; DROP PUBLICATION pub_part_parent; @@ -2542,7 +2916,9 @@ DROP PUBLICATION pub_part_parent_child; DROP VIEW gpt_test_view; DROP TABLE tbl_normal, tbl_parent, tbl_part1; DROP SCHEMA gpt_test_sch CASCADE; -NOTICE: drop cascades to table gpt_test_sch.tbl_sch +NOTICE: drop cascades to 2 other objects +DETAIL: drop cascades to table gpt_test_sch.tbl_sch +drop cascades to table gpt_test_sch.tbl_sch2 -- stage objects for pg_dump tests CREATE SCHEMA pubme CREATE TABLE t0 (c int, d int) CREATE TABLE t1 (c int); CREATE SCHEMA pubme2 CREATE TABLE t0 (c int, d int); diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index fac54b02e27..f77dba51349 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -125,6 +125,9 @@ CREATE PUBLICATION testpub_foralltables_excepttable1 FOR ALL TABLES EXCEPT (TABL \d testpub_tbl1 -- fail - first table in the EXCEPT list should use TABLE keyword CREATE PUBLICATION testpub_foralltables_excepttable2 FOR ALL TABLES EXCEPT (testpub_tbl1, testpub_tbl2); +-- fail - EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testpub_tbl3); --------------------------------------------- -- SET ALL TABLES/SEQUENCES @@ -222,7 +225,177 @@ RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Create same-named tables in public to verify unqualified EXCEPT entries +-- are qualified with the named schema, not public +CREATE TABLE testpub_nopk (foo int, bar int); +CREATE TABLE testpub_tbl_s1 (a int primary key, b text); + +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + +-- Exclude multiple tables using unqualified names; same-named tables exist in +-- public to confirm unqualified names resolve to pub_test, not public +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); + +-- Multiple schemas each with their own EXCEPT clause +CREATE PUBLICATION testpub_schema_except_multi + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_schema_except_multi + +-- fail: same schema repeated with same EXCEPT clauses +CREATE PUBLICATION testpub_schema_except_conflict + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: same schema repeated with conflicting or no EXCEPT clauses +CREATE PUBLICATION testpub_schema_except_conflict2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2), + pub_test; + +-- ALTER TABLE ... SET SCHEMA on a table excluded by a schema publication: +-- the schema-scoped exclusion is no longer meaningful once the table moves +-- out of its schema, so the exclusion is auto-removed. +CREATE PUBLICATION testpub_schema_except_setsch + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_schema_except_setsch +ALTER TABLE pub_test.testpub_tbl_s2 SET SCHEMA public; +\dRp+ testpub_schema_except_setsch +DROP PUBLICATION testpub_schema_except_setsch; +-- Restore for further tests +ALTER TABLE public.testpub_tbl_s2 SET SCHEMA pub_test; + +-- fail: table appears in both the explicit table list and the EXCEPT clause +CREATE PUBLICATION testpub_except_conflict + FOR TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: nonexistent table in EXCEPT clause +CREATE PUBLICATION testpub_except_norel + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- fail: partition cannot appear in EXCEPT clause; only root tables are allowed +CREATE TABLE pub_test.testpub_parted_s (a int) PARTITION BY LIST (a); +CREATE TABLE pub_test.testpub_part_s PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (1); +CREATE PUBLICATION testpub_except_partition + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); + +-- fail: TABLE keyword is required for the first entry in the EXCEPT clause +CREATE PUBLICATION testpub_except_nokw + FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + +-- Check that a table excluded from a schema publication is reported only as +-- excluded and not as published. +\d pub_test.testpub_nopk + +-- fail: ADD TABLE for a partition is rejected when a partition ancestor +-- is currently in the publication's EXCEPT list. +CREATE PUBLICATION testpub_except_ancestor + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ALTER PUBLICATION testpub_except_ancestor ADD TABLE pub_test.testpub_part_s; +DROP PUBLICATION testpub_except_ancestor; + +-- fail: same contradiction (explicit partition + EXCEPT-ed ancestor), but +-- given in a single statement instead of two separate ones +CREATE PUBLICATION testpub_except_ancestor_same_create + FOR TABLE pub_test.testpub_part_s, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); + +-- fail: same contradiction as above, but the partition lives in a different +-- schema (public) than its EXCEPT-ed root (pub_test) +CREATE TABLE public.testpub_part_s2 PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (2); +CREATE PUBLICATION testpub_except_ancestor_cross_schema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s), + TABLE public.testpub_part_s2; +DROP TABLE public.testpub_part_s2; + +-- ALTER PUBLICATION ... SET replaces the publication's whole relation list, so +-- an existing entry for a relation now requested with the opposite kind must be +-- dropped and re-added, not silently left in place. +CREATE PUBLICATION testpub_except_alter1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +-- the excluded table becomes an ordinary member: one non-EXCEPT entry, no +-- EXCEPT entry, and no schema left in the publication +ALTER PUBLICATION testpub_except_alter1 SET TABLE pub_test.testpub_tbl_s1; +\dRp+ testpub_except_alter1 +DROP PUBLICATION testpub_except_alter1; + +-- and the reverse direction: an ordinary member becomes an EXCEPT entry +CREATE PUBLICATION testpub_except_alter2 FOR TABLE pub_test.testpub_tbl_s1; +ALTER PUBLICATION testpub_except_alter2 + SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_except_alter2 +DROP PUBLICATION testpub_except_alter2; + +-- Cross-schema inheritance children and EXCEPT. An EXCEPT clause also +-- excludes inheritance children of a parent named without ONLY. +CREATE TABLE pub_test.testpub_inh_parent (a int); +CREATE TABLE pub_test.testpub_inh_sibling (b int) INHERITS (pub_test.testpub_inh_parent); +CREATE TABLE testpub_inh_child (b int) INHERITS (pub_test.testpub_inh_parent); +CREATE PUBLICATION testpub_inh + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_inh_parent); +-- Two EXCEPT entries: the parent and the child in pub_test. +\dRp+ testpub_inh +DROP PUBLICATION testpub_inh; + +-- fail: the child testpub_inh_child is also included through TABLES IN SCHEM +-- public +CREATE PUBLICATION testpub_inh + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_inh_parent), + TABLES IN SCHEMA public; + +-- fail: the child is also explicitly included by the same statement +CREATE PUBLICATION testpub_inh + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_inh_parent), + TABLE testpub_inh_child; + +-- ONLY resolves the conflict: only the parent is excluded, so the child can +-- be published explicitly +CREATE PUBLICATION testpub_inh + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE ONLY pub_test.testpub_inh_parent), + TABLE testpub_inh_child; +\dRp+ testpub_inh +DROP PUBLICATION testpub_inh; + +-- An EXCEPT clause in the child's schema also excludes the child explicitly, +-- so both clauses agree and there is no conflict. +CREATE PUBLICATION testpub_inh + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_inh_parent), + TABLES IN SCHEMA public EXCEPT (TABLE testpub_inh_child); +\dRp+ testpub_inh +DROP PUBLICATION testpub_inh; +DROP TABLE testpub_inh_child, pub_test.testpub_inh_sibling, + pub_test.testpub_inh_parent; + +-- Cleanup +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP TABLE pub_test.testpub_parted_s CASCADE; +DROP TABLE testpub_nopk, testpub_tbl_s1; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; + +--------------------------------------------- +-- Tests for publications with SEQUENCES +--------------------------------------------- CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; @@ -1194,6 +1367,38 @@ ALTER PUBLICATION testpub1_forschema SET TABLES IN SCHEMA pub_test1, pub_test1; ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo (a, b); ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b); +-- EXCEPT clause with CURRENT_SCHEMA: cross-schema entry must be rejected +SET search_path = pub_test1; +-- qualified name from wrong schema -> error +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.tbl1); +-- unqualified name implicitly qualified with current schema (pub_test1.tbl) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl); +RESET client_min_messages; +\dRp+ testpub_cursch_except +DROP PUBLICATION testpub_cursch_except; + +-- succeeds: CURRENT_SCHEMA and pub_test1 (same schema) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_named_same + FOR TABLES IN SCHEMA CURRENT_SCHEMA, pub_test1; +RESET client_min_messages; +\dRp+ testpub_cursch_named_same +DROP PUBLICATION testpub_cursch_named_same; + +-- fail: CURRENT_SCHEMA and pub_test1 (same schema) have +-- conflicting EXCEPT clauses +CREATE PUBLICATION testpub_cursch_named_conflict + FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl), + pub_test1 EXCEPT (TABLE tbl1); + +-- fail: two CURRENT_SCHEMA mentions with conflicting EXCEPT clauses +CREATE PUBLICATION testpub_cursch_cursch_conflict + FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl), + CURRENT_SCHEMA EXCEPT (TABLE tbl1); + +RESET search_path; + -- cleanup pub_test1 schema for invalidation tests ALTER PUBLICATION testpub2_forschema DROP TABLES IN SCHEMA pub_test1; DROP PUBLICATION testpub3_forschema, testpub4_forschema, testpub5_forschema, testpub6_forschema, testpub_fortable; @@ -1448,6 +1653,7 @@ DROP ROLE regress_publication_user_dummy; -- Test pg_get_publication_tables(text[], oid) function CREATE SCHEMA gpt_test_sch; CREATE TABLE gpt_test_sch.tbl_sch (id int); +CREATE TABLE gpt_test_sch.tbl_sch2 (id int); CREATE TABLE tbl_normal (id int); CREATE TABLE tbl_parent (id1 int, id2 int, id3 int) PARTITION BY RANGE (id1); CREATE TABLE tbl_part1 PARTITION OF tbl_parent FOR VALUES FROM (1) TO (10); @@ -1459,6 +1665,7 @@ CREATE PUBLICATION pub_all_no_viaroot FOR ALL TABLES WITH (publish_via_partition CREATE PUBLICATION pub_all_except FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = true); CREATE PUBLICATION pub_all_except_no_viaroot FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_schema FOR TABLES IN SCHEMA gpt_test_sch; +CREATE PUBLICATION pub_schema_except FOR TABLES IN SCHEMA gpt_test_sch EXCEPT (TABLE gpt_test_sch.tbl_sch); CREATE PUBLICATION pub_normal FOR TABLE tbl_normal WHERE (id < 10); CREATE PUBLICATION pub_part_leaf FOR TABLE tbl_part1 WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_part_parent FOR TABLE tbl_parent (id1, id2) WHERE (id1 = 10) WITH (publish_via_partition_root = true); @@ -1515,6 +1722,32 @@ SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'gpt_test_sch.tbl_sch SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_parent'); -- no result (excluded) SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_part1'); -- no result +-- test for EXCEPT clause with schema publication +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch'); -- no result (excluded) +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch2'); -- one row (included via schema) + +-- test for EXCEPT clause with schema publication, where the excluded root's +-- partition lives in a different schema that is separately, fully included +-- (no EXCEPT) in the same publication. The root's exclusion must cascade to +-- the partition regardless of the partition's own schema membership. +CREATE SCHEMA gpt_cross_sch1; +CREATE SCHEMA gpt_cross_sch2; +CREATE TABLE gpt_cross_sch1.croot (id int) PARTITION BY RANGE (id); +CREATE TABLE gpt_cross_sch2.cpart1 PARTITION OF gpt_cross_sch1.croot FOR VALUES FROM (1) TO (10); + +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION pub_cross_schema_except FOR TABLES IN SCHEMA gpt_cross_sch1 EXCEPT (TABLE gpt_cross_sch1.croot), TABLES IN SCHEMA gpt_cross_sch2; +RESET client_min_messages; + +SELECT * FROM test_gpt(ARRAY['pub_cross_schema_except'], 'gpt_cross_sch1.croot'); -- no result (excluded) +-- no result (excluded via cascading root exclusion, even though cpart1's own +-- schema gpt_cross_sch2 is separately, fully included with no EXCEPT) +SELECT * FROM test_gpt(ARRAY['pub_cross_schema_except'], 'gpt_cross_sch2.cpart1'); + +DROP PUBLICATION pub_cross_schema_except; +DROP TABLE gpt_cross_sch2.cpart1, gpt_cross_sch1.croot; +DROP SCHEMA gpt_cross_sch1, gpt_cross_sch2; + -- two rows with different row filter SELECT * FROM test_gpt(ARRAY['pub_all', 'pub_normal'], 'tbl_normal'); @@ -1543,6 +1776,7 @@ DROP PUBLICATION pub_all_no_viaroot; DROP PUBLICATION pub_all_except; DROP PUBLICATION pub_all_except_no_viaroot; DROP PUBLICATION pub_schema; +DROP PUBLICATION pub_schema_except; DROP PUBLICATION pub_normal; DROP PUBLICATION pub_part_leaf; DROP PUBLICATION pub_part_parent; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 43b51c8ff71..7e11061a594 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -24,14 +24,17 @@ my $result; sub test_except_root_partition { - my ($pubviaroot) = @_; + my ($pubviaroot, $pubsql) = @_; + $pubsql //= + "CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1)"; + $pubsql .= " WITH (publish_via_partition_root = $pubviaroot)"; # If the root partitioned table is in the EXCEPT clause, all its # partitions are excluded from publication, regardless of the # publish_via_partition_root setting. $node_publisher->safe_psql( 'postgres', qq( - CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1) WITH (publish_via_partition_root = $pubviaroot); + $pubsql; INSERT INTO root1 VALUES (1), (101); )); $node_subscriber->safe_psql('postgres', @@ -223,6 +226,206 @@ $node_subscriber->safe_psql( test_except_root_partition('false'); test_except_root_partition('true'); +# Same validation using TABLES IN SCHEMA instead of FOR ALL TABLES. +my $schema_pub = + "CREATE PUBLICATION tap_pub_part FOR TABLES IN SCHEMA public EXCEPT (TABLE public.root1)"; +test_except_root_partition('false', $schema_pub); +test_except_root_partition('true', $schema_pub); + +# ============================================ +# EXCEPT test cases for TABLES IN SCHEMA +# ============================================ + +# Create a dedicated schema with two tables: one to be published and one to be +# excluded. Also create inherited tables to verify ONLY semantics. +$node_publisher->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_published AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.tab_excluded AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.parent (a int); + CREATE TABLE sch1.child (b int) INHERITS (sch1.parent); +)); + +$node_subscriber->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_published (a int); + CREATE TABLE sch1.tab_excluded (a int); + CREATE TABLE sch1.parent (a int); + CREATE TABLE sch1.child (b int) INHERITS (sch1.parent); +)); + +# Basic test: initial sync respects EXCEPT. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_excluded)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: initial sync copies included table'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: initial sync skips excluded table'); + +# DML: only the included table should be replicated. +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (6); + INSERT INTO sch1.tab_excluded VALUES (6); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(6), + 'TABLES IN SCHEMA EXCEPT: DML on included table is replicated'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: DML on excluded table is not replicated'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Inherited tables: excluding the parent (without ONLY) also excludes the child. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.parent)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.child VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.child"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: excluding parent (without ONLY) also excludes child' +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Test that EXCEPT (TABLE ONLY parent) excludes only the parent itself, not its +# child. Truncate child first so rows from the previous test are not copied by +# the initial table sync of the next subscription. +$node_publisher->safe_psql('postgres', 'TRUNCATE sch1.child'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE sch1.child'); +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE ONLY sch1.parent)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.child VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.child"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: ONLY parent in EXCEPT does not exclude child'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Cleanup schema tables before the multi-publication section. +$node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); +$node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); + +# ============================================ +# EXCEPT test cases for TABLES IN SCHEMA with a cross-schema partition +# ============================================ + +# A partition can live in a different schema than its partitioned root. If +# the root is excluded via EXCEPT under its own schema's clause, the +# exclusion must cascade to all its partitions, even when the partition's +# own schema is separately, fully included (no EXCEPT) in the same +# publication. +$node_publisher->safe_psql( + 'postgres', qq( + CREATE SCHEMA csch1; + CREATE SCHEMA csch2; + CREATE TABLE csch1.croot(a int) PARTITION BY RANGE(a); + CREATE TABLE csch2.cpart1 PARTITION OF csch1.croot FOR VALUES FROM (0) TO (100); + INSERT INTO csch1.croot VALUES (generate_series(1,5)); +)); + +$node_subscriber->safe_psql( + 'postgres', qq( + CREATE SCHEMA csch1; + CREATE SCHEMA csch2; + CREATE TABLE csch1.croot(a int); + CREATE TABLE csch2.cpart1(a int); +)); + +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION cross_sch_pub FOR TABLES IN SCHEMA csch1 EXCEPT (TABLE csch1.croot), TABLES IN SCHEMA csch2 WITH (publish_via_partition_root = false)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION cross_sch_sub CONNECTION '$publisher_connstr' PUBLICATION cross_sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'cross_sch_sub'); + +# Baseline: the root itself, pre-populated with rows before the subscription +# was created, is excluded by its own schema's EXCEPT clause -- initial sync +# must not have copied it. +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM csch1.croot"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: cross-schema partition root is excluded by initial sync' +); + +# Regression case: the partition's own schema (csch2) is separately, fully +# included with no EXCEPT, but the root's exclusion must still cascade to it +# -- initial sync must not have copied the pre-existing rows routed into this +# partition via the root. +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM csch2.cpart1"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: cross-schema partition is excluded by initial sync via cascading root exclusion' +); + +# Insert distinct, identifiable data directly into the partition and verify +# it is not replicated either. +$node_publisher->safe_psql('postgres', + "INSERT INTO csch2.cpart1 VALUES (generate_series(1,5))"); +$node_publisher->wait_for_catchup('cross_sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM csch1.croot"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: cross-schema partition root remains excluded after DML' +); +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM csch2.cpart1"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: cross-schema partition remains excluded after DML via cascading root exclusion' +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION cross_sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION cross_sch_pub'); +$node_publisher->safe_psql('postgres', 'DROP SCHEMA csch1, csch2 CASCADE'); +$node_subscriber->safe_psql('postgres', 'DROP SCHEMA csch1, csch2 CASCADE'); + # ============================================ # Test when a subscription is subscribing to multiple publications # ============================================ @@ -254,6 +457,7 @@ $node_publisher->safe_psql( DROP PUBLICATION tap_pub2; TRUNCATE tab1; )); +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_subscriber->safe_psql('postgres', qq(TRUNCATE tab1)); # OK when a table is excluded by pub1 EXCEPT clause, but it is included by pub2 @@ -282,6 +486,59 @@ $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); +# OK when a table is excluded by the EXCEPT clause of one schema publication, +# but it is included by another publication that publishes the same schema in +# full. Inclusion wins, so the table is replicated. +$node_publisher->safe_psql( + 'postgres', qq( + CREATE SCHEMA msch; + CREATE TABLE msch.tab_excl (a int); + INSERT INTO msch.tab_excl VALUES (1); + CREATE PUBLICATION tap_pub_sch_with_except + FOR TABLES IN SCHEMA msch EXCEPT (TABLE msch.tab_excl); + CREATE PUBLICATION tap_pub_sch_without_except FOR TABLES IN SCHEMA msch; +)); + +$node_subscriber->safe_psql( + 'postgres', qq( + CREATE SCHEMA msch; + CREATE TABLE msch.tab_excl (a int); +)); + +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION tap_sub_multi CONNECTION '$publisher_connstr' PUBLICATION tap_pub_sch_with_except, tap_pub_sch_without_except" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, + 'tap_sub_multi'); + +# The initial table sync must copy the excluded table too, because +# tap_pub_sch_without_except publishes it. +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM msch.tab_excl"); +is($result, qq(1), + 'initial sync copies a table excluded by one publication but included by another' +); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO msch.tab_excl VALUES (2); +)); +$node_publisher->wait_for_catchup('tap_sub_multi'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM msch.tab_excl"); +is($result, qq(2), + 'DML on a table excluded by one publication but included by another is replicated' +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub_multi'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub_sch_with_except'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub_sch_without_except'); +$node_publisher->safe_psql('postgres', 'DROP SCHEMA msch CASCADE'); +$node_subscriber->safe_psql('postgres', 'DROP SCHEMA msch CASCADE'); + $node_publisher->stop('fast'); done_testing(); -- 2.55.0
v27-0003-Add-EXCEPT-support-to-ALTER-PUBLICATION-SET-TABL.patch (application/octet-stream, 42.3K) download From 3da16d8dfb52bf65de1498fe99e6db271cb0ec5a Mon Sep 17 00:00:00 2001 From: Vignesh C <c_vigneshwaran@apple.com> Date: Fri, 14 Aug 2026 15:11:18 +0530 Subject: [PATCH v27 3/4] Add EXCEPT support to ALTER PUBLICATION SET TABLES IN SCHEMA Extend AlterPublicationExceptTables() with the AP_SetObjects case, which redefines the publication and replaces the entire EXCEPT list. Syntax: ALTER PUBLICATION pub SET TABLES IN SCHEMA s EXCEPT (TABLE t1); This patch also cleans up EXCEPT entries when a schema is dropped from the publication. --- src/backend/commands/publicationcmds.c | 319 +++++++++++++++++----- src/bin/psql/tab-complete.in.c | 17 ++ src/test/regress/expected/publication.out | 161 ++++++++++- src/test/regress/sql/publication.sql | 69 +++++ src/test/subscription/t/037_except.pl | 85 ++++++ 5 files changed, 575 insertions(+), 76 deletions(-) diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 30fccf68d1d..0f5412fc095 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -67,13 +67,14 @@ static void CloseTableList(List *rels); static void LockSchemaList(List *schemalist); static void PublicationAddTables(Oid pubid, List *rels, bool if_not_exists, AlterPublicationStmt *stmt); -static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok); +static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok, + bool delete_excluded); static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); static void PublicationAddExceptTables(Oid pubid, List *except_pubtables, - List *explicitrelids, - List *schemaidlist, - AlterPublicationStmt *stmt); + List *explicitrelids, + List *schemaidlist, + AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); static void AlterPublicationSchemas(AlterPublicationStmt *stmt, HeapTuple tup, List *schemaidlist, @@ -89,7 +90,12 @@ static void CheckExceptNotInTableList(List *except_rels, static void CheckExceptChildNotInSchemaList(Oid pubid, List *cross_schema_children, List *pubschemas, - List *except_rels); + List *except_rels, + bool existing_except_kept); +static void CheckExceptConflicts(Oid pubid, List *except_rels, + List *cross_schema_children, + List *explicitrelids, List *pubschemas, + bool existing_except_kept); static void ProcessSchemaExceptTables(Oid schemaid, List *except_tables, ParseState *pstate, List **schemas, List **schemas_with_except, @@ -264,9 +270,9 @@ ProcessSchemaExceptTables(Oid schemaid, List *except_tables, parser_errposition(pstate, eobj->location)); /* - * Remember that this EXCEPT entry is associated with a schema. This is - * used by OpenTableList() to skip inheritance children outside that - * schema. + * Remember that this EXCEPT entry is associated with a schema. This + * is used by OpenTableList() to skip inheritance children outside + * that schema. */ eobj->pubtable->except_in_schema = true; @@ -938,8 +944,9 @@ CheckExceptNotInTableList(List *except_rels, List *cross_schema_children, /* * An EXCEPT clause also applies to inheritance children of a parent * named without ONLY. Children in other schemas are not added to - * except_rels, but are still excluded by the EXCEPT clause. Explicitly - * publishing such a child therefore conflicts with the EXCEPT clause. + * except_rels, but are still excluded by the EXCEPT clause. + * Explicitly publishing such a child therefore conflicts with the + * EXCEPT clause. */ if (list_member_oid(cross_schema_children, explicitrelid)) ereport(ERROR, @@ -962,16 +969,18 @@ CheckExceptNotInTableList(List *except_rels, List *cross_schema_children, * the schemas that this statement publishes and those the publication already * publishes; ALTER PUBLICATION ... ADD names only the former. * - * If the child is excluded anyway, there is no conflict, since both sides - * agree. That is so when an EXCEPT clause of this statement names it, and also - * when the publication already holds an EXCEPT entry for it. + * If the child ends up excluded anyway, there is no conflict, since both sides + * agree. That is so when an EXCEPT clause of this statement names it, and, + * where existing_except_kept says such entries remain in force, when the + * publication already holds an EXCEPT entry for it. * * Conflicts with explicitly listed tables are handled by * CheckExceptNotInTableList(). */ static void CheckExceptChildNotInSchemaList(Oid pubid, List *cross_schema_children, - List *pubschemas, List *except_rels) + List *pubschemas, List *except_rels, + bool existing_except_kept) { foreach_oid(childrelid, cross_schema_children) { @@ -992,8 +1001,8 @@ CheckExceptChildNotInSchemaList(Oid pubid, List *cross_schema_children, } } - /* Or does the publication already exclude it? */ - if (!excluded && + /* Or is it already excluded, by an entry that remains in force? */ + if (!excluded && existing_except_kept && CheckPublicationRelEntry(pubid, childrelid, &is_except) && is_except) excluded = true; @@ -1013,13 +1022,56 @@ CheckExceptChildNotInSchemaList(Oid pubid, List *cross_schema_children, } } +/* + * Check that the EXCEPT entries do not conflict with the relations and + * schemas included by the publication after the statement completes. + * + * except_rels and cross_schema_children contain the EXCEPT entries collected + * by OpenTableList(), while explicitrelids contains explicitly included + * relations. + * + * pubschemas contains the schemas included by the publication after the + * statement. + * + * existing_except_kept says whether the EXCEPT entries the publication already + * holds are still in force once the statement completes. ADD only adds + * entries, so they are. SET replaces the whole list, so an existing entry may + * be one this statement drops, and must not be taken as agreement that a + * cross-schema child is excluded. + */ +static void +CheckExceptConflicts(Oid pubid, List *except_rels, + List *cross_schema_children, List *explicitrelids, + List *pubschemas, bool existing_except_kept) +{ + /* + * Validate that a table is not both explicitly included and excluded by + * the schema's EXCEPT clause. + */ + CheckExceptNotInTableList(except_rels, cross_schema_children, + explicitrelids); + + /* + * Validate that an inheritance child is not both excluded by an EXCEPT + * clause and included by its schema. + */ + CheckExceptChildNotInSchemaList(pubid, cross_schema_children, pubschemas, + except_rels, existing_except_kept); +} + /* * Add the EXCEPT tables of a statement's TABLES IN SCHEMA clauses to a * publication, after checking that the statement does not contradict itself. * * explicitrelids is the set of relations the statement publishes by name, and - * schemaidlist the schemas it publishes in full; both are needed to detect a - * table that would be published and excluded at the same time. + * pubschemas the schemas the publication publishes once the statement + * completes; both are needed to detect a table that would be published and + * excluded at the same time. See CheckExceptConflicts() for how callers pick + * pubschemas. + * + * This is for CREATE PUBLICATION and ALTER PUBLICATION ... ADD, which only add + * EXCEPT entries. ALTER PUBLICATION ... SET replaces them, and does its own + * reconciliation; see AlterPublicationSchemaExceptTables(). * * if_not_exists is false: an EXCEPT entry that is already present, or that * collides with an ordinary member, is a conflict worth reporting rather than @@ -1027,41 +1079,20 @@ CheckExceptChildNotInSchemaList(Oid pubid, List *cross_schema_children, */ static void PublicationAddExceptTables(Oid pubid, List *except_pubtables, - List *explicitrelids, List *schemaidlist, + List *explicitrelids, List *pubschemas, AlterPublicationStmt *stmt) { List *except_rels; List *cross_schema_children = NIL; - List *pubschemas; if (except_pubtables == NIL) return; except_rels = OpenTableList(except_pubtables, &cross_schema_children); - /* - * A table is published by this publication if the statement publishes its - * schema, or if the publication already published it. ALTER PUBLICATION - * ... ADD names only the schemas being added, so the catalog has to be - * consulted as well; otherwise a child in a schema that an earlier command - * added would not be recognised as a conflict. - */ - pubschemas = list_concat_unique_oid(list_copy(schemaidlist), - GetPublicationSchemas(pubid)); - - /* - * Validate that a table is not both explicitly included and excluded by - * the schema's EXCEPT clause. - */ - CheckExceptNotInTableList(except_rels, cross_schema_children, - explicitrelids); - - /* - * Validate that an inheritance child is not both excluded by an EXCEPT - * clause and included by its schema. - */ - CheckExceptChildNotInSchemaList(pubid, cross_schema_children, pubschemas, - except_rels); + CheckExceptConflicts(pubid, except_rels, cross_schema_children, + explicitrelids, pubschemas, + true /* existing_except_kept */ ); PublicationAddTables(pubid, except_rels, false, stmt); CloseTableList(except_rels); @@ -1305,6 +1336,11 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) LockSchemaList(schemaidlist); PublicationAddSchemas(puboid, schemaidlist, true, NULL); + /* + * The schemas this statement names are the publication's whole + * set; the pg_publication_namespace rows inserted just above are + * not visible to a catalog lookup within the same command. + */ PublicationAddExceptTables(puboid, except_pubtables, explicitrelids, schemaidlist, NULL); } @@ -1587,7 +1623,7 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, PublicationAddTables(pubid, rels, false, stmt); } else if (stmt->action == AP_DropObjects) - PublicationDropTables(pubid, rels, false); + PublicationDropTables(pubid, rels, false, false); else /* AP_SetObjects */ { List *oldrelids = NIL; @@ -1735,7 +1771,7 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, } /* And drop them. */ - PublicationDropTables(pubid, delrels, true); + PublicationDropTables(pubid, delrels, true, true); /* * Don't bother calculating the difference for adding, we'll catch and @@ -1837,8 +1873,8 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, /* * Increment the command counter so that is_schema_publication() in - * GetExcludedPublicationTables() can see the just-inserted schema - * rows when AlterPublicationSchemaExceptTables runs next. + * GetExcludedPublicationTables() can see the just-inserted schema rows + * when AlterPublicationSchemaExceptTables runs next. */ if (stmt->action == AP_AddObjects || stmt->action == AP_SetObjects) CommandCounterIncrement(); @@ -1856,16 +1892,18 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, */ static void AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, - HeapTuple tup, List *except_pubtables, - List *schemaidlist) + HeapTuple tup, List *except_pubtables, + List *schemaidlist) { Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); Oid pubid = pubform->oid; /* - * Nothing to do if no EXCEPT entries. + * Nothing to do if there are no EXCEPT entries, unless handling the SET + * command, because if the user has removed all exceptions we need to drop + * any existing ones. */ - if (!except_pubtables) + if (!except_pubtables && stmt->action != AP_SetObjects) return; /* @@ -1886,16 +1924,6 @@ AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); - /* - * XXX EXCEPT with SET is not currently implemented. Workaround: DROP and - * re-ADD the schema with the desired EXCEPT list. - */ - if (stmt->action == AP_SetObjects) - ereport(ERROR, - (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"), - errhint("Drop and re-add the schema with the desired EXCEPT list."))); - if (stmt->action == AP_AddObjects) { List *explicitrelids; @@ -1903,8 +1931,84 @@ AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, explicitrelids = GetIncludedPublicationRelations(pubid, PUBLICATION_PART_ROOT); + /* + * schemaidlist holds only the schemas being added, so read the whole + * set from the catalog: AlterPublicationSchemas() has applied the + * additions and incremented the command counter before calling us. + */ PublicationAddExceptTables(pubid, except_pubtables, explicitrelids, - schemaidlist, stmt); + GetPublicationSchemas(pubid), stmt); + } + else + { + List *oldexceptrelids = NIL; + List *newexceptrelids = NIL; + List *delrelids = NIL; + List *except_rels; + List *explicitrelids; + List *cross_schema_children = NIL; + + except_rels = OpenTableList(except_pubtables, &cross_schema_children); + + /* Collect OIDs of the desired new EXCEPT list. */ + foreach_ptr(PublicationRelInfo, pri, except_rels) + newexceptrelids = lappend_oid(newexceptrelids, + RelationGetRelid(pri->relation)); + + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + /* + * Check that the statement does not contradict itself. SET replaces + * the EXCEPT list rather than adding to it, so the entries the + * publication currently holds cannot be taken as agreement: one of + * them may be dropped below. + */ + CheckExceptConflicts(pubid, except_rels, cross_schema_children, + explicitrelids, schemaidlist, + false /* existing_except_kept */ ); + + + /* + * Get the current set of EXCEPT entries. Only FOR ALL TABLES and + * schema-level publications can have EXCEPT entries; for any other + * publication type oldexceptrelids stays NIL. + */ + if (GetPublication(pubid)->alltables || is_schema_publication(pubid)) + oldexceptrelids = GetExcludedPublicationTables(pubid, + PUBLICATION_PART_ROOT); + /* Build a list of old EXCEPT entries not present in the new list. */ + foreach_oid(oldrelid, oldexceptrelids) + { + if (!list_member_oid(newexceptrelids, oldrelid)) + delrelids = lappend_oid(delrelids, oldrelid); + } + + /* Drop old EXCEPT entries not present in the new list. */ + foreach_oid(relid, delrelids) + { + Oid proid; + ObjectAddress obj; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + /* + * Add the new EXCEPT entries. if_not_exists is true here because an + * entry present in both the old and the new list is not dropped above + * and so is still there. + */ + PublicationAddTables(pubid, except_rels, true, stmt); + + CloseTableList(except_rels); } } @@ -2386,17 +2490,17 @@ OpenTableList(List *tables, List **cross_schema_children) CHECK_FOR_INTERRUPTS(); /* - * An EXCEPT clause also excludes inheritance children in other - * schemas. Keep track of such children separately so the - * caller can detect if the same statement also includes them - * through another table or schema clause. + * An EXCEPT clause also excludes inheritance children in + * other schemas. Keep track of such children separately so + * the caller can detect if the same statement also includes + * them through another table or schema clause. */ if (t->except_in_schema && get_rel_namespace(childrelid) != parentnsp) { if (cross_schema_children) *cross_schema_children = lappend_oid(*cross_schema_children, - childrelid); + childrelid); continue; } @@ -2540,33 +2644,69 @@ PublicationAddTables(Oid pubid, List *rels, bool if_not_exists, /* * Remove listed tables from the publication. + * + * delete_excluded controls how EXCEPT (prexcept=true) rows are handled: + * true - delete them silently. Used by the SET path to clear stale + * EXCEPT rows when ALTER PUBLICATION ... SET replaces or removes + * the EXCEPT clause. + * false - treat them as "not a member". Used by ALTER ... DROP TABLE: an + * EXCEPT entry is not something DROP TABLE is expected to remove. */ static void -PublicationDropTables(Oid pubid, List *rels, bool missing_ok) +PublicationDropTables(Oid pubid, List *rels, bool missing_ok, + bool delete_excluded) { ObjectAddress obj; ListCell *lc; - Oid prid; foreach(lc, rels) { PublicationRelInfo *pubrel = (PublicationRelInfo *) lfirst(lc); Relation rel = pubrel->relation; Oid relid = RelationGetRelid(rel); + HeapTuple tup; + Form_pg_publication_rel pubrelform; + Oid prid = InvalidOid; + bool is_except = false; if (pubrel->columns) ereport(ERROR, errcode(ERRCODE_SYNTAX_ERROR), errmsg("column list must not be specified in ALTER PUBLICATION ... DROP")); - prid = GetSysCacheOid2(PUBLICATIONRELMAP, Anum_pg_publication_rel_oid, - ObjectIdGetDatum(relid), - ObjectIdGetDatum(pubid)); - if (!OidIsValid(prid)) + tup = SearchSysCache2(PUBLICATIONRELMAP, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (HeapTupleIsValid(tup)) + { + pubrelform = (Form_pg_publication_rel) GETSTRUCT(tup); + is_except = pubrelform->prexcept; + prid = pubrelform->oid; + ReleaseSysCache(tup); + } + + /* + * DROP TABLE operates only on regular member rows. A missing row and + * an EXCEPT row both mean the table isn't currently published, but we + * distinguish them so the EXCEPT case can carry a hint pointing the + * user at the EXCEPT clause. The SET-cleanup caller (delete_excluded + * = true) intends to remove EXCEPT rows and so bypasses the EXCEPT + * half of this check. + */ + if (!OidIsValid(prid) || (is_except && !delete_excluded)) { if (missing_ok) continue; + if (is_except) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("cannot drop table \"%s\" from publication \"%s\"", + RelationGetQualifiedRelationName(rel), + get_publication_name(pubid, false)), + errdetail("The table is currently named in an EXCEPT clause of the publication."), + errhint("Change the EXCEPT clause using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT."))); + ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("relation \"%s\" is not part of the publication", @@ -2622,6 +2762,7 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) foreach(lc, schemas) { Oid schemaid = lfirst_oid(lc); + List *except_relids; psid = GetSysCacheOid2(PUBLICATIONNAMESPACEMAP, Anum_pg_publication_namespace_oid, @@ -2638,8 +2779,40 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) get_namespace_name(schemaid)))); } + /* + * Collect EXCEPT entries for tables belonging to this schema before + * removing the schema entry. + */ + except_relids = GetExcludedPublicationTables(pubid, PUBLICATION_PART_ROOT); + ObjectAddressSet(obj, PublicationNamespaceRelationId, psid); performDeletion(&obj, DROP_CASCADE, 0); + + /* + * Drop any prexcept rows for tables belonging to this schema. These + * rows have no pg_depend entry pointing at the + * pg_publication_namespace row, so they are not cascaded by the + * performDeletion() call above and must be cleaned up explicitly. + */ + foreach_oid(relid, except_relids) + { + Oid proid; + + if (get_rel_namespace(relid) != schemaid) + continue; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + list_free(except_relids); } } diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index 6d857865d6b..d7a083ea871 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2376,6 +2376,23 @@ match_previous_words(int pattern_id, } else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) COMPLETE_WITH(")"); + /* After a single schema name in SET context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 5ef61587a15..6a851d044cd 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -671,14 +671,14 @@ DROP PUBLICATION testpub_except_alter1; CREATE PUBLICATION testpub_except_alter2 FOR TABLE pub_test.testpub_tbl_s1; ALTER PUBLICATION testpub_except_alter2 SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); -ERROR: EXCEPT clause is not supported with SET in ALTER PUBLICATION -HINT: Drop and re-add the schema with the desired EXCEPT list. \dRp+ testpub_except_alter2 Publication testpub_except_alter2 Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description --------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- regress_publication_user | f | f | t | t | t | t | none | f | -Tables: +Tables from schemas: + "pub_test" +Except tables: "pub_test.testpub_tbl_s1" DROP PUBLICATION testpub_except_alter2; @@ -753,6 +753,52 @@ Except tables: "pub_test.testpub_inh_sibling" "public.testpub_inh_child" +DROP PUBLICATION testpub_inh; +-- SET replaces the EXCEPT list rather than adding to it, so an entry the +-- publication currently holds cannot excuse a conflict: it may be one that this +-- same statement drops. +CREATE PUBLICATION testpub_inh + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_inh_parent), + TABLES IN SCHEMA public EXCEPT (TABLE testpub_inh_child); +-- fail: dropping public's EXCEPT clause would leave testpub_inh_child published +-- while pub_test's clause still covers it +ALTER PUBLICATION testpub_inh + SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_inh_parent), + TABLES IN SCHEMA public; +ERROR: table "public.testpub_inh_child" cannot be both published and excluded +DETAIL: It inherits from a table named in the EXCEPT clause of another schema, and its own schema "public" is published in full. +HINT: Use ONLY in the EXCEPT clause to exclude just the parent, or arrange for schema "public" to exclude this table as well. +-- ok: the new EXCEPT list still excludes it, so both clauses agree +ALTER PUBLICATION testpub_inh + SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_inh_parent), + TABLES IN SCHEMA public EXCEPT (TABLE testpub_inh_child); +\dRp+ testpub_inh + Publication testpub_inh + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_inh_parent" + "pub_test.testpub_inh_sibling" + "public.testpub_inh_child" + +-- ok: public is no longer published, so nothing is both published and excluded +ALTER PUBLICATION testpub_inh + SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_inh_parent); +\dRp+ testpub_inh + Publication testpub_inh + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_inh_parent" + "pub_test.testpub_inh_sibling" + DROP PUBLICATION testpub_inh; DROP TABLE testpub_inh_child, pub_test.testpub_inh_sibling, pub_test.testpub_inh_parent; @@ -814,6 +860,115 @@ Except tables: "pub_test.testpub_tbl_s1" "pub_test.testpub_tbl_s2" +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s2" + +-- fail: table in EXCEPT clause also appears in the explicit table list +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot be both published and excluded +-- fail: explicit partition + EXCEPT-ed root, given in a single SET statement +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_part_s, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ERROR: partition "pub_test.testpub_part_s" cannot be both published and excluded +DETAIL: Partition root "pub_test.testpub_parted_s" is named in the publication's EXCEPT clause for schema "pub_test". +-- fail: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 1: ...xcept SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.tes... + ^ +-- SET: unqualified name in EXCEPT is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- SET without EXCEPT clears the existing except list +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + +-- SET to a different schema removes old schema's EXCEPT entries +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA public; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "public" + +-- fail: nonexistent table in EXCEPT clause (SET path) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- SET: multiple schemas each with their own EXCEPT clause +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- fail: ALTER PUBLICATION ... DROP TABLE on an excluded table is rejected +-- with an EXCEPT-specific error. +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_tbl_s1; +ERROR: cannot drop table "pub_test.testpub_tbl_s1" from publication "testpub_alter_except" +DETAIL: The table is currently named in an EXCEPT clause of the publication. +HINT: Change the EXCEPT clause using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT. +-- the EXCEPT entry is still present after the rejected DROP TABLE +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- fail: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +ERROR: EXCEPT clause is not supported with DROP in ALTER PUBLICATION +-- DROP TABLES IN SCHEMA removes associated EXCEPT entries +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "public" +Except tables: + "public.testpub_tbl1" + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 005d40c5c82..64b5d3c3864 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -383,6 +383,28 @@ CREATE PUBLICATION testpub_inh TABLES IN SCHEMA public EXCEPT (TABLE testpub_inh_child); \dRp+ testpub_inh DROP PUBLICATION testpub_inh; + +-- SET replaces the EXCEPT list rather than adding to it, so an entry the +-- publication currently holds cannot excuse a conflict: it may be one that this +-- same statement drops. +CREATE PUBLICATION testpub_inh + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_inh_parent), + TABLES IN SCHEMA public EXCEPT (TABLE testpub_inh_child); +-- fail: dropping public's EXCEPT clause would leave testpub_inh_child published +-- while pub_test's clause still covers it +ALTER PUBLICATION testpub_inh + SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_inh_parent), + TABLES IN SCHEMA public; +-- ok: the new EXCEPT list still excludes it, so both clauses agree +ALTER PUBLICATION testpub_inh + SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_inh_parent), + TABLES IN SCHEMA public EXCEPT (TABLE testpub_inh_child); +\dRp+ testpub_inh +-- ok: public is no longer published, so nothing is both published and excluded +ALTER PUBLICATION testpub_inh + SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_inh_parent); +\dRp+ testpub_inh +DROP PUBLICATION testpub_inh; DROP TABLE testpub_inh_child, pub_test.testpub_inh_sibling, pub_test.testpub_inh_parent; @@ -429,6 +451,53 @@ ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_parted_s; ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); \dRp+ testpub_alter_except +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + +-- fail: table in EXCEPT clause also appears in the explicit table list +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: explicit partition + EXCEPT-ed root, given in a single SET statement +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_part_s, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); + +-- fail: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- SET: unqualified name in EXCEPT is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +\dRp+ testpub_alter_except + +-- SET without EXCEPT clears the existing except list +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + +-- SET to a different schema removes old schema's EXCEPT entries +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA public; +\dRp+ testpub_alter_except + +-- fail: nonexistent table in EXCEPT clause (SET path) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- SET: multiple schemas each with their own EXCEPT clause +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_alter_except + +-- fail: ALTER PUBLICATION ... DROP TABLE on an excluded table is rejected +-- with an EXCEPT-specific error. +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_tbl_s1; +-- the EXCEPT entry is still present after the rejected DROP TABLE +\dRp+ testpub_alter_except + +-- fail: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); + +-- DROP TABLES IN SCHEMA removes associated EXCEPT entries +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index ed931d0d970..f981bcd0003 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -376,6 +376,61 @@ $result = is($result, qq(0), 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); +# SET: replace the except list; tab_excluded is now included and tab_published is excluded. +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_published)" +); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (7); + INSERT INTO sch1.tab_excluded VALUES (7); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded WHERE a = 7"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: newly included table is replicated' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published WHERE a = 7"); +is($result, qq(0), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: now-excluded table is not replicated' +); + +# SET without EXCEPT: clears the except list; both tables are now published. +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1"); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (8); + INSERT INTO sch1.tab_excluded VALUES (8); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published WHERE a = 8"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_published replicated after except list cleared' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded WHERE a = 8"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_excluded replicated after except list cleared' +); + $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); @@ -571,6 +626,36 @@ $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub_sch_without_exc $node_publisher->safe_psql('postgres', 'DROP SCHEMA msch CASCADE'); $node_subscriber->safe_psql('postgres', 'DROP SCHEMA msch CASCADE'); +# OK when a table is excluded by a TABLES IN SCHEMA EXCEPT publication, +# but is included by another publication. +$node_publisher->safe_psql('postgres', 'TRUNCATE tab1'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE tab1'); + +$node_publisher->safe_psql( + 'postgres', qq( + CREATE PUBLICATION tap_pub1 FOR TABLES IN SCHEMA public EXCEPT (TABLE public.tab1); + CREATE PUBLICATION tap_pub2 FOR TABLE tab1; + INSERT INTO tab1 VALUES(1); +)); +$node_subscriber->psql('postgres', + "CREATE SUBSCRIPTION tap_sub CONNECTION '$publisher_connstr' PUBLICATION tap_pub1, tap_pub2" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'tap_sub'); + +$node_publisher->safe_psql('postgres', qq(INSERT INTO tab1 VALUES(2))); +$node_publisher->wait_for_catchup('tap_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT * FROM tab1 ORDER BY a"); +is( $result, qq(1 +2), + "TABLES IN SCHEMA EXCEPT: table excluded in schema pub but included by another pub is replicated" +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); + $node_publisher->stop('fast'); done_testing(); -- 2.55.0
v27-0004-Documentation-Patch.patch (application/octet-stream, 11.4K) download From ea6f6416ac86e6c080cc84f3ea7777aca84cfe21 Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Thu, 30 Jul 2026 10:15:42 +0530 Subject: [PATCH v27 4/4] Documentation Patch --- doc/src/sgml/logical-replication.sgml | 3 +- doc/src/sgml/ref/alter_publication.sgml | 54 +++++++++++++++++++++++- doc/src/sgml/ref/create_publication.sgml | 42 ++++++++++++++---- 3 files changed, 87 insertions(+), 12 deletions(-) diff --git a/doc/src/sgml/logical-replication.sgml b/doc/src/sgml/logical-replication.sgml index 3a61e2d6889..eaf2d814ac6 100644 --- a/doc/src/sgml/logical-replication.sgml +++ b/doc/src/sgml/logical-replication.sgml @@ -117,7 +117,8 @@ or <literal>FOR ALL SEQUENCES</literal>. Unlike tables, sequences can be synchronized at any time. For more information, see <xref linkend="logical-replication-sequences"/>. When a publication is - created with <literal>FOR ALL TABLES</literal>, a table or set of tables can + created with <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal>, a table or set of tables can be explicitly excluded from publication using the <link linkend="sql-createpublication-params-for-except-table"><literal>EXCEPT</literal></link> clause. diff --git a/doc/src/sgml/ref/alter_publication.sgml b/doc/src/sgml/ref/alter_publication.sgml index d2898d2633e..4aec48e5e48 100644 --- a/doc/src/sgml/ref/alter_publication.sgml +++ b/doc/src/sgml/ref/alter_publication.sgml @@ -31,7 +31,7 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA <replaceable class="parameter">tables_in_schema</replaceable> [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -47,6 +47,10 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <replaceable class="parameter">table_object</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] [ WHERE ( <replaceable class="parameter">expression</replaceable> ) ] +<phrase>and <replaceable class="parameter">tables_in_schema</replaceable> is:</phrase> + + { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] + <phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> TABLE <replaceable class="parameter">table_object</replaceable> [, ... ] @@ -69,6 +73,9 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r The first two variants modify which tables/schemas are part of the publication. The <literal>ADD</literal> and <literal>DROP</literal> clauses will add and remove one or more tables/schemas from the publication. + The <literal>EXCEPT</literal> clause can be used with + <literal>ADD TABLES IN SCHEMA</literal> to exclude specific tables from a + schema-level publication. </para> <para> @@ -93,7 +100,11 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r used with a publication defined with <literal>FOR TABLE</literal> or <literal>FOR TABLES IN SCHEMA</literal>, replaces the list of tables/schemas in the publication with the specified list; the existing tables or schemas - that were present in the publication will be removed. + that were present in the publication will be removed. When + <literal>SET TABLES IN SCHEMA</literal> is used with an + <literal>EXCEPT</literal> clause, the excluded tables for each schema are + replaced with the specified list; if <literal>EXCEPT</literal> is omitted + for a schema, any existing exclusions for that schema are cleared. </para> <para> @@ -210,6 +221,26 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r </listitem> </varlistentry> + <varlistentry id="sql-alterpublication-params-except"> + <term><literal>EXCEPT</literal></term> + <listitem> + <para> + When used with <literal>ADD TABLES IN SCHEMA</literal> + or <literal>SET TABLES IN SCHEMA</literal>, specifies tables to be + excluded from the publication. Each named table must belong to the + schema specified in the same <literal>TABLES IN SCHEMA</literal> clause. + Table names may be schema-qualified or unqualified; unqualified names + are implicitly qualified with the schema named in the same clause. See + <xref linkend="sql-createpublication"/> for further details on the + semantics of <literal>EXCEPT</literal>. + </para> + <para> + Dropping a table always removes it from the <literal>EXCEPT</literal> + clause. + </para> + </listitem> + </varlistentry> + <varlistentry id="sql-alterpublication-params-set"> <term><literal>SET ( <replaceable class="parameter">publication_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] )</literal></term> <listitem> @@ -300,6 +331,25 @@ ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA marketing, sales; </programlisting> </para> + <para> + Add schema <structname>sales</structname> to the publication + <structname>sales_publication</structname>, excluding the + <structname>sales.internal</structname> and + <structname>sales.drafts</structname> tables: +<programlisting> +ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA sales EXCEPT (TABLE internal, drafts); +</programlisting> + </para> + + <para> + Replace the schema list of <structname>sales_publication</structname> with + only schema <structname>sales</structname>, excluding only + <structname>sales.drafts</structname> table: +<programlisting> +ALTER PUBLICATION sales_publication SET TABLES IN SCHEMA sales EXCEPT (TABLE drafts); +</programlisting> + </para> + <para> Add tables <structname>users</structname>, <structname>departments</structname> and schema diff --git a/doc/src/sgml/ref/create_publication.sgml b/doc/src/sgml/ref/create_publication.sgml index 35c28006f60..5b128694ad0 100644 --- a/doc/src/sgml/ref/create_publication.sgml +++ b/doc/src/sgml/ref/create_publication.sgml @@ -28,7 +28,7 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA <replaceable class="parameter">tables_in_schema</replaceable> [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -39,6 +39,10 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <replaceable class="parameter">table_object</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] [ WHERE ( <replaceable class="parameter">expression</replaceable> ) ] +<phrase>and <replaceable class="parameter">tables_in_schema</replaceable> is:</phrase> + + { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] + <phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> TABLE <replaceable class="parameter">table_object</replaceable> [, ... ] @@ -172,6 +176,8 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <para> Marks the publication as one that replicates changes for all tables in the specified list of schemas, including tables created in the future. + Tables listed in the <literal>EXCEPT</literal> clause for a given schema + are excluded from the publication. </para> <para> @@ -203,7 +209,7 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <para> Marks the publication as one that replicates changes for all tables in the database, including tables created in the future. Tables listed in - <literal>EXCEPT</literal> clause are excluded from the publication. + the <literal>EXCEPT</literal> clause are excluded from the publication. </para> </listitem> </varlistentry> @@ -228,13 +234,21 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <listitem> <para> This clause specifies a list of tables to be excluded from the - publication. + publication. It can be used with <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal>. For <literal>FOR TABLES IN + SCHEMA</literal>, the exclusion applies only to tables in the schema + associated with the <literal>EXCEPT</literal> clause. </para> <para> - Once a table is excluded, the exclusion applies to that table - regardless of its name or schema. Renaming the table or moving it to - another schema using <command>ALTER TABLE ... SET SCHEMA</command> does - not remove the exclusion. + Once a table is excluded under <literal>FOR ALL TABLES</literal>, the + exclusion applies to that table regardless of its name or schema. + Renaming the table or moving it to another schema using + <command>ALTER TABLE ... SET SCHEMA</command> does not remove the + exclusion. However, for <literal>FOR TABLES IN SCHEMA</literal>, because + the <literal>EXCEPT</literal> is schema-scoped, moving a schema-excluded + table to another schema does remove the exclusion; if the table is later + moved back, the exclusion is not restored and must be re-established + with <command>ALTER PUBLICATION</command>. </para> <para> For inherited tables, if <literal>ONLY</literal> is specified before the @@ -247,8 +261,9 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> </para> <para> For partitioned tables, only the root partitioned table may be specified - in <literal>EXCEPT</literal>. Doing so excludes the root table and - all of its partitions from replication. The optional + in <literal>EXCEPT</literal>. Excluding the root table automatically + excludes all of its partitions from replication, even those in + schemas that are otherwise included in the publication. The optional <literal>ONLY</literal> and <literal>*</literal> has no effect for partitioned tables. </para> @@ -552,6 +567,15 @@ CREATE PUBLICATION production_publication FOR TABLE users, departments, TABLES I CREATE PUBLICATION sales_publication FOR TABLES IN SCHEMA marketing, sales; </programlisting></para> + <para> + Create a publication that publishes all changes for all the tables present in + the schema <structname>sales</structname>, except + <structname>internal</structname> and <structname>drafts</structname>: +<programlisting> +CREATE PUBLICATION sales_filtered FOR TABLES IN SCHEMA sales EXCEPT (TABLE internal, drafts); +</programlisting> + </para> + <para> Create a publication that publishes all changes for table <structname>users</structname>, but replicates only columns <structname>user_id</structname> and -- 2.55.0
v27-0002-Add-EXCEPT-support-to-ALTER-PUBLICATION-ADD-TABL.patch (application/octet-stream, 30.2K) download From 71152be738be30272341890a93ef0309e358b7e6 Mon Sep 17 00:00:00 2001 From: Vignesh C <c_vigneshwaran@apple.com> Date: Fri, 14 Aug 2026 14:50:02 +0530 Subject: [PATCH v27 2/4] Add EXCEPT support to ALTER PUBLICATION ADD TABLES IN SCHEMA Extend the EXCEPT clause support to allow tables to be excluded when adding a schema to a publication via ALTER PUBLICATION ... ADD. Syntax: ALTER PUBLICATION pub ADD TABLES IN SCHEMA s EXCEPT (TABLE s.t1); Since pg_dump uses ALTER PUBLICATION ... ADD, support for it is included in this patch. --- src/backend/catalog/pg_publication.c | 19 +- src/backend/commands/publicationcmds.c | 211 +++++++++++++++++----- src/bin/pg_dump/pg_dump.c | 30 ++- src/bin/pg_dump/t/002_pg_dump.pl | 24 +++ src/bin/psql/tab-complete.in.c | 17 ++ src/test/regress/expected/publication.out | 68 ++++++- src/test/regress/sql/publication.sql | 45 ++++- src/test/subscription/t/037_except.pl | 32 ++++ 8 files changed, 390 insertions(+), 56 deletions(-) diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index 81e4166cfee..12a360347d2 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -749,15 +749,18 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, * here, as CreatePublication() function invalidates all relations as part * of defining a FOR ALL TABLES publication. * - * For ALTER PUBLICATION, invalidation is needed only when adding an - * EXCEPT table to a publication already marked as ALL TABLES. For - * publications that were originally empty or defined as ALL SEQUENCES and - * are being converted to ALL TABLES, invalidation is skipped here, as - * AlterPublicationAllFlags() function invalidates all relations while - * marking the publication as ALL TABLES publication. + * For ALTER PUBLICATION, invalidation is needed when adding an EXCEPT + * table to either a FOR ALL TABLES publication (pub->alltables is true) + * or a FOR TABLES IN SCHEMA publication (is_schema_publication is true). + * The exception: when a publication is being converted to FOR ALL TABLES + * (pub->alltables is still false at this point), + * AlterPublicationAllFlags() will perform a full invalidation, so we skip + * it here. */ - inval_except_table = (alter_stmt != NULL) && pub->alltables && - (alter_stmt->for_all_tables && pri->except); + inval_except_table = (alter_stmt != NULL) && pri->except && + (pub->alltables + ? alter_stmt->for_all_tables + : is_schema_publication(pubid)); if (!pri->except || inval_except_table) { diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 77a829bc1bd..30fccf68d1d 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -70,13 +70,25 @@ static void PublicationAddTables(Oid pubid, List *rels, bool if_not_exists, static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok); static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); +static void PublicationAddExceptTables(Oid pubid, List *except_pubtables, + List *explicitrelids, + List *schemaidlist, + AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); +static void AlterPublicationSchemas(AlterPublicationStmt *stmt, + HeapTuple tup, List *schemaidlist, + List *except_pubtables); +static void AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, + List *except_pubtables, + List *schemaidlist); static char defGetGeneratedColsOption(DefElem *def); static void CheckExceptNotInTableList(List *except_rels, List *cross_schema_children, List *explicitrelids); -static void CheckExceptChildNotInSchemaList(List *cross_schema_children, - List *schemaidlist, +static void CheckExceptChildNotInSchemaList(Oid pubid, + List *cross_schema_children, + List *pubschemas, List *except_rels); static void ProcessSchemaExceptTables(Oid schemaid, List *except_tables, ParseState *pstate, List **schemas, @@ -941,31 +953,36 @@ CheckExceptNotInTableList(List *except_rels, List *cross_schema_children, } /* - * Check that an EXCEPT clause does not conflict with a TABLES IN SCHEMA - * clause in the same statement. + * Check that an EXCEPT clause does not conflict with a schema published by the + * publication. * * cross_schema_children contains inheritance children excluded through a * parent in another schema. If such a child is also included through a - * TABLES IN SCHEMA clause in the same statement, report the conflict. + * published schema, report the conflict. pubschemas must therefore cover both + * the schemas that this statement publishes and those the publication already + * publishes; ALTER PUBLICATION ... ADD names only the former. * - * If the child's schema also has an EXCEPT clause specified through TABLES - * IN SCHEMA, there is no conflict, since both clauses exclude the child. + * If the child is excluded anyway, there is no conflict, since both sides + * agree. That is so when an EXCEPT clause of this statement names it, and also + * when the publication already holds an EXCEPT entry for it. * * Conflicts with explicitly listed tables are handled by * CheckExceptNotInTableList(). */ static void -CheckExceptChildNotInSchemaList(List *cross_schema_children, List *schemaidlist, - List *except_rels) +CheckExceptChildNotInSchemaList(Oid pubid, List *cross_schema_children, + List *pubschemas, List *except_rels) { foreach_oid(childrelid, cross_schema_children) { Oid childnsp = get_rel_namespace(childrelid); bool excluded = false; + bool is_except; - if (!list_member_oid(schemaidlist, childnsp)) + if (!list_member_oid(pubschemas, childnsp)) continue; + /* Does an EXCEPT clause of this statement exclude it as well? */ foreach_ptr(PublicationRelInfo, pri, except_rels) { if (RelationGetRelid(pri->relation) == childrelid) @@ -975,6 +992,12 @@ CheckExceptChildNotInSchemaList(List *cross_schema_children, List *schemaidlist, } } + /* Or does the publication already exclude it? */ + if (!excluded && + CheckPublicationRelEntry(pubid, childrelid, &is_except) && + is_except) + excluded = true; + if (excluded) continue; @@ -985,11 +1008,65 @@ CheckExceptChildNotInSchemaList(List *cross_schema_children, List *schemaidlist, get_rel_name(childrelid))), errdetail("It inherits from a table named in the EXCEPT clause of another schema, and its own schema \"%s\" is published in full.", get_namespace_name(childnsp)), - errhint("Use ONLY in the EXCEPT clause to exclude just the parent, or name this table in the EXCEPT clause of schema \"%s\".", + errhint("Use ONLY in the EXCEPT clause to exclude just the parent, or arrange for schema \"%s\" to exclude this table as well.", get_namespace_name(childnsp))); } } +/* + * Add the EXCEPT tables of a statement's TABLES IN SCHEMA clauses to a + * publication, after checking that the statement does not contradict itself. + * + * explicitrelids is the set of relations the statement publishes by name, and + * schemaidlist the schemas it publishes in full; both are needed to detect a + * table that would be published and excluded at the same time. + * + * if_not_exists is false: an EXCEPT entry that is already present, or that + * collides with an ordinary member, is a conflict worth reporting rather than + * something to skip silently. + */ +static void +PublicationAddExceptTables(Oid pubid, List *except_pubtables, + List *explicitrelids, List *schemaidlist, + AlterPublicationStmt *stmt) +{ + List *except_rels; + List *cross_schema_children = NIL; + List *pubschemas; + + if (except_pubtables == NIL) + return; + + except_rels = OpenTableList(except_pubtables, &cross_schema_children); + + /* + * A table is published by this publication if the statement publishes its + * schema, or if the publication already published it. ALTER PUBLICATION + * ... ADD names only the schemas being added, so the catalog has to be + * consulted as well; otherwise a child in a schema that an earlier command + * added would not be recognised as a conflict. + */ + pubschemas = list_concat_unique_oid(list_copy(schemaidlist), + GetPublicationSchemas(pubid)); + + /* + * Validate that a table is not both explicitly included and excluded by + * the schema's EXCEPT clause. + */ + CheckExceptNotInTableList(except_rels, cross_schema_children, + explicitrelids); + + /* + * Validate that an inheritance child is not both excluded by an EXCEPT + * clause and included by its schema. + */ + CheckExceptChildNotInSchemaList(pubid, cross_schema_children, pubschemas, + except_rels); + + PublicationAddTables(pubid, except_rels, false, stmt); + CloseTableList(except_rels); +} + /* * Given a list of tables that are going to be added to a publication, * verify that they fulfill the necessary preconditions, namely: no tables @@ -1228,31 +1305,8 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) LockSchemaList(schemaidlist); PublicationAddSchemas(puboid, schemaidlist, true, NULL); - if (except_pubtables != NIL) - { - List *except_rels; - List *cross_schema_children = NIL; - - except_rels = OpenTableList(except_pubtables, - &cross_schema_children); - - /* - * Validate that a table is not both explicitly included and - * excluded by the schema's EXCEPT clause. - */ - CheckExceptNotInTableList(except_rels, cross_schema_children, - explicitrelids); - - /* - * Validate that an inheritance child is not both excluded by - * an EXCEPT clause and included by its schema. - */ - CheckExceptChildNotInSchemaList(cross_schema_children, - schemaidlist, except_rels); - - PublicationAddTables(puboid, except_rels, false, NULL); - CloseTableList(except_rels); - } + PublicationAddExceptTables(puboid, except_pubtables, + explicitrelids, schemaidlist, NULL); } } @@ -1702,7 +1756,8 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, */ static void AlterPublicationSchemas(AlterPublicationStmt *stmt, - HeapTuple tup, List *schemaidlist) + HeapTuple tup, List *schemaidlist, + List *except_pubtables) { Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); @@ -1779,6 +1834,78 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, */ PublicationAddSchemas(pubform->oid, schemaidlist, true, stmt); } + + /* + * Increment the command counter so that is_schema_publication() in + * GetExcludedPublicationTables() can see the just-inserted schema + * rows when AlterPublicationSchemaExceptTables runs next. + */ + if (stmt->action == AP_AddObjects || stmt->action == AP_SetObjects) + CommandCounterIncrement(); + + AlterPublicationSchemaExceptTables(stmt, tup, except_pubtables, schemaidlist); +} + +/* + * Alter the EXCEPT list of a schema-level publication. + * + * Adds, removes, or replaces except-table entries in pg_publication_rel + * (rows with prexcept = true). These entries suppress publication of the + * named tables that would otherwise be covered by a FOR TABLES IN SCHEMA + * clause. + */ +static void +AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, List *except_pubtables, + List *schemaidlist) +{ + Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); + Oid pubid = pubform->oid; + + /* + * Nothing to do if no EXCEPT entries. + */ + if (!except_pubtables) + return; + + /* + * This function handles EXCEPT entries for schema-level publications + * only. For FOR ALL TABLES publications, EXCEPT entries are already + * processed by AlterPublicationTables(). + */ + if (schemaidlist == NIL && !is_schema_publication(pubid)) + return; + + /* + * Dropping a schema from a publication removes all its EXCEPT entries via + * cascade. The concept of "drop all schema tables from the publication + * EXCEPT these ones" is not supported. + */ + if (stmt->action == AP_DropObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); + + /* + * XXX EXCEPT with SET is not currently implemented. Workaround: DROP and + * re-ADD the schema with the desired EXCEPT list. + */ + if (stmt->action == AP_SetObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"), + errhint("Drop and re-add the schema with the desired EXCEPT list."))); + + if (stmt->action == AP_AddObjects) + { + List *explicitrelids; + + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + PublicationAddExceptTables(pubid, except_pubtables, explicitrelids, + schemaidlist, stmt); + } } /* @@ -1960,12 +2087,12 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) else { List *relations = NIL; - List *exceptrelations = NIL; + List *except_pubtables = NIL; List *schemaidlist = NIL; Oid pubid = pubform->oid; ObjectsInPublicationToOids(stmt->pubobjects, pstate, &relations, - &exceptrelations, &schemaidlist); + &except_pubtables, &schemaidlist); CheckAlterPublication(stmt, tup, relations, schemaidlist); @@ -1988,10 +2115,12 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) errmsg("publication \"%s\" does not exist", stmt->pubname)); - relations = list_concat(relations, exceptrelations); + if (stmt->for_all_tables) + relations = list_concat(relations, except_pubtables); + AlterPublicationTables(stmt, tup, relations, pstate->p_sourcetext, schemaidlist != NIL); - AlterPublicationSchemas(stmt, tup, schemaidlist); + AlterPublicationSchemas(stmt, tup, schemaidlist, except_pubtables); AlterPublicationAllFlags(stmt, rel, tup); } diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c index feed88f9854..ddbd5e40285 100644 --- a/src/bin/pg_dump/pg_dump.c +++ b/src/bin/pg_dump/pg_dump.c @@ -4973,6 +4973,7 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) PublicationInfo *pubinfo = pubsinfo->publication; PQExpBuffer query; char *tag; + bool has_except = false; /* Do nothing if not dumping schema */ if (!dopt->dumpSchema) @@ -4983,7 +4984,34 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) query = createPQExpBuffer(); appendPQExpBuffer(query, "ALTER PUBLICATION %s ", fmtId(pubinfo->dobj.name)); - appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s;\n", fmtId(schemainfo->dobj.name)); + appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s", fmtId(schemainfo->dobj.name)); + + /* + * Append EXCEPT clause for any tables that belong to this schema + * and are excluded from the publication. + */ + for (SimplePtrListCell *cell = pubinfo->except_tables.head; cell; cell = cell->next) + { + TableInfo *tbinfo = (TableInfo *) cell->ptr; + + if (strcmp(tbinfo->dobj.namespace->dobj.name, schemainfo->dobj.name) == 0) + { + if (!has_except) + { + appendPQExpBufferStr(query, " EXCEPT ("); + has_except = true; + } + else + appendPQExpBufferStr(query, ", "); + + appendPQExpBuffer(query, "TABLE ONLY %s", fmtId(tbinfo->dobj.name)); + } + } + + if (has_except) + appendPQExpBufferStr(query, ")"); + + appendPQExpBufferStr(query, ";\n"); /* * There is no point in creating drop query as the drop is done by schema diff --git a/src/bin/pg_dump/t/002_pg_dump.pl b/src/bin/pg_dump/t/002_pg_dump.pl index 9258948b583..d18b3b0d7b9 100644 --- a/src/bin/pg_dump/t/002_pg_dump.pl +++ b/src/bin/pg_dump/t/002_pg_dump.pl @@ -3283,6 +3283,30 @@ my %tests = ( like => { %full_runs, section_post_data => 1, }, }, + 'CREATE PUBLICATION pub11' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub11 FOR TABLES IN SCHEMA dump_test EXCEPT (TABLE test_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub11 WITH (publish = 'insert, update, delete, truncate');\E + .*? + \QALTER PUBLICATION pub11 ADD TABLES IN SCHEMA dump_test EXCEPT (TABLE ONLY test_table);\E + /xms, + like => { %full_runs, section_post_data => 1, }, + }, + + 'CREATE PUBLICATION pub12' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub12 FOR TABLES IN SCHEMA dump_test EXCEPT (TABLE test_table, dump_test.test_second_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub12 WITH (publish = 'insert, update, delete, truncate');\E + .*? + \QALTER PUBLICATION pub12 ADD TABLES IN SCHEMA dump_test EXCEPT (TABLE ONLY test_table, TABLE ONLY test_second_table);\E + /xms, + like => { %full_runs, section_post_data => 1, }, + }, + 'CREATE SUBSCRIPTION sub1' => { create_order => 50, create_sql => 'CREATE SUBSCRIPTION sub1 diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index f069e2654cc..6d857865d6b 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2359,6 +2359,23 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); + /* After a single schema name in ADD context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 6befa549ae6..5ef61587a15 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -671,14 +671,14 @@ DROP PUBLICATION testpub_except_alter1; CREATE PUBLICATION testpub_except_alter2 FOR TABLE pub_test.testpub_tbl_s1; ALTER PUBLICATION testpub_except_alter2 SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: EXCEPT clause is not supported with SET in ALTER PUBLICATION +HINT: Drop and re-add the schema with the desired EXCEPT list. \dRp+ testpub_except_alter2 Publication testpub_except_alter2 Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description --------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- regress_publication_user | f | f | t | t | t | t | none | f | -Tables from schemas: - "pub_test" -Except tables: +Tables: "pub_test.testpub_tbl_s1" DROP PUBLICATION testpub_except_alter2; @@ -709,7 +709,7 @@ CREATE PUBLICATION testpub_inh TABLES IN SCHEMA public; ERROR: table "public.testpub_inh_child" cannot be both published and excluded DETAIL: It inherits from a table named in the EXCEPT clause of another schema, and its own schema "public" is published in full. -HINT: Use ONLY in the EXCEPT clause to exclude just the parent, or name this table in the EXCEPT clause of schema "public". +HINT: Use ONLY in the EXCEPT clause to exclude just the parent, or arrange for schema "public" to exclude this table as well. -- fail: the child is also explicitly included by the same statement CREATE PUBLICATION testpub_inh FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_inh_parent), @@ -756,12 +756,70 @@ Except tables: DROP PUBLICATION testpub_inh; DROP TABLE testpub_inh_child, pub_test.testpub_inh_sibling, pub_test.testpub_inh_parent; +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; +-- fail: non-existing table in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- fail: EXCEPT table belongs to a different schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 1: ...xcept ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.tes... + ^ +-- fail: TABLE keyword is required for the first entry in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +ERROR: syntax error at or near "testpub_nopk" +LINE 1: ...lter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_no... + ^ +-- fail: exact same table given as both explicitly published and excluded +-- in a single ALTER ... ADD +ALTER PUBLICATION testpub_alter_except + ADD TABLE pub_test.testpub_tbl_s1, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot be both published and excluded +-- fail: add explicit partition and EXCEPT ancestor, given in a +-- single ALTER ... ADD statement +ALTER PUBLICATION testpub_alter_except + ADD TABLE pub_test.testpub_part_s, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ERROR: partition "pub_test.testpub_part_s" cannot be both published and excluded +DETAIL: Partition root "pub_test.testpub_parted_s" is named in the publication's EXCEPT clause for schema "pub_test". +-- fail: partition already explicitly published, then its root is EXCEPT-ed +-- via a later, separate ALTER ... ADD +ALTER PUBLICATION testpub_alter_except ADD TABLE pub_test.testpub_part_s; +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ERROR: partition "pub_test.testpub_part_s" cannot be both published and excluded +DETAIL: Partition root "pub_test.testpub_parted_s" is named in the publication's EXCEPT clause for schema "pub_test". +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_part_s; +-- fail: root already explicitly published, then its partition is rejected +-- from EXCEPT via a later, separate ALTER ... ADD (partitions can never +-- appear in EXCEPT, independent of the root's state) +ALTER PUBLICATION testpub_alter_except ADD TABLE pub_test.testpub_parted_s; +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); +ERROR: cannot specify relation "pub_test.testpub_part_s" in the publication EXCEPT clause +DETAIL: This operation is not supported for individual partitions. +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_parted_s; +-- ADD: qualified and unqualified names; unqualified is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + "pub_test.testpub_tbl_s2" + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP TABLE pub_test.testpub_parted_s CASCADE; DROP TABLE testpub_nopk, testpub_tbl_s1; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi, testpub_alter_except; --------------------------------------------- -- Tests for publications with SEQUENCES --------------------------------------------- diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index f77dba51349..005d40c5c82 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -386,12 +386,55 @@ DROP PUBLICATION testpub_inh; DROP TABLE testpub_inh_child, pub_test.testpub_inh_sibling, pub_test.testpub_inh_parent; +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; + +-- fail: non-existing table in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- fail: EXCEPT table belongs to a different schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- fail: TABLE keyword is required for the first entry in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + +-- fail: exact same table given as both explicitly published and excluded +-- in a single ALTER ... ADD +ALTER PUBLICATION testpub_alter_except + ADD TABLE pub_test.testpub_tbl_s1, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: add explicit partition and EXCEPT ancestor, given in a +-- single ALTER ... ADD statement +ALTER PUBLICATION testpub_alter_except + ADD TABLE pub_test.testpub_part_s, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); + +-- fail: partition already explicitly published, then its root is EXCEPT-ed +-- via a later, separate ALTER ... ADD +ALTER PUBLICATION testpub_alter_except ADD TABLE pub_test.testpub_part_s; +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_part_s; + +-- fail: root already explicitly published, then its partition is rejected +-- from EXCEPT via a later, separate ALTER ... ADD (partitions can never +-- appear in EXCEPT, independent of the root's state) +ALTER PUBLICATION testpub_alter_except ADD TABLE pub_test.testpub_parted_s; +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_parted_s; + +-- ADD: qualified and unqualified names; unqualified is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); +\dRp+ testpub_alter_except + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP TABLE pub_test.testpub_parted_s CASCADE; DROP TABLE testpub_nopk, testpub_tbl_s1; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi, testpub_alter_except; --------------------------------------------- -- Tests for publications with SEQUENCES diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 7e11061a594..ed931d0d970 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -347,6 +347,38 @@ is($result, qq(5), $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); +# ============================================ +# ALTER PUBLICATION EXCEPT for TABLES IN SCHEMA +# ============================================ + +# Truncate subscriber tables to remove data accumulated from previous tests. +$node_subscriber->safe_psql('postgres', + 'TRUNCATE sch1.tab_published, sch1.tab_excluded, sch1.parent, sch1.child'); + +# ADD: add a schema with an excepted table; verify the except entry takes effect. +$node_publisher->safe_psql('postgres', "CREATE PUBLICATION sch_pub"); +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub ADD TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_excluded)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(6), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: included table synced'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + # Cleanup schema tables before the multi-publication section. $node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); $node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); -- 2.55.0
^ permalink raw reply [nested|flat] 196+ messages in thread

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-14 14:22  vignesh C <vignesh21@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: vignesh C @ 2026-08-14 14:22 UTC (permalink / raw)
  To: shveta malik <shveta.malik@gmail.com>; +Cc: Nisha Moond <nisha.moond412@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; Peter Smith <smithpb2250@gmail.com>

On Wed, 12 Aug 2026 at 14:40, shveta malik <shveta.malik@gmail.com> wrote:
>
> On Tue, Aug 11, 2026 at 2:28 PM vignesh C <vignesh21@gmail.com> wrote:
> >
> >
> > Apart from these, the rest of the comments are also fixed in the v26
> > version attached.
>
> Thanks Vignesh. A few comments on v26-0001:
>
> 1)
>
> publication_add_relation() accepts 'if_not_exists' i.e. add the new
> entry 'if already not present' else skip it (no error if it is a
> duplicate addition). Most flows pass it as 'true'. The current code
> skips raising error if if_not_exists=true and entry exists. It made
> sense earlier, but in our implementation, I feel it should still raise
> an error if entries are cross wired (i.e., if an exclusion is present
> and we are trying to add it as an inclusion, or vice versa). The
> 'if_not_exists' based 'skip logic' should only be exercised if the
> nature of existing entity is of same kind as user is trying to add.
>
> Let me know if you have different understanding.

That is my understanding as well.
I tested a few scenarios to determine whether there was an actual
issue and found that the following cases were succeeding when they
should have thrown an error:
Scenario 1:
CREATE PUBLICATION p FOR TABLES IN SCHEMA s1 EXCEPT (TABLE s1.t);
ALTER PUBLICATION p ADD TABLE s1.t;

Scenario 2:
CREATE PUBLICATION p2 FOR TABLE s1.t;
ALTER PUBLICATION p2 ADD TABLES IN SCHEMA s1 EXCEPT (TABLE s1.t);

Both scenarios should have resulted in an error, but they currently
succeed. I have addressed these cases as well.

> 2)
> ProcessSchemaExceptTables:
>
> + * Also rejects a schema being mentioned more than once with an EXCEPT
> + * clause, even if the EXCEPT clauses are identical — much like
> + * OpenTableList() rejects "FOR TABLE t1(a), t1(a)" despite the column
> + * lists matching. A schema can still be mentioned multiple times, just
> + * not more than once with EXCEPT.
> + *
> + * Qualify unqualified EXCEPT table names with the given schema (rejecting
> + * any explicitly qualified with a different schema), and append them to
> + * *except_pubtables.
>
> We changed the order of comments above, but missed to change these:
>
> 'Also rejects a schema ' -> Reject a schema
> Qualify unqualified -> 'Also qualify unqualified EXCEPT table..'

Modified

> 3)
> CheckExceptNotInTableList:
> + * Both checks are performed here, on the lists supplied by the statement,
> + * because at this point the catalog cannot answer either question. The
> + * corresponding checks in publication_add_relation() and
> + * check_publication_add_relation() rely on pg_publication_rel entries and
> + * ancestor lookups, neither of which is sufficient in the cases below:
>
> Since we have changed comment prior to it, this too needs to be
> changed as 'Both checks' does not make much sense.
>
> Suggestion:
> Similar checks are present in publication_add_relation() and
> check_publication_add_relation(), but they rely on pg_publication_rel
> entries and ancestor lookups. Here, the checks are performed on the
> object lists collected during the statement, as the catalog state is
> not sufficient in the cases below:

Modified

The v27 version patch attached at [1] has the changes for the same.
[1] - https://www.postgresql.org/message-id/CALDaNm0802S%3D557rKtYcV%2BoEbXFw23n%3DXtPHMCbKGSgOgOgk2A%40ma...

Regards,
Vignesh






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-14 14:29  vignesh C <vignesh21@gmail.com>
  parent: vignesh C <vignesh21@gmail.com>
  0 siblings, 0 replies; 196+ messages in thread

From: vignesh C @ 2026-08-14 14:29 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Peter Smith <smithpb2250@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Fri, 7 Aug 2026 at 19:51, vignesh C <vignesh21@gmail.com> wrote:
>
> On Tue, 4 Aug 2026 at 14:11, Nisha Moond <nisha.moond412@gmail.com> wrote:
> >
> > Attached is the v25 patch set addressing all of the above, as well as
> > Shlok's and Peter's comments in [1] and [2].
>
> There is another issue with pg_dump when dumping a publication created
> using FOR TABLES IN SCHEMA ... EXCEPT.
> CREATE SCHEMA s1;
> CREATE SCHEMA s2;
> CREATE TABLE s1.parent (a int);
> CREATE TABLE s2.child (b int) INHERITS (s1.parent);
>
> -- Create a publication excluding the parent table
> CREATE PUBLICATION p FOR TABLES IN SCHEMA s1 EXCEPT (TABLE s1.parent);
>
> The publication correctly excludes both the parent and its inherited child:
> postgres=# \dRp+
> Publication p
> Owner      | All tables | All sequences | Inserts | Updates | Deletes
> | Truncates | Generated columns | Via root | Description
> ------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+-------------
> test        | f          | f             | t       | t       | t
> | t         | none              | f        |
> Tables from schemas:
>   "s1"
> Except tables:
>   "s1.parent"
>   "s2.child"

This implementation has now been modified to include only s1.parent
and not s2.child, since the s2 schema was not specified in the
publication.

> However, pg_dump generates the following definition:
> CREATE PUBLICATION p WITH (publish = 'insert, update, delete, truncate');
> ALTER PUBLICATION p OWNER TO test;
> ALTER PUBLICATION p ADD TABLES IN SCHEMA s1 EXCEPT (TABLE ONLY parent);

Since s2.child is not included in the publication relation catalog,
the dump retains the original publication definition. Consequently,
during restore, the original publication definition is recreated.

This issue is addressed in the v27 version patch attached at [1].
[1] - https://www.postgresql.org/message-id/CALDaNm0802S%3D557rKtYcV%2BoEbXFw23n%3DXtPHMCbKGSgOgOgk2A%40ma...

Regards,
Vignesh






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-17 04:02  shveta malik <shveta.malik@gmail.com>
  parent: vignesh C <vignesh21@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: shveta malik @ 2026-08-17 04:02 UTC (permalink / raw)
  To: vignesh C <vignesh21@gmail.com>; +Cc: Nisha Moond <nisha.moond412@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; Peter Smith <smithpb2250@gmail.com>; shveta malik <shveta.malik@gmail.com>

On Fri, Aug 14, 2026 at 7:52 PM vignesh C <vignesh21@gmail.com> wrote:
>
> On Wed, 12 Aug 2026 at 14:40, shveta malik <shveta.malik@gmail.com> wrote:
> >
> > On Tue, Aug 11, 2026 at 2:28 PM vignesh C <vignesh21@gmail.com> wrote:
> > >
> > >
> > > Apart from these, the rest of the comments are also fixed in the v26
> > > version attached.
> >
> > Thanks Vignesh. A few comments on v26-0001:
> >
> > 1)
> >
> > publication_add_relation() accepts 'if_not_exists' i.e. add the new
> > entry 'if already not present' else skip it (no error if it is a
> > duplicate addition). Most flows pass it as 'true'. The current code
> > skips raising error if if_not_exists=true and entry exists. It made
> > sense earlier, but in our implementation, I feel it should still raise
> > an error if entries are cross wired (i.e., if an exclusion is present
> > and we are trying to add it as an inclusion, or vice versa). The
> > 'if_not_exists' based 'skip logic' should only be exercised if the
> > nature of existing entity is of same kind as user is trying to add.
> >
> > Let me know if you have different understanding.
>
> That is my understanding as well.
> I tested a few scenarios to determine whether there was an actual
> issue and found that the following cases were succeeding when they
> should have thrown an error:
> Scenario 1:
> CREATE PUBLICATION p FOR TABLES IN SCHEMA s1 EXCEPT (TABLE s1.t);
> ALTER PUBLICATION p ADD TABLE s1.t;
>
> Scenario 2:
> CREATE PUBLICATION p2 FOR TABLE s1.t;
> ALTER PUBLICATION p2 ADD TABLES IN SCHEMA s1 EXCEPT (TABLE s1.t);
>
> Both scenarios should have resulted in an error, but they currently
> succeed. I have addressed these cases as well.
>

These are very simple scenarios which I tested multiple times. These
scenarios produced an error in the previous version; see:

postgres=# create publication pub1 for tables in schema s1 except (table s1.t1);
CREATE PUBLICATION
postgres=# alter publication pub1 add table s1.t1;
ERROR:  cannot add table "s1.t1" to publication "pub1"
DETAIL:  The table is named in the publication's EXCEPT clause for schema "s1".
HINT:  Change the EXCEPT clause using ALTER PUBLICATION ... SET TABLES
IN SCHEMA ... EXCEPT.

postgres=# CREATE PUBLICATION pub2 FOR TABLE s1.t1;
CREATE PUBLICATION
postgres=# ALTER PUBLICATION pub2 ADD TABLES IN SCHEMA s1 EXCEPT (TABLE s1.t1);
ERROR:  table "s1.t1" cannot be both published and excluded

By any chance did you comment out 'CheckExceptNotInTableList' while
testing these i.e. did you intend to test these through
publication_add_relation() alone?

thanks
Shveta






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-17 07:06  vignesh C <vignesh21@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  0 siblings, 0 replies; 196+ messages in thread

From: vignesh C @ 2026-08-17 07:06 UTC (permalink / raw)
  To: shveta malik <shveta.malik@gmail.com>; +Cc: Nisha Moond <nisha.moond412@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; Peter Smith <smithpb2250@gmail.com>

On Mon, 17 Aug 2026 at 09:32, shveta malik <shveta.malik@gmail.com> wrote:
>
> These are very simple scenarios which I tested multiple times. These
> scenarios produced an error in the previous version; see:

Sorry for mentioning the wrong test. There is only one issue, here are
the steps for the same with v25 version:
create schema pub_test;
create table pub_test.testpub_tbl_s1(c1 int);
CREATE PUBLICATION testpub_xwire FOR TABLES IN SCHEMA pub_test EXCEPT
(TABLE pub_test.testpub_tbl_s1);
-- publication ends up empty
ALTER PUBLICATION testpub_xwire SET TABLE pub_test.testpub_tbl_s1;
postgres=# \dRp+ testpub_xwire
                                                     Publication testpub_xwire
     Owner      | All tables | All sequences | Inserts | Updates |
Deletes | Truncates | Generated columns | Via root | Description
----------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+-------------
 vigneshwaran_c | f          | f             | t       | t       | t
 | t         | none              | f        |
(1 row)

postgres=# select * from pg_publication_rel ;
 oid | prpubid | prrelid | prexcept | prqual | prattrs
-----+---------+---------+----------+--------+---------
(0 rows)

This has been fixed in the v27 version:
-- Includes the publication table pub_test.testpub_tbl_s1 correctly:
postgres=# \dRp+ testpub_xwire
                                                     Publication testpub_xwire
     Owner      | All tables | All sequences | Inserts | Updates |
Deletes | Truncates | Generated columns | Via root | Description
----------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+-------------
 test | f          | f             | t       | t       | t       | t
    | none              | f        |
Tables:
    "pub_test.testpub_tbl_s1"

postgres=# select * from pg_publication_rel ;
  oid  | prpubid | prrelid | prexcept | prqual | prattrs
-------+---------+---------+----------+--------+---------
 16391 |   16388 |   16385 | f        |        |
(1 row)

Regards,
Vignesh






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-18 03:58  Peter Smith <smithpb2250@gmail.com>
  parent: vignesh C <vignesh21@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: Peter Smith @ 2026-08-18 03:58 UTC (permalink / raw)
  To: vignesh C <vignesh21@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Nisha Moond <nisha.moond412@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

Some review comments for patch v27-0001.

(Have not finished looking at the other patches yet)

======
Commit Message

1.
What are the implemented rules for parent/child (inherited) tables?
Shouldn't the commit message have something to say about those?
Perhaps it is covered by "A table cannot be both explicitly published
and excluded in the same statement", but even so I still think the
rule for inherited tables should be mentioned for clarity.

======
src/backend/catalog/pg_publication.c

publication_add_relation:

2.
- if (if_not_exists)
+ /*
+ * if_not_exists asks us to skip an entry that is already present.  An
+ * existing entry of the opposite kind is not the entry the caller
+ * asked for, though: skipping it would silently leave the relation
+ * excluded when the caller wanted it published, or published when the
+ * caller wanted it excluded.  So only skip when the existing entry is
+ * of the same kind, and report the conflict otherwise.
+ */
+ if (if_not_exists && is_except == pri->except)
  return InvalidObjectAddress;

The parameter `if_not_exists` seems like a poor name. There is no verb
to say *what* to do if not exists, so it only makes sense if read in
context of the function name (e.g. "add relation" "if not exists").

You really should not need that first comment sentence to explain the
meaning of the parameter because if it had a good name it would be
already obvious. IMO rename this parameter to something like
'skip_if_already_exists'

~~~

3.
+ if (is_except)
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("cannot add table \"%s\" to publication \"%s\"",
+ RelationGetQualifiedRelationName(targetrel),
+ pub->name),
+ errdetail("The table is named in the publication's EXCEPT clause for
schema \"%s\".",
+   get_namespace_name(RelationGetNamespace(targetrel))),
+ errhint("Change the EXCEPT clause using ALTER PUBLICATION ... SET
TABLES IN SCHEMA ... EXCEPT.")));
+ else if (pri->except)
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("cannot exclude table \"%s\" from publication \"%s\"",
+ RelationGetQualifiedRelationName(targetrel),
+ pub->name),
+ errdetail("The table is a member of the publication."),
+ errhint("Remove the table from the publication using ALTER
PUBLICATION ... DROP TABLE.")));


I feel these messages should better convey that the problem is really
due to an "inconsistent" specification. To do this, you can use the
same common errmsg that is already used elsewhere in this patch.

SUGGESTION
errmsg("table \"%s\" cannot be both published and excluded",
errdetail "The table is already in the publication EXCEPT clause for
schema \"%s\"."

and

SUGGESTION
errmsg("table \"%s\" cannot be both published and excluded",
errdetail "The table is already in the publication"
(I am not sure; should this 2nd errdetail mention it is in the
publication via a FOR TABLE clause?)

~~~

GetPublicationRelationsOfAnyKind:

4.
+/*
+ * Gets list of relation oids associated with a publication, covering both
+ * explicitly included relations and relations named in an EXCEPT clause.
+ *
+ * This is used by ALTER PUBLICATION ... SET to replaces a publication's entire
+ * relation list.
+ */
+List *
+GetPublicationRelationsOfAnyKind(Oid pubid, PublicationPartOpt pub_partopt)
+{
+ List   *result;
+
+ result = get_publication_relations(pubid, pub_partopt, false);
+
+ return list_concat_unique_oid(result,
+  get_publication_relations(pubid, pub_partopt,
+ true));
+}
+

4a.
/replaces/replace/

~

4b
Calling this same get_publication_relations multiple times seemed
overkill. Won't it be better to change the signature of
get_publication_relations like:

static List *
get_publication_relations(Oid pubid, PublicationPartOpt pub_partopt,
  bool want_included,
  bool want_excluded);

then
a) it would be more efficient; e.g. 1 scan instead of 2
b) then GetPublicationRelationsOfAnyKind not needed; just call
get_publication_relations(..., true, true);

======
src/backend/commands/publicationcmds.c

CheckExceptNotInTableList:

5.
+ /*
+ * An EXCEPT clause also applies to inheritance children of a parent
+ * named without ONLY. Children in other schemas are not added to
+ * except_rels, but are still excluded by the EXCEPT clause. Explicitly
+ * publishing such a child therefore conflicts with the EXCEPT clause.
+ */
+ if (list_member_oid(cross_schema_children, explicitrelid))
+ ereport(ERROR,
+ errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("table \"%s\" cannot be both published and excluded",
+   quote_qualified_identifier(get_namespace_name(get_rel_namespace(explicitrelid)),
+  get_rel_name(explicitrelid))),
+ errdetail("It inherits from a table named in an EXCEPT clause of
this statement."),
+ errhint("Use ONLY in the EXCEPT clause to exclude just the parent,
or do not publish this table explicitly."));

5a.
Here is a reworded comment. See what you think.
- e.g. I didn't like "not added to except_rels" because this function
is not adding that anyhow

SUGGESTION
An EXCEPT clause for a parent table named without ONLY also excludes
its inheritance children. Therefore, explicitly publishing such a
child conflicts with the EXCEPT clause. Note that children in other
schemas are not present in `except_rels`.

~~~

5b.
IMO the erdetail should look more like the other one.

So something like:

errdetail("It inherits from parent table \"%s\" named in the
publication's EXCEPT clause for schema \"%s\".",

Alternatively, if you word it like below, then you can remove the errhint too.
errdetail("It inherits from parent table \"%s\" named without ONLY in
the publication's EXCEPT clause for schema \"%s\".",

~~~

CheckExceptChildNotInSchemaList:

6.
+/*
+ * Check that an EXCEPT clause does not conflict with a TABLES IN SCHEMA
+ * clause in the same statement.
+ *
+ * cross_schema_children contains inheritance children excluded through a
+ * parent in another schema. If such a child is also included through a
+ * TABLES IN SCHEMA clause in the same statement, report the conflict.
+ *
+ * If the child's schema also has an EXCEPT clause specified through TABLES
+ * IN SCHEMA, there is no conflict, since both clauses exclude the child.
+ *
+ * Conflicts with explicitly listed tables are handled by
+ * CheckExceptNotInTableList().
+ */

An example would help to clarify this comment

Something like this?
e.g.
When:   s1.parent has s2.child
Error:  FOR TABLES IN SCHEMA s1 EXCEPT (TABLE parent), s2;
OK:     FOR TABLES IN SCHEMA s1 EXCEPT (TABLE parent), s2 EXCEPT (TABLE child);

~~~

7.
+ if (excluded)
+ continue;
+
+ ereport(ERROR,
+ errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("table \"%s\" cannot be both published and excluded",
+   quote_qualified_identifier(get_namespace_name(childnsp),
+  get_rel_name(childrelid))),
+ errdetail("It inherits from a table named in the EXCEPT clause of
another schema, and its own schema \"%s\" is published in full.",
+  get_namespace_name(childnsp)),
+ errhint("Use ONLY in the EXCEPT clause to exclude just the parent,
or name this table in the EXCEPT clause of schema \"%s\".",
+ get_namespace_name(childnsp)));

7a.
This is coded strangely. Can't it simply say

if (!excluded)
  ereport(ERROR, ...)

~~~

7b.
This errdetail can be reworded similar to the one in an early review
comment #5b in this post.

~~~

CreatePublication:

8.
+ if (except_pubtables != NIL)
+ {
+ List   *except_rels;
+ List   *cross_schema_children = NIL;
+
+ except_rels = OpenTableList(except_pubtables,
+ &cross_schema_children);
+
+ /*
+ * Validate that a table is not both explicitly included and
+ * excluded by the schema's EXCEPT clause.
+ */
+ CheckExceptNotInTableList(except_rels, cross_schema_children,
+  explicitrelids);
+
+ /*
+ * Validate that an inheritance child is not both excluded by
+ * an EXCEPT clause and included by its schema.
+ */
+ CheckExceptChildNotInSchemaList(cross_schema_children,
+ schemaidlist, except_rels);
+
+ PublicationAddTables(puboid, except_rels, false, NULL);
+ CloseTableList(except_rels);
+ }

8a.
It seems unusual that the functions CheckExceptNotInTableList() and
CheckExceptChildNotInSchemaList() have the same parameters but are in
different order. It might be better if they are in the same order.

~

8b.
In fact, both of these static functions not only have the same
parameters, but they are both only called from one place, which is
here. So is there a reason why these aren't combined in a single
function?

~~~

AlterPublicationTables:

9.
+ /*
+ * SET replaces the publication's whole relation list, so every
+ * existing entry has to be reconciled against the new one -- an
+ * EXCEPT entry included.  If the same relation is now requested
+ * with the opposite kind, the old entry is dropped below and the
+ * new one added, rather than the old one being silently kept.
+ */

I'm not sure you need to mention "If the same relation is now..."
here. That part seems more appropriate to say where you actually do
it, rather than saying that it's something that's going to happen
later "below".

~~~

10.
+ * existing relations in the publication. An entry matches
+ * only if it is of the same kind, that is, both are ordinary
+ * members or both are EXCEPT entries. Additionally, if the

"Ordinary members" versus "EXCEPT entries"

Simpler just to say:

SUGGESTION
An entry matches only if it is of the same kind (e.g. the EXCEPT flags
must be the same).

~~~

11.
  if (newrelid == oldrelid)
  {
- if (equal(oldrelwhereclause, newpubrel->whereClause) &&
+ if (newpubrel->except == oldexcept &&
+ equal(oldrelwhereclause, newpubrel->whereClause) &&
  bms_equal(oldcolumns, newcolumns))
  {

Should all this be combined to a single "if"?

~~~

OpenTableList:

12.
 /*
  * Open relations specified by a PublicationTable list.
  * The returned tables are locked in ShareUpdateExclusiveLock mode in order to
  * add them to a publication.
  */
 static List *
-OpenTableList(List *tables)
+OpenTableList(List *tables, List **cross_schema_children)

The function comment describes the meaning of `cross_schema_children`.

~~~

13.
Since there are lots of changes here, you can also change the
foreach() loop to foreach_oid() to make things a little bit neater.

~~~

14.
+ /*
+ * An EXCEPT clause also excludes inheritance children in other
+ * schemas. Keep track of such children separately so the
+ * caller can detect if the same statement also includes them
+ * through another table or schema clause.
+ */

for "another table or schema clause."

SUGGESTION
another FOR TABLE clause or FOR TABLES IN SCHEMA clause.

======
src/include/nodes/parsenodes.h

15.
  List   *columns; /* List of columns in a publication table */
  bool except; /* True if listed in the EXCEPT clause */
+ bool except_in_schema; /* True if listed in the EXCEPT clause of a
+ * TABLES IN SCHEMA clause, whose scope is
+ * limited to that schema */
 } PublicationTable;

Now, that ("True if listed in the EXCEPT clause") is ambiguous. e.g.
Is that first flag also true for SCHEMA EXCEPT or not? It would be
better to give these attributes explicit names so there is no doubt.

e.g.
bool all_tables_except;
bool tables_in_schema_except;

(or something else if there are better names)

======
src/test/regress/sql/publication.sql

16.
+-- ALTER PUBLICATION ... SET replaces the publication's whole relation list, so
+-- an existing entry for a relation now requested with the opposite
kind must be
+-- dropped and re-added, not silently left in place.
+CREATE PUBLICATION testpub_except_alter1
+    FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1);
+-- the excluded table becomes an ordinary member: one non-EXCEPT entry, no
+-- EXCEPT entry, and no schema left in the publication
+ALTER PUBLICATION testpub_except_alter1 SET TABLE pub_test.testpub_tbl_s1;
+\dRp+ testpub_except_alter1
+DROP PUBLICATION testpub_except_alter1;

Maybe this can also do "\dRp+ testpub_except_alter1" for the "before"
case so you can more easily see the before/after.

~~~

17.
+-- Cross-schema inheritance children and EXCEPT. An EXCEPT clause also
+-- excludes inheritance children of a parent named without ONLY.
+CREATE TABLE pub_test.testpub_inh_parent (a int);
+CREATE TABLE pub_test.testpub_inh_sibling (b int) INHERITS
(pub_test.testpub_inh_parent);
+CREATE TABLE testpub_inh_child (b int) INHERITS (pub_test.testpub_inh_parent);
+CREATE PUBLICATION testpub_inh
+    FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_inh_parent);
+-- Two EXCEPT entries: the parent and the child in pub_test.
+\dRp+ testpub_inh
+DROP PUBLICATION testpub_inh;

The names were a bit confusing. Maybe just `child1` and `child2` would
be easier than testpub_inh_sibling and testpub_inh_child.

~~~

18.
+-- fail: the child testpub_inh_child is also included through TABLES IN SCHEM
+-- public

/SCHEM/SCHEMA/

~~~

19.
+-- ONLY resolves the conflict: only the parent is excluded, so the child can
+-- be published explicitly
+CREATE PUBLICATION testpub_inh
+    FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE ONLY
pub_test.testpub_inh_parent),
+        TABLE testpub_inh_child;
+\dRp+ testpub_inh
+DROP PUBLICATION testpub_inh;

Maybe there is a missing test combination where you use ONLY to
exclude the parent, and you include the entire public schema of the
testpub_inh_child.

======
Kind Regards,
Peter Smith.
Fujitsu Australia






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-18 04:54  vignesh C <vignesh21@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  2 siblings, 2 replies; 196+ messages in thread

From: vignesh C @ 2026-08-18 04:54 UTC (permalink / raw)
  To: shveta malik <shveta.malik@gmail.com>; +Cc: Nisha Moond <nisha.moond412@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Peter Smith <smithpb2250@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Wed, 12 Aug 2026 at 11:42, shveta malik <shveta.malik@gmail.com> wrote:
>
> If we implement what I suggested above, Case 2's implementation for
> partitions would be contrary to what we decided at [2] earlier for the
> scenario at [1]. However, after reconsidering all scenarios, I feel
> the new approach (suggested above) makes more sense and is also
> consistent with Case 3. Case 2 and Case 3 are logically the same and
> should have the same behaviour, IMO. Thoughts?

The v28 version of the attached patch handles the changes to throw an
error when a partition table is both included and excluded through an
EXCEPT clause, keeping the behavior consistent with inheritance
tables.

Regards,
Vignesh

Attachments: download all (4 files, .tar.gz)

v28-0002-Add-EXCEPT-support-to-ALTER-PUBLICATION-ADD-TABL.patch (application/octet-stream, 38.1K) download From 9bf2abf4bd377b0b8d8818dd8b7ab258f99c80ff Mon Sep 17 00:00:00 2001 From: Vignesh C <c_vigneshwaran@apple.com> Date: Tue, 18 Aug 2026 09:22:15 +0530 Subject: [PATCH v28 2/4] Add EXCEPT support to ALTER PUBLICATION ADD TABLES IN SCHEMA Extend the EXCEPT clause support to allow tables to be excluded when adding a schema to a publication via ALTER PUBLICATION ... ADD. Syntax: ALTER PUBLICATION pub ADD TABLES IN SCHEMA s EXCEPT (TABLE s.t1); Since pg_dump uses ALTER PUBLICATION ... ADD, support for it is included in this patch. --- src/backend/catalog/pg_publication.c | 19 +- src/backend/commands/publicationcmds.c | 332 ++++++++++++++++++---- src/bin/pg_dump/pg_dump.c | 30 +- src/bin/pg_dump/t/002_pg_dump.pl | 24 ++ src/bin/psql/tab-complete.in.c | 17 ++ src/test/regress/expected/publication.out | 98 ++++++- src/test/regress/sql/publication.sql | 73 ++++- src/test/subscription/t/037_except.pl | 32 +++ 8 files changed, 562 insertions(+), 63 deletions(-) diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index 81e4166cfee..12a360347d2 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -749,15 +749,18 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, * here, as CreatePublication() function invalidates all relations as part * of defining a FOR ALL TABLES publication. * - * For ALTER PUBLICATION, invalidation is needed only when adding an - * EXCEPT table to a publication already marked as ALL TABLES. For - * publications that were originally empty or defined as ALL SEQUENCES and - * are being converted to ALL TABLES, invalidation is skipped here, as - * AlterPublicationAllFlags() function invalidates all relations while - * marking the publication as ALL TABLES publication. + * For ALTER PUBLICATION, invalidation is needed when adding an EXCEPT + * table to either a FOR ALL TABLES publication (pub->alltables is true) + * or a FOR TABLES IN SCHEMA publication (is_schema_publication is true). + * The exception: when a publication is being converted to FOR ALL TABLES + * (pub->alltables is still false at this point), + * AlterPublicationAllFlags() will perform a full invalidation, so we skip + * it here. */ - inval_except_table = (alter_stmt != NULL) && pub->alltables && - (alter_stmt->for_all_tables && pri->except); + inval_except_table = (alter_stmt != NULL) && pri->except && + (pub->alltables + ? alter_stmt->for_all_tables + : is_schema_publication(pubid)); if (!pri->except || inval_except_table) { diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index a46c072801b..246649da0ea 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -70,13 +70,26 @@ static void PublicationAddTables(Oid pubid, List *rels, bool if_not_exists, static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok); static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); +static void CheckSchemaListNotExcluded(Oid pubid, List *schemaidlist); +static void PublicationAddExceptTables(Oid pubid, List *except_pubtables, + List *explicitrelids, + List *schemaidlist, + AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); +static void AlterPublicationSchemas(AlterPublicationStmt *stmt, + HeapTuple tup, List *schemaidlist, + List *except_pubtables); +static void AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, + List *except_pubtables, + List *schemaidlist); static char defGetGeneratedColsOption(DefElem *def); static void CheckExceptNotInTableList(List *except_rels, List *cross_schema_children, List *explicitrelids); -static void CheckExceptChildNotInSchemaList(List *cross_schema_children, - List *schemaidlist, +static void CheckExceptChildNotInSchemaList(Oid pubid, + List *cross_schema_children, + List *pubschemas, List *except_rels); static void CheckExceptPartitionNotInSchemaList(List *except_rels, List *schemaidlist); @@ -944,31 +957,36 @@ CheckExceptNotInTableList(List *except_rels, List *cross_schema_children, } /* - * Check that an EXCEPT clause does not conflict with a TABLES IN SCHEMA - * clause in the same statement. + * Check that an EXCEPT clause does not conflict with a schema published by the + * publication. * * cross_schema_children contains inheritance children excluded through a * parent in another schema. If such a child is also included through a - * TABLES IN SCHEMA clause in the same statement, report the conflict. + * published schema, report the conflict. pubschemas must therefore cover both + * the schemas that this statement publishes and those the publication already + * publishes; ALTER PUBLICATION ... ADD names only the former. * - * If the child's schema also has an EXCEPT clause specified through TABLES - * IN SCHEMA, there is no conflict, since both clauses exclude the child. + * If the child is excluded anyway, there is no conflict, since both sides + * agree. That is so when an EXCEPT clause of this statement names it, and also + * when the publication already holds an EXCEPT entry for it. * * Conflicts with explicitly listed tables are handled by * CheckExceptNotInTableList(). */ static void -CheckExceptChildNotInSchemaList(List *cross_schema_children, List *schemaidlist, - List *except_rels) +CheckExceptChildNotInSchemaList(Oid pubid, List *cross_schema_children, + List *pubschemas, List *except_rels) { foreach_oid(childrelid, cross_schema_children) { Oid childnsp = get_rel_namespace(childrelid); bool excluded = false; + bool is_except; - if (!list_member_oid(schemaidlist, childnsp)) + if (!list_member_oid(pubschemas, childnsp)) continue; + /* Does an EXCEPT clause of this statement exclude it as well? */ foreach_ptr(PublicationRelInfo, pri, except_rels) { if (RelationGetRelid(pri->relation) == childrelid) @@ -978,6 +996,12 @@ CheckExceptChildNotInSchemaList(List *cross_schema_children, List *schemaidlist, } } + /* Or does the publication already exclude it? */ + if (!excluded && + CheckPublicationRelEntry(pubid, childrelid, &is_except) && + is_except) + excluded = true; + if (excluded) continue; @@ -988,11 +1012,172 @@ CheckExceptChildNotInSchemaList(List *cross_schema_children, List *schemaidlist, get_rel_name(childrelid))), errdetail("It inherits from a table named in the EXCEPT clause of another schema, and its own schema \"%s\" is published in full.", get_namespace_name(childnsp)), - errhint("Use ONLY in the EXCEPT clause to exclude just the parent, or name this table in the EXCEPT clause of schema \"%s\".", + errhint("Use ONLY in the EXCEPT clause to exclude just the parent, or arrange for schema \"%s\" to exclude this table as well.", get_namespace_name(childnsp))); } } +/* + * Check that the schemas being added to a publication do not contain a table + * that the publication already excludes through a partition root or an + * inheritance parent in a different schema. + * + * This is the mirror of the checks made when the EXCEPT clause itself is + * processed. There, the statement supplies the EXCEPT entries and the schemas + * are looked up; here the statement supplies the schemas and the EXCEPT entries + * are looked up. Either way the publication must not end up both publishing a + * table and excluding it, and both orders have to be rejected or the state one + * statement refuses could be reached with two. + * + * An EXCEPT entry reaches only the descendants that live in its own schema, so + * a descendant in the schema being added is not covered by it; publishing that + * schema would leave the table published while the EXCEPT clause means to + * exclude it. A descendant in the excluded table's own schema is covered, and + * is no conflict. + * + * Only partitioned EXCEPT entries can be checked; see below for why an entry + * naming a plain table has to be skipped. + */ +static void +CheckSchemaListNotExcluded(Oid pubid, List *schemaidlist) +{ + List *exceptrelids; + + if (schemaidlist == NIL) + return; + + /* + * Only FOR ALL TABLES and schema publications can hold EXCEPT entries, + * and schemas cannot be added to the former. + */ + if (!is_schema_publication(pubid)) + return; + + exceptrelids = GetExcludedPublicationTables(pubid, PUBLICATION_PART_ROOT); + + foreach_oid(exceptrelid, exceptrelids) + { + Oid exceptnsp = get_rel_namespace(exceptrelid); + List *children; + + /* + * Only partitioned tables can be checked here. Whether an EXCEPT + * entry was written with ONLY is not recorded anywhere: for a plain + * table, "EXCEPT (TABLE ONLY t)" and "EXCEPT (TABLE t)" leave exactly + * the same rows behind whenever t's children all live in other + * schemas, since those are never given entries of their own. + * Rejecting the schema would then also reject the ONLY spelling, + * which excludes the parent alone and has no quarrel with publishing + * the children. + * + * ONLY has no effect for partitioned tables, so an entry naming one + * always covers the whole tree and the catalog is unambiguous. + */ + if (get_rel_relkind(exceptrelid) != RELKIND_PARTITIONED_TABLE) + continue; + + /* + * find_all_inheritors() returns exceptrelid itself first, which the + * schema comparison below skips. No lock is taken, as in + * GetPubPartitionOptionRelations(). + */ + children = find_all_inheritors(exceptrelid, NoLock, NULL); + + foreach_oid(childrelid, children) + { + Oid childnsp = get_rel_namespace(childrelid); + + if (childnsp == exceptnsp || + !list_member_oid(schemaidlist, childnsp)) + continue; + + /* + * An entry of its own means the publication excludes the child + * too, so both sides agree. + */ + if (list_member_oid(exceptrelids, childrelid)) + continue; + + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("cannot add schema \"%s\" to publication \"%s\"", + get_namespace_name(childnsp), + get_publication_name(pubid, false)), + errdetail("It contains table \"%s\", which descends from \"%s\", already named in the publication's EXCEPT clause for schema \"%s\".", + quote_qualified_identifier(get_namespace_name(childnsp), + get_rel_name(childrelid)), + quote_qualified_identifier(get_namespace_name(exceptnsp), + get_rel_name(exceptrelid)), + get_namespace_name(exceptnsp)), + errhint("The table would be both published and excluded.")); + } + + list_free(children); + } + + list_free(exceptrelids); +} + +/* + * Add the EXCEPT tables of a statement's TABLES IN SCHEMA clauses to a + * publication, after checking that the statement does not contradict itself. + * + * explicitrelids is the set of relations the statement publishes by name, and + * schemaidlist the schemas it publishes in full; both are needed to detect a + * table that would be published and excluded at the same time. + * + * if_not_exists is false: an EXCEPT entry that is already present, or that + * collides with an ordinary member, is a conflict worth reporting rather than + * something to skip silently. + */ +static void +PublicationAddExceptTables(Oid pubid, List *except_pubtables, + List *explicitrelids, List *schemaidlist, + AlterPublicationStmt *stmt) +{ + List *except_rels; + List *cross_schema_children = NIL; + List *pubschemas; + + if (except_pubtables == NIL) + return; + + except_rels = OpenTableList(except_pubtables, &cross_schema_children); + + /* + * A table is published by this publication if the statement publishes its + * schema, or if the publication already published it. ALTER PUBLICATION + * ... ADD names only the schemas being added, so the catalog has to be + * consulted as well; otherwise a child in a schema that an earlier + * command added would not be recognised as a conflict. + */ + pubschemas = list_concat_unique_oid(list_copy(schemaidlist), + GetPublicationSchemas(pubid)); + + /* + * Validate that a table is not both explicitly included and excluded by + * the schema's EXCEPT clause. + */ + CheckExceptNotInTableList(except_rels, cross_schema_children, + explicitrelids); + + /* + * Validate that an inheritance child is not both excluded by an EXCEPT + * clause and included by its schema. + */ + CheckExceptChildNotInSchemaList(pubid, cross_schema_children, pubschemas, + except_rels); + + /* + * Validate that a partition is not both excluded through its root by an + * EXCEPT clause and included by its own schema. + */ + CheckExceptPartitionNotInSchemaList(except_rels, pubschemas); + + PublicationAddTables(pubid, except_rels, false, stmt); + CloseTableList(except_rels); +} + /* * Check that an EXCEPT clause naming a partitioned table does not conflict with * a schema included by the same statement. @@ -1291,38 +1476,8 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) */ LockSchemaList(schemaidlist); PublicationAddSchemas(puboid, schemaidlist, true, NULL); - - if (except_pubtables != NIL) - { - List *except_rels; - List *cross_schema_children = NIL; - - except_rels = OpenTableList(except_pubtables, - &cross_schema_children); - - /* - * Validate that a table is not both explicitly included and - * excluded by the schema's EXCEPT clause. - */ - CheckExceptNotInTableList(except_rels, cross_schema_children, - explicitrelids); - - /* - * Validate that an inheritance child is not both excluded by - * an EXCEPT clause and included by its schema. - */ - CheckExceptChildNotInSchemaList(cross_schema_children, - schemaidlist, except_rels); - - /* - * Validate that a partition is not both excluded through its - * root by an EXCEPT clause and included by its own schema. - */ - CheckExceptPartitionNotInSchemaList(except_rels, schemaidlist); - - PublicationAddTables(puboid, except_rels, false, NULL); - CloseTableList(except_rels); - } + PublicationAddExceptTables(puboid, except_pubtables, + explicitrelids, schemaidlist, NULL); } } @@ -1772,7 +1927,8 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, */ static void AlterPublicationSchemas(AlterPublicationStmt *stmt, - HeapTuple tup, List *schemaidlist) + HeapTuple tup, List *schemaidlist, + List *except_pubtables) { Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); @@ -1822,6 +1978,12 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, ReleaseSysCache(coltuple); } + /* + * Reject a schema whose tables the publication already excludes + * through a root or parent in another schema. + */ + CheckSchemaListNotExcluded(pubform->oid, schemaidlist); + PublicationAddSchemas(pubform->oid, schemaidlist, false, stmt); } else if (stmt->action == AP_DropObjects) @@ -1849,6 +2011,78 @@ AlterPublicationSchemas(AlterPublicationStmt *stmt, */ PublicationAddSchemas(pubform->oid, schemaidlist, true, stmt); } + + /* + * Increment the command counter so that is_schema_publication() in + * GetExcludedPublicationTables() can see the just-inserted schema rows + * when AlterPublicationSchemaExceptTables runs next. + */ + if (stmt->action == AP_AddObjects || stmt->action == AP_SetObjects) + CommandCounterIncrement(); + + AlterPublicationSchemaExceptTables(stmt, tup, except_pubtables, schemaidlist); +} + +/* + * Alter the EXCEPT list of a schema-level publication. + * + * Adds, removes, or replaces except-table entries in pg_publication_rel + * (rows with prexcept = true). These entries suppress publication of the + * named tables that would otherwise be covered by a FOR TABLES IN SCHEMA + * clause. + */ +static void +AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, List *except_pubtables, + List *schemaidlist) +{ + Form_pg_publication pubform = (Form_pg_publication) GETSTRUCT(tup); + Oid pubid = pubform->oid; + + /* + * Nothing to do if no EXCEPT entries. + */ + if (!except_pubtables) + return; + + /* + * This function handles EXCEPT entries for schema-level publications + * only. For FOR ALL TABLES publications, EXCEPT entries are already + * processed by AlterPublicationTables(). + */ + if (schemaidlist == NIL && !is_schema_publication(pubid)) + return; + + /* + * Dropping a schema from a publication removes all its EXCEPT entries via + * cascade. The concept of "drop all schema tables from the publication + * EXCEPT these ones" is not supported. + */ + if (stmt->action == AP_DropObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); + + /* + * XXX EXCEPT with SET is not currently implemented. Workaround: DROP and + * re-ADD the schema with the desired EXCEPT list. + */ + if (stmt->action == AP_SetObjects) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"), + errhint("Drop and re-add the schema with the desired EXCEPT list."))); + + if (stmt->action == AP_AddObjects) + { + List *explicitrelids; + + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + PublicationAddExceptTables(pubid, except_pubtables, explicitrelids, + schemaidlist, stmt); + } } /* @@ -2030,12 +2264,12 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) else { List *relations = NIL; - List *exceptrelations = NIL; + List *except_pubtables = NIL; List *schemaidlist = NIL; Oid pubid = pubform->oid; ObjectsInPublicationToOids(stmt->pubobjects, pstate, &relations, - &exceptrelations, &schemaidlist); + &except_pubtables, &schemaidlist); CheckAlterPublication(stmt, tup, relations, schemaidlist); @@ -2058,10 +2292,12 @@ AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt) errmsg("publication \"%s\" does not exist", stmt->pubname)); - relations = list_concat(relations, exceptrelations); + if (stmt->for_all_tables) + relations = list_concat(relations, except_pubtables); + AlterPublicationTables(stmt, tup, relations, pstate->p_sourcetext, schemaidlist != NIL); - AlterPublicationSchemas(stmt, tup, schemaidlist); + AlterPublicationSchemas(stmt, tup, schemaidlist, except_pubtables); AlterPublicationAllFlags(stmt, rel, tup); } diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c index feed88f9854..1b5d91fbd8f 100644 --- a/src/bin/pg_dump/pg_dump.c +++ b/src/bin/pg_dump/pg_dump.c @@ -4973,6 +4973,7 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) PublicationInfo *pubinfo = pubsinfo->publication; PQExpBuffer query; char *tag; + bool has_except = false; /* Do nothing if not dumping schema */ if (!dopt->dumpSchema) @@ -4983,7 +4984,34 @@ dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo) query = createPQExpBuffer(); appendPQExpBuffer(query, "ALTER PUBLICATION %s ", fmtId(pubinfo->dobj.name)); - appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s;\n", fmtId(schemainfo->dobj.name)); + appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s", fmtId(schemainfo->dobj.name)); + + /* + * Append EXCEPT clause for any tables that belong to this schema and are + * excluded from the publication. + */ + for (SimplePtrListCell *cell = pubinfo->except_tables.head; cell; cell = cell->next) + { + TableInfo *tbinfo = (TableInfo *) cell->ptr; + + if (strcmp(tbinfo->dobj.namespace->dobj.name, schemainfo->dobj.name) == 0) + { + if (!has_except) + { + appendPQExpBufferStr(query, " EXCEPT ("); + has_except = true; + } + else + appendPQExpBufferStr(query, ", "); + + appendPQExpBuffer(query, "TABLE ONLY %s", fmtId(tbinfo->dobj.name)); + } + } + + if (has_except) + appendPQExpBufferStr(query, ")"); + + appendPQExpBufferStr(query, ";\n"); /* * There is no point in creating drop query as the drop is done by schema diff --git a/src/bin/pg_dump/t/002_pg_dump.pl b/src/bin/pg_dump/t/002_pg_dump.pl index 9258948b583..d18b3b0d7b9 100644 --- a/src/bin/pg_dump/t/002_pg_dump.pl +++ b/src/bin/pg_dump/t/002_pg_dump.pl @@ -3283,6 +3283,30 @@ my %tests = ( like => { %full_runs, section_post_data => 1, }, }, + 'CREATE PUBLICATION pub11' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub11 FOR TABLES IN SCHEMA dump_test EXCEPT (TABLE test_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub11 WITH (publish = 'insert, update, delete, truncate');\E + .*? + \QALTER PUBLICATION pub11 ADD TABLES IN SCHEMA dump_test EXCEPT (TABLE ONLY test_table);\E + /xms, + like => { %full_runs, section_post_data => 1, }, + }, + + 'CREATE PUBLICATION pub12' => { + create_order => 50, + create_sql => + 'CREATE PUBLICATION pub12 FOR TABLES IN SCHEMA dump_test EXCEPT (TABLE test_table, dump_test.test_second_table);', + regexp => qr/^ + \QCREATE PUBLICATION pub12 WITH (publish = 'insert, update, delete, truncate');\E + .*? + \QALTER PUBLICATION pub12 ADD TABLES IN SCHEMA dump_test EXCEPT (TABLE ONLY test_table, TABLE ONLY test_second_table);\E + /xms, + like => { %full_runs, section_post_data => 1, }, + }, + 'CREATE SUBSCRIPTION sub1' => { create_order => 50, create_sql => 'CREATE SUBSCRIPTION sub1 diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index f069e2654cc..6d857865d6b 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2359,6 +2359,23 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); + /* After a single schema name in ADD context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 9498ef9a7f8..bb3ed7b0cb1 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -671,14 +671,14 @@ DROP PUBLICATION testpub_except_alter1; CREATE PUBLICATION testpub_except_alter2 FOR TABLE pub_test.testpub_tbl_s1; ALTER PUBLICATION testpub_except_alter2 SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: EXCEPT clause is not supported with SET in ALTER PUBLICATION +HINT: Drop and re-add the schema with the desired EXCEPT list. \dRp+ testpub_except_alter2 Publication testpub_except_alter2 Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description --------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- regress_publication_user | f | f | t | t | t | t | none | f | -Tables from schemas: - "pub_test" -Except tables: +Tables: "pub_test.testpub_tbl_s1" DROP PUBLICATION testpub_except_alter2; @@ -709,7 +709,7 @@ CREATE PUBLICATION testpub_inh TABLES IN SCHEMA public; ERROR: table "public.testpub_inh_child" cannot be both published and excluded DETAIL: It inherits from a table named in the EXCEPT clause of another schema, and its own schema "public" is published in full. -HINT: Use ONLY in the EXCEPT clause to exclude just the parent, or name this table in the EXCEPT clause of schema "public". +HINT: Use ONLY in the EXCEPT clause to exclude just the parent, or arrange for schema "public" to exclude this table as well. -- fail: the child is also explicitly included by the same statement CREATE PUBLICATION testpub_inh FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_inh_parent), @@ -756,12 +756,100 @@ Except tables: DROP PUBLICATION testpub_inh; DROP TABLE testpub_inh_child, pub_test.testpub_inh_sibling, pub_test.testpub_inh_parent; +-- The reverse order must be rejected too: excluding a root or parent first and +-- then adding the schema that holds a descendant reaches the same state that a +-- single statement refuses. +CREATE TABLE pub_test.testpub_xs_parted (a int) PARTITION BY LIST (a); +CREATE TABLE testpub_xs_part PARTITION OF pub_test.testpub_xs_parted + FOR VALUES IN (1); +CREATE TABLE pub_test.testpub_xs_parent (a int); +CREATE TABLE testpub_xs_child (b int) INHERITS (pub_test.testpub_xs_parent); +CREATE PUBLICATION testpub_xs + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_xs_parted); +-- fail: public holds a partition of the excluded root +ALTER PUBLICATION testpub_xs ADD TABLES IN SCHEMA public; +ERROR: cannot add schema "public" to publication "testpub_xs" +DETAIL: It contains table "public.testpub_xs_part", which descends from "pub_test.testpub_xs_parted", already named in the publication's EXCEPT clause for schema "pub_test". +HINT: The table would be both published and excluded. +DROP PUBLICATION testpub_xs; +-- An EXCEPT entry naming a plain table cannot be checked this way: whether it +-- was written with ONLY is not recorded, and with the only child in another +-- schema both spellings leave the same single row behind. So adding the +-- child's schema is accepted for either spelling. +CREATE PUBLICATION testpub_xs + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_xs_parent); +ALTER PUBLICATION testpub_xs ADD TABLES IN SCHEMA public; +DROP PUBLICATION testpub_xs; +CREATE PUBLICATION testpub_xs + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE ONLY pub_test.testpub_xs_parent); +ALTER PUBLICATION testpub_xs ADD TABLES IN SCHEMA public; +DROP PUBLICATION testpub_xs; +DROP TABLE testpub_xs_child, pub_test.testpub_xs_parent; +DROP TABLE testpub_xs_part, pub_test.testpub_xs_parted; +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; +-- fail: non-existing table in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- fail: EXCEPT table belongs to a different schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 1: ...xcept ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.tes... + ^ +-- fail: TABLE keyword is required for the first entry in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +ERROR: syntax error at or near "testpub_nopk" +LINE 1: ...lter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_no... + ^ +-- fail: exact same table given as both explicitly published and excluded +-- in a single ALTER ... ADD +ALTER PUBLICATION testpub_alter_except + ADD TABLE pub_test.testpub_tbl_s1, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot be both published and excluded +-- fail: add explicit partition and EXCEPT ancestor, given in a +-- single ALTER ... ADD statement +ALTER PUBLICATION testpub_alter_except + ADD TABLE pub_test.testpub_part_s, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ERROR: partition "pub_test.testpub_part_s" cannot be both published and excluded +DETAIL: Partition root "pub_test.testpub_parted_s" is named in the publication's EXCEPT clause for schema "pub_test". +-- fail: partition already explicitly published, then its root is EXCEPT-ed +-- via a later, separate ALTER ... ADD +ALTER PUBLICATION testpub_alter_except ADD TABLE pub_test.testpub_part_s; +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ERROR: partition "pub_test.testpub_part_s" cannot be both published and excluded +DETAIL: Partition root "pub_test.testpub_parted_s" is named in the publication's EXCEPT clause for schema "pub_test". +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_part_s; +-- fail: root already explicitly published, then its partition is rejected +-- from EXCEPT via a later, separate ALTER ... ADD (partitions can never +-- appear in EXCEPT, independent of the root's state) +ALTER PUBLICATION testpub_alter_except ADD TABLE pub_test.testpub_parted_s; +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); +ERROR: cannot specify relation "pub_test.testpub_part_s" in the publication EXCEPT clause +DETAIL: This operation is not supported for individual partitions. +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_parted_s; +-- ADD: qualified and unqualified names; unqualified is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + "pub_test.testpub_tbl_s2" + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP TABLE pub_test.testpub_parted_s CASCADE; DROP TABLE testpub_nopk, testpub_tbl_s1; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi, testpub_alter_except; --------------------------------------------- -- Tests for publications with SEQUENCES --------------------------------------------- diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 8258c0591da..913f7de3a19 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -385,13 +385,84 @@ CREATE PUBLICATION testpub_inh DROP PUBLICATION testpub_inh; DROP TABLE testpub_inh_child, pub_test.testpub_inh_sibling, pub_test.testpub_inh_parent; +-- The reverse order must be rejected too: excluding a root or parent first and +-- then adding the schema that holds a descendant reaches the same state that a +-- single statement refuses. +CREATE TABLE pub_test.testpub_xs_parted (a int) PARTITION BY LIST (a); +CREATE TABLE testpub_xs_part PARTITION OF pub_test.testpub_xs_parted + FOR VALUES IN (1); +CREATE TABLE pub_test.testpub_xs_parent (a int); +CREATE TABLE testpub_xs_child (b int) INHERITS (pub_test.testpub_xs_parent); +CREATE PUBLICATION testpub_xs + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_xs_parted); +-- fail: public holds a partition of the excluded root +ALTER PUBLICATION testpub_xs ADD TABLES IN SCHEMA public; +DROP PUBLICATION testpub_xs; +-- An EXCEPT entry naming a plain table cannot be checked this way: whether it +-- was written with ONLY is not recorded, and with the only child in another +-- schema both spellings leave the same single row behind. So adding the +-- child's schema is accepted for either spelling. +CREATE PUBLICATION testpub_xs + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_xs_parent); +ALTER PUBLICATION testpub_xs ADD TABLES IN SCHEMA public; +DROP PUBLICATION testpub_xs; +CREATE PUBLICATION testpub_xs + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE ONLY pub_test.testpub_xs_parent); +ALTER PUBLICATION testpub_xs ADD TABLES IN SCHEMA public; +DROP PUBLICATION testpub_xs; +DROP TABLE testpub_xs_child, pub_test.testpub_xs_parent; +DROP TABLE testpub_xs_part, pub_test.testpub_xs_parted; + + +--------------------------------------------- +-- EXCEPT tests for ALTER PUBLICATION +--------------------------------------------- +CREATE PUBLICATION testpub_alter_except; + +-- fail: non-existing table in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- fail: EXCEPT table belongs to a different schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- fail: TABLE keyword is required for the first entry in EXCEPT clause +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + +-- fail: exact same table given as both explicitly published and excluded +-- in a single ALTER ... ADD +ALTER PUBLICATION testpub_alter_except + ADD TABLE pub_test.testpub_tbl_s1, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: add explicit partition and EXCEPT ancestor, given in a +-- single ALTER ... ADD statement +ALTER PUBLICATION testpub_alter_except + ADD TABLE pub_test.testpub_part_s, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); + +-- fail: partition already explicitly published, then its root is EXCEPT-ed +-- via a later, separate ALTER ... ADD +ALTER PUBLICATION testpub_alter_except ADD TABLE pub_test.testpub_part_s; +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_part_s; + +-- fail: root already explicitly published, then its partition is rejected +-- from EXCEPT via a later, separate ALTER ... ADD (partitions can never +-- appear in EXCEPT, independent of the root's state) +ALTER PUBLICATION testpub_alter_except ADD TABLE pub_test.testpub_parted_s; +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_parted_s; + +-- ADD: qualified and unqualified names; unqualified is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); +\dRp+ testpub_alter_except -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; DROP TABLE pub_test.testpub_parted_s CASCADE; DROP TABLE testpub_nopk, testpub_tbl_s1; -DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi, testpub_alter_except; --------------------------------------------- -- Tests for publications with SEQUENCES diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index de4e7dff7ba..e0650d685bc 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -347,6 +347,38 @@ is($result, qq(5), $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); +# ============================================ +# ALTER PUBLICATION EXCEPT for TABLES IN SCHEMA +# ============================================ + +# Truncate subscriber tables to remove data accumulated from previous tests. +$node_subscriber->safe_psql('postgres', + 'TRUNCATE sch1.tab_published, sch1.tab_excluded, sch1.parent, sch1.child'); + +# ADD: add a schema with an excepted table; verify the except entry takes effect. +$node_publisher->safe_psql('postgres', "CREATE PUBLICATION sch_pub"); +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub ADD TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_excluded)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(6), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: included table synced'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + # Cleanup schema tables before the multi-publication section. $node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); $node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); -- 2.55.0
v28-0004-Documentation-Patch.patch (application/octet-stream, 12.6K) download From c4ee5dadb20afe509faf36da242c1f97ce88c13d Mon Sep 17 00:00:00 2001 From: Nisha Moond <nisha.moond412@gmail.com> Date: Thu, 30 Jul 2026 10:15:42 +0530 Subject: [PATCH v28 4/4] Documentation Patch --- doc/src/sgml/logical-replication.sgml | 3 +- doc/src/sgml/ref/alter_publication.sgml | 54 ++++++++++++++++++++- doc/src/sgml/ref/create_publication.sgml | 60 ++++++++++++++++++++---- 3 files changed, 104 insertions(+), 13 deletions(-) diff --git a/doc/src/sgml/logical-replication.sgml b/doc/src/sgml/logical-replication.sgml index 3a61e2d6889..eaf2d814ac6 100644 --- a/doc/src/sgml/logical-replication.sgml +++ b/doc/src/sgml/logical-replication.sgml @@ -117,7 +117,8 @@ or <literal>FOR ALL SEQUENCES</literal>. Unlike tables, sequences can be synchronized at any time. For more information, see <xref linkend="logical-replication-sequences"/>. When a publication is - created with <literal>FOR ALL TABLES</literal>, a table or set of tables can + created with <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal>, a table or set of tables can be explicitly excluded from publication using the <link linkend="sql-createpublication-params-for-except-table"><literal>EXCEPT</literal></link> clause. diff --git a/doc/src/sgml/ref/alter_publication.sgml b/doc/src/sgml/ref/alter_publication.sgml index 86bdc98fd09..c1a60797361 100644 --- a/doc/src/sgml/ref/alter_publication.sgml +++ b/doc/src/sgml/ref/alter_publication.sgml @@ -31,7 +31,7 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA <replaceable class="parameter">tables_in_schema</replaceable> [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -47,6 +47,10 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r <replaceable class="parameter">table_object</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] [ WHERE ( <replaceable class="parameter">expression</replaceable> ) ] +<phrase>and <replaceable class="parameter">tables_in_schema</replaceable> is:</phrase> + + { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] + <phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> TABLE <replaceable class="parameter">table_object</replaceable> [, ... ] @@ -69,6 +73,9 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r The first two variants modify which tables/schemas are part of the publication. The <literal>ADD</literal> and <literal>DROP</literal> clauses will add and remove one or more tables/schemas from the publication. + The <literal>EXCEPT</literal> clause can be used with + <literal>ADD TABLES IN SCHEMA</literal> to exclude specific tables from a + schema-level publication. </para> <para> @@ -93,7 +100,11 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r used with a publication defined with <literal>FOR TABLE</literal> or <literal>FOR TABLES IN SCHEMA</literal>, replaces the list of tables/schemas in the publication with the specified list; the existing tables or schemas - that were present in the publication will be removed. + that were present in the publication will be removed. When + <literal>SET TABLES IN SCHEMA</literal> is used with an + <literal>EXCEPT</literal> clause, the excluded tables for each schema are + replaced with the specified list; if <literal>EXCEPT</literal> is omitted + for a schema, any existing exclusions for that schema are cleared. </para> <para> @@ -211,6 +222,26 @@ ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <r </listitem> </varlistentry> + <varlistentry id="sql-alterpublication-params-except"> + <term><literal>EXCEPT</literal></term> + <listitem> + <para> + When used with <literal>ADD TABLES IN SCHEMA</literal> + or <literal>SET TABLES IN SCHEMA</literal>, specifies tables to be + excluded from the publication. Each named table must belong to the + schema specified in the same <literal>TABLES IN SCHEMA</literal> clause. + Table names may be schema-qualified or unqualified; unqualified names + are implicitly qualified with the schema named in the same clause. See + <xref linkend="sql-createpublication"/> for further details on the + semantics of <literal>EXCEPT</literal>. + </para> + <para> + Dropping a table always removes it from the <literal>EXCEPT</literal> + clause. + </para> + </listitem> + </varlistentry> + <varlistentry id="sql-alterpublication-params-set"> <term><literal>SET ( <replaceable class="parameter">publication_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] )</literal></term> <listitem> @@ -301,6 +332,25 @@ ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA marketing, sales; </programlisting> </para> + <para> + Add schema <structname>sales</structname> to the publication + <structname>sales_publication</structname>, excluding the + <structname>sales.internal</structname> and + <structname>sales.drafts</structname> tables: +<programlisting> +ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA sales EXCEPT (TABLE internal, drafts); +</programlisting> + </para> + + <para> + Replace the schema list of <structname>sales_publication</structname> with + only schema <structname>sales</structname>, excluding only + <structname>sales.drafts</structname> table: +<programlisting> +ALTER PUBLICATION sales_publication SET TABLES IN SCHEMA sales EXCEPT (TABLE drafts); +</programlisting> + </para> + <para> Add tables <structname>users</structname>, <structname>departments</structname> and schema diff --git a/doc/src/sgml/ref/create_publication.sgml b/doc/src/sgml/ref/create_publication.sgml index 35c28006f60..2de5bedb1c8 100644 --- a/doc/src/sgml/ref/create_publication.sgml +++ b/doc/src/sgml/ref/create_publication.sgml @@ -28,7 +28,7 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> TABLE <replaceable class="parameter">table_and_columns</replaceable> [, ... ] - TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] + TABLES IN SCHEMA <replaceable class="parameter">tables_in_schema</replaceable> [, ... ] <phrase>and <replaceable class="parameter">publication_all_object</replaceable> is one of:</phrase> @@ -39,6 +39,10 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <replaceable class="parameter">table_object</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] [ WHERE ( <replaceable class="parameter">expression</replaceable> ) ] +<phrase>and <replaceable class="parameter">tables_in_schema</replaceable> is:</phrase> + + { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [ EXCEPT ( <replaceable class="parameter">except_table_object</replaceable> [, ... ] ) ] + <phrase>and <replaceable class="parameter">except_table_object</replaceable> is:</phrase> TABLE <replaceable class="parameter">table_object</replaceable> [, ... ] @@ -172,6 +176,8 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <para> Marks the publication as one that replicates changes for all tables in the specified list of schemas, including tables created in the future. + Tables listed in the <literal>EXCEPT</literal> clause for a given schema + are excluded from the publication. </para> <para> @@ -203,7 +209,7 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <para> Marks the publication as one that replicates changes for all tables in the database, including tables created in the future. Tables listed in - <literal>EXCEPT</literal> clause are excluded from the publication. + the <literal>EXCEPT</literal> clause are excluded from the publication. </para> </listitem> </varlistentry> @@ -228,13 +234,21 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <listitem> <para> This clause specifies a list of tables to be excluded from the - publication. + publication. It can be used with <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal>. For <literal>FOR TABLES IN + SCHEMA</literal>, the exclusion applies only to tables in the schema + associated with the <literal>EXCEPT</literal> clause. </para> <para> - Once a table is excluded, the exclusion applies to that table - regardless of its name or schema. Renaming the table or moving it to - another schema using <command>ALTER TABLE ... SET SCHEMA</command> does - not remove the exclusion. + Once a table is excluded under <literal>FOR ALL TABLES</literal>, the + exclusion applies to that table regardless of its name or schema. + Renaming the table or moving it to another schema using + <command>ALTER TABLE ... SET SCHEMA</command> does not remove the + exclusion. However, for <literal>FOR TABLES IN SCHEMA</literal>, because + the <literal>EXCEPT</literal> is schema-scoped, moving a schema-excluded + table to another schema does remove the exclusion; if the table is later + moved back, the exclusion is not restored and must be re-established + with <command>ALTER PUBLICATION</command>. </para> <para> For inherited tables, if <literal>ONLY</literal> is specified before the @@ -245,12 +259,29 @@ CREATE PUBLICATION <replaceable class="parameter">name</replaceable> <replaceable class="parameter">table_name</replaceable> to explicitly indicate that descendant tables are excluded. </para> + <para> + For <literal>FOR TABLES IN SCHEMA</literal>, an <literal>EXCEPT</literal> + entry excludes only those descendants that belong to the schema specified + by the corresponding <literal>FOR TABLES IN SCHEMA</literal> clause. A + descendant in a different schema is not excluded, since the exclusion is + scoped to that schema. Publishing that schema in the same statement is + therefore rejected because the descendant would be both published and + excluded. + </para> <para> For partitioned tables, only the root partitioned table may be specified in <literal>EXCEPT</literal>. Doing so excludes the root table and - all of its partitions from replication. The optional - <literal>ONLY</literal> and <literal>*</literal> has no effect for - partitioned tables. + all of its partitions from replication, including any partition that + lives in another schema. The optional <literal>ONLY</literal> and + <literal>*</literal> has no effect for partitioned tables. + </para> + <para> + Because the exclusion is bound to the schema of the + <literal>TABLES IN SCHEMA</literal> clause it belongs to, a partition in + another schema is reached only when that schema is not itself published: + publishing it as well would both publish and exclude the same partition, + which is rejected. Excluding such a partition on its own is not possible + either, since a partition may not be named in <literal>EXCEPT</literal>. </para> <para> There can be a case where a subscription includes multiple publications. @@ -552,6 +583,15 @@ CREATE PUBLICATION production_publication FOR TABLE users, departments, TABLES I CREATE PUBLICATION sales_publication FOR TABLES IN SCHEMA marketing, sales; </programlisting></para> + <para> + Create a publication that publishes all changes for all the tables present in + the schema <structname>sales</structname>, except + <structname>internal</structname> and <structname>drafts</structname>: +<programlisting> +CREATE PUBLICATION sales_filtered FOR TABLES IN SCHEMA sales EXCEPT (TABLE internal, drafts); +</programlisting> + </para> + <para> Create a publication that publishes all changes for table <structname>users</structname>, but replicates only columns <structname>user_id</structname> and -- 2.55.0
v28-0003-Add-EXCEPT-support-to-ALTER-PUBLICATION-SET-TABL.patch (application/octet-stream, 42.2K) download From d37a073e297302083053a9e6137b7b4eb6a4f0c6 Mon Sep 17 00:00:00 2001 From: Vignesh C <c_vigneshwaran@apple.com> Date: Tue, 18 Aug 2026 09:41:49 +0530 Subject: [PATCH v28 3/4] Add EXCEPT support to ALTER PUBLICATION SET TABLES IN SCHEMA Extend AlterPublicationExceptTables() with the AP_SetObjects case, which redefines the publication and replaces the entire EXCEPT list. Syntax: ALTER PUBLICATION pub SET TABLES IN SCHEMA s EXCEPT (TABLE t1); This patch also cleans up EXCEPT entries when a schema is dropped from the publication. --- src/backend/commands/publicationcmds.c | 298 +++++++++++++++++----- src/bin/psql/tab-complete.in.c | 17 ++ src/test/regress/expected/publication.out | 174 ++++++++++++- src/test/regress/sql/publication.sql | 80 ++++++ src/test/subscription/t/037_except.pl | 85 ++++++ 5 files changed, 590 insertions(+), 64 deletions(-) diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 246649da0ea..0f9790c4c0f 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -67,13 +67,18 @@ static void CloseTableList(List *rels); static void LockSchemaList(List *schemalist); static void PublicationAddTables(Oid pubid, List *rels, bool if_not_exists, AlterPublicationStmt *stmt); -static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok); +static void PublicationDropTables(Oid pubid, List *rels, bool missing_ok, + bool delete_excluded); static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); static void CheckSchemaListNotExcluded(Oid pubid, List *schemaidlist); +static void CheckExceptConflicts(Oid pubid, List *except_rels, + List *cross_schema_children, + List *explicitrelids, List *pubschemas, + bool existing_except_kept); static void PublicationAddExceptTables(Oid pubid, List *except_pubtables, List *explicitrelids, - List *schemaidlist, + List *pubschemas, AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); static void AlterPublicationSchemas(AlterPublicationStmt *stmt, @@ -90,7 +95,12 @@ static void CheckExceptNotInTableList(List *except_rels, static void CheckExceptChildNotInSchemaList(Oid pubid, List *cross_schema_children, List *pubschemas, - List *except_rels); + List *except_rels, + bool existing_except_kept); +static void CheckExceptConflicts(Oid pubid, List *except_rels, + List *cross_schema_children, + List *explicitrelids, List *pubschemas, + bool existing_except_kept); static void CheckExceptPartitionNotInSchemaList(List *except_rels, List *schemaidlist); static void ProcessSchemaExceptTables(Oid schemaid, List *except_tables, @@ -966,16 +976,18 @@ CheckExceptNotInTableList(List *except_rels, List *cross_schema_children, * the schemas that this statement publishes and those the publication already * publishes; ALTER PUBLICATION ... ADD names only the former. * - * If the child is excluded anyway, there is no conflict, since both sides - * agree. That is so when an EXCEPT clause of this statement names it, and also - * when the publication already holds an EXCEPT entry for it. + * If the child ends up excluded anyway, there is no conflict, since both sides + * agree. That is so when an EXCEPT clause of this statement names it, and, + * where existing_except_kept says such entries remain in force, when the + * publication already holds an EXCEPT entry for it. * * Conflicts with explicitly listed tables are handled by * CheckExceptNotInTableList(). */ static void CheckExceptChildNotInSchemaList(Oid pubid, List *cross_schema_children, - List *pubschemas, List *except_rels) + List *pubschemas, List *except_rels, + bool existing_except_kept) { foreach_oid(childrelid, cross_schema_children) { @@ -996,8 +1008,8 @@ CheckExceptChildNotInSchemaList(Oid pubid, List *cross_schema_children, } } - /* Or does the publication already exclude it? */ - if (!excluded && + /* Or is it already excluded, by an entry that remains in force? */ + if (!excluded && existing_except_kept && CheckPublicationRelEntry(pubid, childrelid, &is_except) && is_except) excluded = true; @@ -1119,41 +1131,27 @@ CheckSchemaListNotExcluded(Oid pubid, List *schemaidlist) } /* - * Add the EXCEPT tables of a statement's TABLES IN SCHEMA clauses to a - * publication, after checking that the statement does not contradict itself. + * Check that the EXCEPT entries do not conflict with the relations and + * schemas included by the publication after the statement completes. * - * explicitrelids is the set of relations the statement publishes by name, and - * schemaidlist the schemas it publishes in full; both are needed to detect a - * table that would be published and excluded at the same time. + * except_rels and cross_schema_children contain the EXCEPT entries collected + * by OpenTableList(), while explicitrelids contains explicitly included + * relations. * - * if_not_exists is false: an EXCEPT entry that is already present, or that - * collides with an ordinary member, is a conflict worth reporting rather than - * something to skip silently. + * pubschemas contains the schemas included by the publication after the + * statement. + * + * existing_except_kept says whether the EXCEPT entries the publication already + * holds are still in force once the statement completes. ADD only adds + * entries, so they are. SET replaces the whole list, so an existing entry may + * be one this statement drops, and must not be taken as agreement that a + * cross-schema child is excluded. */ static void -PublicationAddExceptTables(Oid pubid, List *except_pubtables, - List *explicitrelids, List *schemaidlist, - AlterPublicationStmt *stmt) +CheckExceptConflicts(Oid pubid, List *except_rels, + List *cross_schema_children, List *explicitrelids, + List *pubschemas, bool existing_except_kept) { - List *except_rels; - List *cross_schema_children = NIL; - List *pubschemas; - - if (except_pubtables == NIL) - return; - - except_rels = OpenTableList(except_pubtables, &cross_schema_children); - - /* - * A table is published by this publication if the statement publishes its - * schema, or if the publication already published it. ALTER PUBLICATION - * ... ADD names only the schemas being added, so the catalog has to be - * consulted as well; otherwise a child in a schema that an earlier - * command added would not be recognised as a conflict. - */ - pubschemas = list_concat_unique_oid(list_copy(schemaidlist), - GetPublicationSchemas(pubid)); - /* * Validate that a table is not both explicitly included and excluded by * the schema's EXCEPT clause. @@ -1166,13 +1164,49 @@ PublicationAddExceptTables(Oid pubid, List *except_pubtables, * clause and included by its schema. */ CheckExceptChildNotInSchemaList(pubid, cross_schema_children, pubschemas, - except_rels); + except_rels, existing_except_kept); /* * Validate that a partition is not both excluded through its root by an * EXCEPT clause and included by its own schema. */ CheckExceptPartitionNotInSchemaList(except_rels, pubschemas); +} + +/* + * Add the EXCEPT tables of a statement's TABLES IN SCHEMA clauses to a + * publication, after checking that the statement does not contradict itself. + * + * explicitrelids is the set of relations the statement publishes by name, and + * pubschemas the schemas the publication publishes once the statement + * completes; both are needed to detect a table that would be published and + * excluded at the same time. See CheckExceptConflicts() for how callers pick + * pubschemas. + * + * This is for CREATE PUBLICATION and ALTER PUBLICATION ... ADD, which only add + * EXCEPT entries. ALTER PUBLICATION ... SET replaces them, and does its own + * reconciliation; see AlterPublicationSchemaExceptTables(). + * + * if_not_exists is false: an EXCEPT entry that is already present, or that + * collides with an ordinary member, is a conflict worth reporting rather than + * something to skip silently. + */ +static void +PublicationAddExceptTables(Oid pubid, List *except_pubtables, + List *explicitrelids, List *pubschemas, + AlterPublicationStmt *stmt) +{ + List *except_rels; + List *cross_schema_children = NIL; + + if (except_pubtables == NIL) + return; + + except_rels = OpenTableList(except_pubtables, &cross_schema_children); + + CheckExceptConflicts(pubid, except_rels, cross_schema_children, + explicitrelids, pubschemas, + true /* existing_except_kept */ ); PublicationAddTables(pubid, except_rels, false, stmt); CloseTableList(except_rels); @@ -1476,6 +1510,12 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) */ LockSchemaList(schemaidlist); PublicationAddSchemas(puboid, schemaidlist, true, NULL); + + /* + * The schemas this statement names are the publication's whole + * set; the pg_publication_namespace rows inserted just above are + * not visible to a catalog lookup within the same command. + */ PublicationAddExceptTables(puboid, except_pubtables, explicitrelids, schemaidlist, NULL); } @@ -1758,7 +1798,7 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, PublicationAddTables(pubid, rels, false, stmt); } else if (stmt->action == AP_DropObjects) - PublicationDropTables(pubid, rels, false); + PublicationDropTables(pubid, rels, false, false); else /* AP_SetObjects */ { List *oldrelids = NIL; @@ -1906,7 +1946,7 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, } /* And drop them. */ - PublicationDropTables(pubid, delrels, true); + PublicationDropTables(pubid, delrels, true, true); /* * Don't bother calculating the difference for adding, we'll catch and @@ -2040,9 +2080,11 @@ AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, Oid pubid = pubform->oid; /* - * Nothing to do if no EXCEPT entries. + * Nothing to do if there are no EXCEPT entries, unless handling the SET + * command, because if the user has removed all exceptions we need to drop + * any existing ones. */ - if (!except_pubtables) + if (!except_pubtables && stmt->action != AP_SetObjects) return; /* @@ -2063,16 +2105,6 @@ AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); - /* - * XXX EXCEPT with SET is not currently implemented. Workaround: DROP and - * re-ADD the schema with the desired EXCEPT list. - */ - if (stmt->action == AP_SetObjects) - ereport(ERROR, - (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("EXCEPT clause is not supported with SET in ALTER PUBLICATION"), - errhint("Drop and re-add the schema with the desired EXCEPT list."))); - if (stmt->action == AP_AddObjects) { List *explicitrelids; @@ -2080,8 +2112,83 @@ AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, explicitrelids = GetIncludedPublicationRelations(pubid, PUBLICATION_PART_ROOT); + /* + * schemaidlist holds only the schemas being added, so read the whole + * set from the catalog: AlterPublicationSchemas() has applied the + * additions and incremented the command counter before calling us. + */ PublicationAddExceptTables(pubid, except_pubtables, explicitrelids, - schemaidlist, stmt); + GetPublicationSchemas(pubid), stmt); + } + else + { + List *oldexceptrelids = NIL; + List *newexceptrelids = NIL; + List *delrelids = NIL; + List *except_rels; + List *explicitrelids; + List *cross_schema_children = NIL; + + except_rels = OpenTableList(except_pubtables, &cross_schema_children); + + /* Collect OIDs of the desired new EXCEPT list. */ + foreach_ptr(PublicationRelInfo, pri, except_rels) + newexceptrelids = lappend_oid(newexceptrelids, + RelationGetRelid(pri->relation)); + + explicitrelids = GetIncludedPublicationRelations(pubid, + PUBLICATION_PART_ROOT); + + /* + * Check that the statement does not contradict itself. SET replaces + * the EXCEPT list rather than adding to it, so the entries the + * publication currently holds cannot be taken as agreement: one of + * them may be dropped below. + */ + CheckExceptConflicts(pubid, except_rels, cross_schema_children, + explicitrelids, schemaidlist, + false /* existing_except_kept */ ); + + /* + * Get the current set of EXCEPT entries. Only FOR ALL TABLES and + * schema-level publications can have EXCEPT entries; for any other + * publication type oldexceptrelids stays NIL. + */ + if (GetPublication(pubid)->alltables || is_schema_publication(pubid)) + oldexceptrelids = GetExcludedPublicationTables(pubid, + PUBLICATION_PART_ROOT); + /* Build a list of old EXCEPT entries not present in the new list. */ + foreach_oid(oldrelid, oldexceptrelids) + { + if (!list_member_oid(newexceptrelids, oldrelid)) + delrelids = lappend_oid(delrelids, oldrelid); + } + + /* Drop old EXCEPT entries not present in the new list. */ + foreach_oid(relid, delrelids) + { + Oid proid; + ObjectAddress obj; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + /* + * Add the new EXCEPT entries. if_not_exists is true here because an + * entry present in both the old and the new list is not dropped above + * and so is still there. + */ + PublicationAddTables(pubid, except_rels, true, stmt); + + CloseTableList(except_rels); } } @@ -2717,33 +2824,69 @@ PublicationAddTables(Oid pubid, List *rels, bool if_not_exists, /* * Remove listed tables from the publication. + * + * delete_excluded controls how EXCEPT (prexcept=true) rows are handled: + * true - delete them silently. Used by the SET path to clear stale + * EXCEPT rows when ALTER PUBLICATION ... SET replaces or removes + * the EXCEPT clause. + * false - treat them as "not a member". Used by ALTER ... DROP TABLE: an + * EXCEPT entry is not something DROP TABLE is expected to remove. */ static void -PublicationDropTables(Oid pubid, List *rels, bool missing_ok) +PublicationDropTables(Oid pubid, List *rels, bool missing_ok, + bool delete_excluded) { ObjectAddress obj; ListCell *lc; - Oid prid; foreach(lc, rels) { PublicationRelInfo *pubrel = (PublicationRelInfo *) lfirst(lc); Relation rel = pubrel->relation; Oid relid = RelationGetRelid(rel); + HeapTuple tup; + Form_pg_publication_rel pubrelform; + Oid prid = InvalidOid; + bool is_except = false; if (pubrel->columns) ereport(ERROR, errcode(ERRCODE_SYNTAX_ERROR), errmsg("column list must not be specified in ALTER PUBLICATION ... DROP")); - prid = GetSysCacheOid2(PUBLICATIONRELMAP, Anum_pg_publication_rel_oid, - ObjectIdGetDatum(relid), - ObjectIdGetDatum(pubid)); - if (!OidIsValid(prid)) + tup = SearchSysCache2(PUBLICATIONRELMAP, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (HeapTupleIsValid(tup)) + { + pubrelform = (Form_pg_publication_rel) GETSTRUCT(tup); + is_except = pubrelform->prexcept; + prid = pubrelform->oid; + ReleaseSysCache(tup); + } + + /* + * DROP TABLE operates only on regular member rows. A missing row and + * an EXCEPT row both mean the table isn't currently published, but we + * distinguish them so the EXCEPT case can carry a hint pointing the + * user at the EXCEPT clause. The SET-cleanup caller (delete_excluded + * = true) intends to remove EXCEPT rows and so bypasses the EXCEPT + * half of this check. + */ + if (!OidIsValid(prid) || (is_except && !delete_excluded)) { if (missing_ok) continue; + if (is_except) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("cannot drop table \"%s\" from publication \"%s\"", + RelationGetQualifiedRelationName(rel), + get_publication_name(pubid, false)), + errdetail("The table is currently named in an EXCEPT clause of the publication."), + errhint("Change the EXCEPT clause using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT."))); + ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("relation \"%s\" is not part of the publication", @@ -2799,6 +2942,7 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) foreach(lc, schemas) { Oid schemaid = lfirst_oid(lc); + List *except_relids; psid = GetSysCacheOid2(PUBLICATIONNAMESPACEMAP, Anum_pg_publication_namespace_oid, @@ -2815,8 +2959,40 @@ PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok) get_namespace_name(schemaid)))); } + /* + * Collect EXCEPT entries for tables belonging to this schema before + * removing the schema entry. + */ + except_relids = GetExcludedPublicationTables(pubid, PUBLICATION_PART_ROOT); + ObjectAddressSet(obj, PublicationNamespaceRelationId, psid); performDeletion(&obj, DROP_CASCADE, 0); + + /* + * Drop any prexcept rows for tables belonging to this schema. These + * rows have no pg_depend entry pointing at the + * pg_publication_namespace row, so they are not cascaded by the + * performDeletion() call above and must be cleaned up explicitly. + */ + foreach_oid(relid, except_relids) + { + Oid proid; + + if (get_rel_namespace(relid) != schemaid) + continue; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddressSet(obj, PublicationRelRelationId, proid); + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + list_free(except_relids); } } diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index 6d857865d6b..d7a083ea871 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -2376,6 +2376,23 @@ match_previous_words(int pattern_id, } else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) COMPLETE_WITH(")"); + /* After a single schema name in SET context, offer EXCEPT ( TABLE */ + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny) && + !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* ALTER PUBLICATION <name> SET ( */ else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index bb3ed7b0cb1..463dc4098e2 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -671,14 +671,14 @@ DROP PUBLICATION testpub_except_alter1; CREATE PUBLICATION testpub_except_alter2 FOR TABLE pub_test.testpub_tbl_s1; ALTER PUBLICATION testpub_except_alter2 SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); -ERROR: EXCEPT clause is not supported with SET in ALTER PUBLICATION -HINT: Drop and re-add the schema with the desired EXCEPT list. \dRp+ testpub_except_alter2 Publication testpub_except_alter2 Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description --------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- regress_publication_user | f | f | t | t | t | t | none | f | -Tables: +Tables from schemas: + "pub_test" +Except tables: "pub_test.testpub_tbl_s1" DROP PUBLICATION testpub_except_alter2; @@ -753,6 +753,52 @@ Except tables: "pub_test.testpub_inh_sibling" "public.testpub_inh_child" +DROP PUBLICATION testpub_inh; +-- SET replaces the EXCEPT list rather than adding to it, so an entry the +-- publication currently holds cannot excuse a conflict: it may be one that this +-- same statement drops. +CREATE PUBLICATION testpub_inh + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_inh_parent), + TABLES IN SCHEMA public EXCEPT (TABLE testpub_inh_child); +-- fail: dropping public's EXCEPT clause would leave testpub_inh_child published +-- while pub_test's clause still covers it +ALTER PUBLICATION testpub_inh + SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_inh_parent), + TABLES IN SCHEMA public; +ERROR: table "public.testpub_inh_child" cannot be both published and excluded +DETAIL: It inherits from a table named in the EXCEPT clause of another schema, and its own schema "public" is published in full. +HINT: Use ONLY in the EXCEPT clause to exclude just the parent, or arrange for schema "public" to exclude this table as well. +-- ok: the new EXCEPT list still excludes it, so both clauses agree +ALTER PUBLICATION testpub_inh + SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_inh_parent), + TABLES IN SCHEMA public EXCEPT (TABLE testpub_inh_child); +\dRp+ testpub_inh + Publication testpub_inh + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_inh_parent" + "pub_test.testpub_inh_sibling" + "public.testpub_inh_child" + +-- ok: public is no longer published, so nothing is both published and excluded +ALTER PUBLICATION testpub_inh + SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_inh_parent); +\dRp+ testpub_inh + Publication testpub_inh + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_inh_parent" + "pub_test.testpub_inh_sibling" + DROP PUBLICATION testpub_inh; DROP TABLE testpub_inh_child, pub_test.testpub_inh_sibling, pub_test.testpub_inh_parent; @@ -784,6 +830,19 @@ CREATE PUBLICATION testpub_xs FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE ONLY pub_test.testpub_xs_parent); ALTER PUBLICATION testpub_xs ADD TABLES IN SCHEMA public; DROP PUBLICATION testpub_xs; +-- SET runs the same conflict checks. Unlike ADD it replaces the EXCEPT list, +-- so an exclusion the publication already holds is not carried over and cannot +-- conflict with anything; only what the statement itself names can. +CREATE PUBLICATION testpub_xs + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_xs_parted); +-- fail: public holds a partition of the root this statement excludes +ALTER PUBLICATION testpub_xs + SET TABLES IN SCHEMA public, pub_test + EXCEPT (TABLE pub_test.testpub_xs_parted); +ERROR: table "public.testpub_xs_part" cannot be both published and excluded +DETAIL: It is a partition of "pub_test.testpub_xs_parted", which is named in the EXCEPT clause of schema "pub_test", and its own schema "public" is published in full. +HINT: Either do not publish schema "public", or do not name "pub_test.testpub_xs_parted" in the EXCEPT clause. +DROP PUBLICATION testpub_xs; DROP TABLE testpub_xs_child, pub_test.testpub_xs_parent; DROP TABLE testpub_xs_part, pub_test.testpub_xs_parted; --------------------------------------------- @@ -844,6 +903,115 @@ Except tables: "pub_test.testpub_tbl_s1" "pub_test.testpub_tbl_s2" +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s2" + +-- fail: table in EXCEPT clause also appears in the explicit table list +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot be both published and excluded +-- fail: explicit partition + EXCEPT-ed root, given in a single SET statement +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_part_s, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ERROR: partition "pub_test.testpub_part_s" cannot be both published and excluded +DETAIL: Partition root "pub_test.testpub_parted_s" is named in the publication's EXCEPT clause for schema "pub_test". +-- fail: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 1: ...xcept SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.tes... + ^ +-- SET: unqualified name in EXCEPT is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- SET without EXCEPT clears the existing except list +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + +-- SET to a different schema removes old schema's EXCEPT entries +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA public; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "public" + +-- fail: nonexistent table in EXCEPT clause (SET path) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- SET: multiple schemas each with their own EXCEPT clause +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- fail: ALTER PUBLICATION ... DROP TABLE on an excluded table is rejected +-- with an EXCEPT-specific error. +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_tbl_s1; +ERROR: cannot drop table "pub_test.testpub_tbl_s1" from publication "testpub_alter_except" +DETAIL: The table is currently named in an EXCEPT clause of the publication. +HINT: Change the EXCEPT clause using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT. +-- the EXCEPT entry is still present after the rejected DROP TABLE +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- fail: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +ERROR: EXCEPT clause is not supported with DROP in ALTER PUBLICATION +-- DROP TABLES IN SCHEMA removes associated EXCEPT entries +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + Publication testpub_alter_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "public" +Except tables: + "public.testpub_tbl1" + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index 913f7de3a19..28fa7abc7d5 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -383,6 +383,28 @@ CREATE PUBLICATION testpub_inh TABLES IN SCHEMA public EXCEPT (TABLE testpub_inh_child); \dRp+ testpub_inh DROP PUBLICATION testpub_inh; + +-- SET replaces the EXCEPT list rather than adding to it, so an entry the +-- publication currently holds cannot excuse a conflict: it may be one that this +-- same statement drops. +CREATE PUBLICATION testpub_inh + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_inh_parent), + TABLES IN SCHEMA public EXCEPT (TABLE testpub_inh_child); +-- fail: dropping public's EXCEPT clause would leave testpub_inh_child published +-- while pub_test's clause still covers it +ALTER PUBLICATION testpub_inh + SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_inh_parent), + TABLES IN SCHEMA public; +-- ok: the new EXCEPT list still excludes it, so both clauses agree +ALTER PUBLICATION testpub_inh + SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_inh_parent), + TABLES IN SCHEMA public EXCEPT (TABLE testpub_inh_child); +\dRp+ testpub_inh +-- ok: public is no longer published, so nothing is both published and excluded +ALTER PUBLICATION testpub_inh + SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_inh_parent); +\dRp+ testpub_inh +DROP PUBLICATION testpub_inh; DROP TABLE testpub_inh_child, pub_test.testpub_inh_sibling, pub_test.testpub_inh_parent; -- The reverse order must be rejected too: excluding a root or parent first and @@ -410,6 +432,17 @@ CREATE PUBLICATION testpub_xs FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE ONLY pub_test.testpub_xs_parent); ALTER PUBLICATION testpub_xs ADD TABLES IN SCHEMA public; DROP PUBLICATION testpub_xs; + +-- SET runs the same conflict checks. Unlike ADD it replaces the EXCEPT list, +-- so an exclusion the publication already holds is not carried over and cannot +-- conflict with anything; only what the statement itself names can. +CREATE PUBLICATION testpub_xs + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_xs_parted); +-- fail: public holds a partition of the root this statement excludes +ALTER PUBLICATION testpub_xs + SET TABLES IN SCHEMA public, pub_test + EXCEPT (TABLE pub_test.testpub_xs_parted); +DROP PUBLICATION testpub_xs; DROP TABLE testpub_xs_child, pub_test.testpub_xs_parent; DROP TABLE testpub_xs_part, pub_test.testpub_xs_parted; @@ -457,6 +490,53 @@ ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_parted_s; ALTER PUBLICATION testpub_alter_except ADD TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1, testpub_tbl_s2); \dRp+ testpub_alter_except +-- SET: replace the except list (keep same schema, different except table) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_alter_except + +-- fail: table in EXCEPT clause also appears in the explicit table list +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: explicit partition + EXCEPT-ed root, given in a single SET statement +ALTER PUBLICATION testpub_alter_except SET TABLE pub_test.testpub_part_s, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); + +-- fail: except table's schema (public) not in the publication's schema list (pub_test) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- SET: unqualified name in EXCEPT is implicitly qualified with the schema +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +\dRp+ testpub_alter_except + +-- SET without EXCEPT clears the existing except list +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + +-- SET to a different schema removes old schema's EXCEPT entries +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_tbl_s1); +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA public; +\dRp+ testpub_alter_except + +-- fail: nonexistent table in EXCEPT clause (SET path) +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- SET: multiple schemas each with their own EXCEPT clause +ALTER PUBLICATION testpub_alter_except SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_alter_except + +-- fail: ALTER PUBLICATION ... DROP TABLE on an excluded table is rejected +-- with an EXCEPT-specific error. +ALTER PUBLICATION testpub_alter_except DROP TABLE pub_test.testpub_tbl_s1; +-- the EXCEPT entry is still present after the rejected DROP TABLE +\dRp+ testpub_alter_except + +-- fail: EXCEPT is not allowed with DROP +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); + +-- DROP TABLES IN SCHEMA removes associated EXCEPT entries +ALTER PUBLICATION testpub_alter_except DROP TABLES IN SCHEMA pub_test; +\dRp+ testpub_alter_except + -- Cleanup RESET client_min_messages; DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index e0650d685bc..80895e2d661 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -376,6 +376,61 @@ $result = is($result, qq(0), 'ALTER ... ADD TABLES IN SCHEMA EXCEPT: excluded table not synced'); +# SET: replace the except list; tab_excluded is now included and tab_published is excluded. +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_published)" +); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (7); + INSERT INTO sch1.tab_excluded VALUES (7); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded WHERE a = 7"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: newly included table is replicated' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published WHERE a = 7"); +is($result, qq(0), + 'ALTER ... SET TABLES IN SCHEMA EXCEPT: now-excluded table is not replicated' +); + +# SET without EXCEPT: clears the except list; both tables are now published. +$node_publisher->safe_psql('postgres', + "ALTER PUBLICATION sch_pub SET TABLES IN SCHEMA sch1"); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sch_sub REFRESH PUBLICATION"); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (8); + INSERT INTO sch1.tab_excluded VALUES (8); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published WHERE a = 8"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_published replicated after except list cleared' +); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded WHERE a = 8"); +is($result, qq(1), + 'ALTER ... SET TABLES IN SCHEMA (no EXCEPT): tab_excluded replicated after except list cleared' +); + $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); @@ -573,6 +628,36 @@ $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub_sch_without_exc $node_publisher->safe_psql('postgres', 'DROP SCHEMA msch CASCADE'); $node_subscriber->safe_psql('postgres', 'DROP SCHEMA msch CASCADE'); +# OK when a table is excluded by a TABLES IN SCHEMA EXCEPT publication, +# but is included by another publication. +$node_publisher->safe_psql('postgres', 'TRUNCATE tab1'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE tab1'); + +$node_publisher->safe_psql( + 'postgres', qq( + CREATE PUBLICATION tap_pub1 FOR TABLES IN SCHEMA public EXCEPT (TABLE public.tab1); + CREATE PUBLICATION tap_pub2 FOR TABLE tab1; + INSERT INTO tab1 VALUES(1); +)); +$node_subscriber->psql('postgres', + "CREATE SUBSCRIPTION tap_sub CONNECTION '$publisher_connstr' PUBLICATION tap_pub1, tap_pub2" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'tap_sub'); + +$node_publisher->safe_psql('postgres', qq(INSERT INTO tab1 VALUES(2))); +$node_publisher->wait_for_catchup('tap_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT * FROM tab1 ORDER BY a"); +is( $result, qq(1 +2), + "TABLES IN SCHEMA EXCEPT: table excluded in schema pub but included by another pub is replicated" +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); + $node_publisher->stop('fast'); done_testing(); -- 2.55.0
v28-0001-Support-EXCEPT-clause-for-schema-level-publicati.patch (application/octet-stream, 110.3K) download From 6c5965788c0fbe182943f6185650ce16b546375d Mon Sep 17 00:00:00 2001 From: Vignesh C <c_vigneshwaran@apple.com> Date: Tue, 18 Aug 2026 08:51:08 +0530 Subject: [PATCH v28 1/4] Support EXCEPT clause for schema-level publications Extend table exclusion support in publications to allow specific tables to be excluded from schema-level publications using an EXCEPT clause in CREATE PUBLICATION. Supported syntax: CREATE PUBLICATION pub FOR TABLES IN SCHEMA s EXCEPT (TABLE t1,...); This reuses the existing opt_pub_except_clause grammar and stores excluded tables as pg_publication_rel entries with prexcept = true, requiring no catalog changes. NOTES - Each EXCEPT clause applies only to its own schema; cross-schema references are rejected. - A schema may appear only once with an EXCEPT clause. - A table cannot be both explicitly published and excluded in the same statement. - Only partition roots may be excluded. Excluding a root excludes the entire partition tree, including partitions in other published schemas. Individual partitions cannot be added while their root is excluded, and ATTACH PARTITION is rejected if the attached table is excluded. - ALTER TABLE ... SET SCHEMA removes schema-scoped exclusions, matching existing schema-publication behavior. - psql describe output and tab completion are updated to support the new syntax. --- src/backend/catalog/pg_publication.c | 274 ++++++++++-- src/backend/commands/publicationcmds.c | 455 +++++++++++++++++++- src/backend/commands/tablecmds.c | 24 +- src/backend/parser/gram.y | 27 +- src/backend/replication/pgoutput/pgoutput.c | 37 +- src/backend/utils/cache/relcache.c | 26 +- src/bin/psql/describe.c | 44 +- src/bin/psql/tab-complete.in.c | 35 +- src/include/catalog/pg_publication.h | 3 + src/include/commands/publicationcmds.h | 2 + src/include/nodes/parsenodes.h | 5 + src/test/regress/expected/publication.out | 391 ++++++++++++++++- src/test/regress/sql/publication.sql | 241 ++++++++++- src/test/subscription/t/037_except.pl | 263 ++++++++++- 14 files changed, 1731 insertions(+), 96 deletions(-) diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index 12af7d15536..81e4166cfee 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -54,7 +54,7 @@ typedef struct * error if not. */ static void -check_publication_add_relation(PublicationRelInfo *pri) +check_publication_add_relation(PublicationRelInfo *pri, Oid pubid) { Relation targetrel = pri->relation; const char *relname; @@ -71,12 +71,51 @@ check_publication_add_relation(PublicationRelInfo *pri) errormsg = gettext_noop("cannot add relation \"%s\" to publication"); } - /* If in EXCEPT clause, must be root partitioned table */ - if (pri->except && targetrel->rd_rel->relispartition) - ereport(ERROR, - (errcode(ERRCODE_INVALID_PARAMETER_VALUE), - errmsg(errormsg, relname), - errdetail("This operation is not supported for individual partitions."))); + /* + * A partition cannot be added to a publication if its partition root is + * excluded by the publication. We follow the rule that excluding a + * partition root means that the entire partition tree is excluded. Thus, + * check whether the root is in the EXCEPT clause and reject adding the + * individual partition to the publication. + */ + if (targetrel->rd_rel->relispartition) + { + List *ancestors; + + if (pri->except) + { + /* If in EXCEPT clause, must be root partitioned table */ + ereport(ERROR, + (errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg(errormsg, relname), + errdetail("This operation is not supported for individual partitions."))); + } + + /* + * ancestors is NIL for a partition with a pending DETACH + * CONCURRENTLY, in which case there is no root to check. + */ + ancestors = get_partition_ancestors(RelationGetRelid(targetrel)); + if (ancestors != NIL) + { + Oid root = llast_oid(ancestors); + bool root_except; + + if (CheckPublicationRelEntry(pubid, root, &root_except) && root_except) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("cannot add partition \"%s\" to publication \"%s\"", + RelationGetQualifiedRelationName(targetrel), + get_publication_name(pubid, false)), + errdetail("Partition root \"%s\" is named in the publication's EXCEPT clause for schema \"%s\".", + quote_qualified_identifier(get_namespace_name(get_rel_namespace(root)), + get_rel_name(root)), + get_namespace_name(get_rel_namespace(root))), + errhint("Change the EXCEPT clause using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT.")); + } + + list_free(ancestors); + } /* Must be a regular or partitioned table */ if (RelationGetForm(targetrel)->relkind != RELKIND_RELATION && @@ -320,8 +359,7 @@ is_schema_publication(Oid pubid) } /* - * Returns true if the publication has explicitly included relation (i.e., - * not marked as EXCEPT). + * Returns true if the publication has a FOR TABLE clause. */ bool is_table_publication(Oid pubid) @@ -341,19 +379,23 @@ is_table_publication(Oid pubid) scan = systable_beginscan(pubrelsrel, PublicationRelPrpubidIndexId, true, NULL, 1, &scankey); - tup = systable_getnext(scan); - if (HeapTupleIsValid(tup)) - { - Form_pg_publication_rel pubrel; - - pubrel = (Form_pg_publication_rel) GETSTRUCT(tup); - /* - * For any publication, pg_publication_rel contains either only EXCEPT - * entries or only explicitly included tables. Therefore, examining - * the first tuple is sufficient to determine table inclusion. - */ - result = !pubrel->prexcept; + /* + * A publication can have both explicitly included (prexcept = false) and + * EXCEPT (prexcept = true) rows for the same pubid. For example: + * + * CREATE PUBLICATION pub1 FOR TABLE s1.t1, TABLES IN SCHEMA s2 EXCEPT + * (TABLE s2.t1); + * + * Scan until we find an explicitly included row. + */ + while (HeapTupleIsValid(tup = systable_getnext(scan))) + { + if (!((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept) + { + result = true; + break; + } } systable_endscan(scan); @@ -362,6 +404,27 @@ is_table_publication(Oid pubid) return result; } +/* + * Check whether a pg_publication_rel row exists for (pubid, relid); if so, + * set *is_except to its prexcept flag. + */ +bool +CheckPublicationRelEntry(Oid pubid, Oid relid, bool *is_except) +{ + HeapTuple tup; + + tup = SearchSysCache2(PUBLICATIONRELMAP, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (!HeapTupleIsValid(tup)) + return false; + + *is_except = ((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept; + ReleaseSysCache(tup); + + return true; +} + /* * Returns true if the relation has column list associated with the * publication, false otherwise. @@ -457,11 +520,26 @@ GetPubPartitionOptionRelations(List *result, PublicationPartOpt pub_partopt, * ancestor is at the end of the list. */ Oid -GetTopMostAncestorInPublication(Oid puboid, List *ancestors, int *ancestor_level) +GetTopMostAncestorInPublication(Oid puboid, List *ancestors, + int *ancestor_level) { ListCell *lc; Oid topmost_relid = InvalidOid; int level = 0; + bool root_except; + + if (ancestors == NIL) + return InvalidOid; + + /* + * If the partition root is excluded from this publication via an EXCEPT + * clause, the partition is not published through this publication, so + * return InvalidOid. Since only partition roots can appear in an EXCEPT + * clause, the root is the only ancestor worth a catalog lookup. + */ + if (CheckPublicationRelEntry(puboid, llast_oid(ancestors), &root_except) && + root_except) + return InvalidOid; /* * Find the "topmost" ancestor that is in this publication. @@ -548,6 +626,7 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, List *relids = NIL; int i; bool inval_except_table; + bool is_except; rel = table_open(PublicationRelRelationId, RowExclusiveLock); @@ -556,21 +635,46 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, * duplicates, it's here just to provide nicer error message in common * case. The real protection is the unique key on the catalog. */ - if (SearchSysCacheExists2(PUBLICATIONRELMAP, ObjectIdGetDatum(relid), - ObjectIdGetDatum(pubid))) + if (CheckPublicationRelEntry(pubid, relid, &is_except)) { table_close(rel, RowExclusiveLock); - if (if_not_exists) + /* + * if_not_exists asks us to skip an entry that is already present. An + * existing entry of the opposite kind is not the entry the caller + * asked for, though: skipping it would silently leave the relation + * excluded when the caller wanted it published, or published when the + * caller wanted it excluded. So only skip when the existing entry is + * of the same kind, and report the conflict otherwise. + */ + if (if_not_exists && is_except == pri->except) return InvalidObjectAddress; - ereport(ERROR, - (errcode(ERRCODE_DUPLICATE_OBJECT), - errmsg("relation \"%s\" is already a member of publication \"%s\"", - RelationGetRelationName(targetrel), pub->name))); + if (is_except) + ereport(ERROR, + (errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("cannot add table \"%s\" to publication \"%s\"", + RelationGetQualifiedRelationName(targetrel), + pub->name), + errdetail("The table is named in the publication's EXCEPT clause for schema \"%s\".", + get_namespace_name(RelationGetNamespace(targetrel))), + errhint("Change the EXCEPT clause using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT."))); + else if (pri->except) + ereport(ERROR, + (errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("cannot exclude table \"%s\" from publication \"%s\"", + RelationGetQualifiedRelationName(targetrel), + pub->name), + errdetail("The table is a member of the publication."), + errhint("Remove the table from the publication using ALTER PUBLICATION ... DROP TABLE."))); + else + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("relation \"%s\" is already a member of publication \"%s\"", + RelationGetRelationName(targetrel), pub->name))); } - check_publication_add_relation(pri); + check_publication_add_relation(pri, pubid); /* Validate and translate column names into a Bitmapset of attnums. */ attnums = pub_collist_validate(pri->relation, pri->columns); @@ -996,16 +1100,36 @@ GetIncludedPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) * Gets list of table oids that were specified in the EXCEPT clause for a * publication. * - * This should only be used FOR ALL TABLES publications. + * This is used for FOR ALL TABLES and FOR TABLES IN SCHEMA publications, + * both of which support EXCEPT TABLE. */ List * GetExcludedPublicationTables(Oid pubid, PublicationPartOpt pub_partopt) { - Assert(GetPublication(pubid)->alltables); + Assert(GetPublication(pubid)->alltables || is_schema_publication(pubid)); return get_publication_relations(pubid, pub_partopt, true); } +/* + * Gets list of relation oids associated with a publication, covering both + * explicitly included relations and relations named in an EXCEPT clause. + * + * This is used by ALTER PUBLICATION ... SET to replaces a publication's entire + * relation list. + */ +List * +GetPublicationRelationsOfAnyKind(Oid pubid, PublicationPartOpt pub_partopt) +{ + List *result; + + result = get_publication_relations(pubid, pub_partopt, false); + + return list_concat_unique_oid(result, + get_publication_relations(pubid, pub_partopt, + true)); +} + /* * Gets list of publication oids for publications marked as FOR ALL TABLES. */ @@ -1246,22 +1370,63 @@ GetSchemaPublicationRelations(Oid schemaid, PublicationPartOpt pub_partopt) /* * Gets the list of all relations published by FOR TABLES IN SCHEMA - * publication. + * publication, excluding any tables listed in EXCEPT clauses. */ List * GetAllSchemaPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) { List *result = NIL; List *pubschemalist = GetPublicationSchemas(pubid); + List *except_relids = NIL; ListCell *cell; + /* get the list of tables excluded via EXCEPT TABLE for this publication */ + if (pubschemalist != NIL) + except_relids = GetExcludedPublicationTables(pubid, pub_partopt); + foreach(cell, pubschemalist) { Oid schemaid = lfirst_oid(cell); List *schemaRels = NIL; schemaRels = GetSchemaPublicationRelations(schemaid, pub_partopt); - result = list_concat(result, schemaRels); + + if (except_relids != NIL) + { + /* filter out any tables that appear in the EXCEPT list */ + foreach_oid(relid, schemaRels) + { + bool excluded = list_member_oid(except_relids, relid); + + /* + * A partition whose root is excluded from the publication is + * also excluded, even if the partition itself lives in a + * different (included) schema. Only the topmost root of a + * partition hierarchy can ever appear in EXCEPT (see + * check_publication_add_relation()), so it's enough to check + * the last element of the ancestors list, rather than walking + * the whole chain. + */ + if (!excluded && get_rel_relispartition(relid)) + { + List *ancestors = get_partition_ancestors(relid); + + if (ancestors != NIL) + { + excluded = list_member_oid(except_relids, + llast_oid(ancestors)); + list_free(ancestors); + } + } + + if (!excluded) + result = lappend_oid(result, relid); + } + + list_free(schemaRels); + } + else + result = list_concat(result, schemaRels); } return result; @@ -1338,6 +1503,7 @@ is_table_publishable_in_publication(Oid relid, Publication *pub) { bool relispartition; List *ancestors = NIL; + bool is_except; /* * For non-pubviaroot publications, a partitioned table is never the @@ -1385,6 +1551,10 @@ is_table_publishable_in_publication(Oid relid, Publication *pub) */ /* + * If the partition root is excluded via the EXCEPT clause, the partition + * is never considered to be published through this publication. Check + * this before checking whether an ancestor is published. + * * If an ancestor is published, the partition's status depends on * publish_via_partition_root value. * @@ -1394,20 +1564,38 @@ is_table_publishable_in_publication(Oid relid, Publication *pub) * If it's false, the partition is covered by its ancestor's presence in * the publication, it should be included (return true). */ - if (relispartition && - OidIsValid(GetTopMostAncestorInPublication(pub->oid, ancestors, NULL))) - return !pub->pubviaroot; + if (relispartition) + { + /* + * ancestors can be NIL for a partition whose DETACH ... CONCURRENTLY + * is pending, in which case there is no ancestor to check. + */ + if (ancestors != NIL && + CheckPublicationRelEntry(pub->oid, llast_oid(ancestors), &is_except) && + is_except) + return false; + + if (OidIsValid(GetTopMostAncestorInPublication(pub->oid, ancestors, NULL))) + return !pub->pubviaroot; + } /* * Check whether the table is explicitly published via pg_publication_rel * or pg_publication_namespace. + * + * A pg_publication_rel row with prexcept=true means the table is + * explicitly excluded via EXCEPT and must not be reported as published, + * even if its schema is otherwise included. A row with prexcept=false + * means it is explicitly included. If no pg_publication_rel row exists, + * the table is published iff its schema appears in + * pg_publication_namespace. */ - return (SearchSysCacheExists2(PUBLICATIONRELMAP, - ObjectIdGetDatum(relid), - ObjectIdGetDatum(pub->oid)) || - SearchSysCacheExists2(PUBLICATIONNAMESPACEMAP, - ObjectIdGetDatum(get_rel_namespace(relid)), - ObjectIdGetDatum(pub->oid))); + if (CheckPublicationRelEntry(pub->oid, relid, &is_except)) + return !is_except; + else + return SearchSysCacheExists2(PUBLICATIONNAMESPACEMAP, + ObjectIdGetDatum(get_rel_namespace(relid)), + ObjectIdGetDatum(pub->oid)); } /* diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 96838730fe1..a46c072801b 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -22,6 +22,7 @@ #include "catalog/namespace.h" #include "catalog/objectaccess.h" #include "catalog/objectaddress.h" +#include "catalog/partition.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" #include "catalog/pg_namespace.h" @@ -61,7 +62,7 @@ typedef struct rf_context Oid parentid; /* relid of the parent relation */ } rf_context; -static List *OpenTableList(List *tables); +static List *OpenTableList(List *tables, List **cross_schema_children); static void CloseTableList(List *rels); static void LockSchemaList(List *schemalist); static void PublicationAddTables(Oid pubid, List *rels, bool if_not_exists, @@ -71,6 +72,18 @@ static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); static char defGetGeneratedColsOption(DefElem *def); +static void CheckExceptNotInTableList(List *except_rels, + List *cross_schema_children, + List *explicitrelids); +static void CheckExceptChildNotInSchemaList(List *cross_schema_children, + List *schemaidlist, + List *except_rels); +static void CheckExceptPartitionNotInSchemaList(List *except_rels, + List *schemaidlist); +static void ProcessSchemaExceptTables(Oid schemaid, List *except_tables, + ParseState *pstate, List **schemas, + List **schemas_with_except, + List **except_pubtables); static void @@ -175,16 +188,93 @@ parse_publication_options(ParseState *pstate, } } +/* + * Reject a schema being mentioned more than once with an EXCEPT clause, even + * if the EXCEPT clauses are identical — much like OpenTableList() rejects + * "FOR TABLE t1(a), t1(a)" despite the column lists matching. A schema can + * still be mentioned multiple times, just not more than once with EXCEPT. + * + * Also qualify unqualified EXCEPT table names with the given schema (rejecting + * any explicitly qualified with a different schema), and append them to + * *except_pubtables. + * + * schemaid: OID of the schema for this TABLES IN SCHEMA mention. + * except_tables: the EXCEPT list (or NIL) attached to this mention. + * pstate: parse state of the statement, used to report the error position of + * an offending EXCEPT entry. + * *schemas: accumulates all schema OIDs seen so far in this statement. + * *schemas_with_except: This is a subset of *schemas. Tracks which of + * the seen schemas of this statement had an EXCEPT clause. + * *except_pubtables: accumulates the (now schema-qualified) EXCEPT table + * entries across the whole statement. + */ +static void +ProcessSchemaExceptTables(Oid schemaid, List *except_tables, + ParseState *pstate, List **schemas, + List **schemas_with_except, List **except_pubtables) +{ + char *schema_name = get_namespace_name(schemaid); + bool schema_has_except = (except_tables != NIL); + + /* + * A repeating schema is only a problem if this mention has EXCEPT, or an + * earlier mention of the same schema did. + */ + if (list_member_oid(*schemas, schemaid)) + { + if (schema_has_except || + list_member_oid(*schemas_with_except, schemaid)) + ereport(ERROR, + errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("conflicting or redundant EXCEPT clauses for schema \"%s\"", + schema_name)); + } + + if (schema_has_except) + *schemas_with_except = lappend_oid(*schemas_with_except, schemaid); + + /* Filter out duplicates if the user specifies "sch1, sch1" */ + *schemas = list_append_unique_oid(*schemas, schemaid); + + if (!schema_has_except) + return; + + foreach_ptr(PublicationObjSpec, eobj, except_tables) + { + RangeVar *relation = eobj->pubtable->relation; + + if (relation->schemaname == NULL) + relation->schemaname = schema_name; + else if (strcmp(relation->schemaname, schema_name) != 0) + ereport(ERROR, + errcode(ERRCODE_INVALID_OBJECT_DEFINITION), + errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", + quote_qualified_identifier(relation->schemaname, relation->relname), + schema_name), + parser_errposition(pstate, eobj->location)); + + /* + * Remember that this EXCEPT entry is associated with a schema. This + * is used by OpenTableList() to skip inheritance children outside + * that schema. + */ + eobj->pubtable->except_in_schema = true; + + *except_pubtables = lappend(*except_pubtables, eobj->pubtable); + } +} + /* * Convert the PublicationObjSpecType list into schema oid list and * PublicationTable list. */ static void ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, - List **rels, List **exceptrels, List **schemas) + List **rels, List **except_pubtables, List **schemas) { ListCell *cell; PublicationObjSpec *pubobj; + List *schemas_with_except = NIL; if (!pubobjspec_list) return; @@ -200,7 +290,7 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, { case PUBLICATIONOBJ_EXCEPT_TABLE: pubobj->pubtable->except = true; - *exceptrels = lappend(*exceptrels, pubobj->pubtable); + *except_pubtables = lappend(*except_pubtables, pubobj->pubtable); break; case PUBLICATIONOBJ_TABLE: pubobj->pubtable->except = false; @@ -209,8 +299,10 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, case PUBLICATIONOBJ_TABLES_IN_SCHEMA: schemaid = get_namespace_oid(pubobj->name, false); - /* Filter out duplicates if user specifies "sch1, sch1" */ - *schemas = list_append_unique_oid(*schemas, schemaid); + ProcessSchemaExceptTables(schemaid, pubobj->except_tables, + pstate, schemas, + &schemas_with_except, + except_pubtables); break; case PUBLICATIONOBJ_TABLES_IN_CUR_SCHEMA: search_path = fetch_search_path(false); @@ -222,8 +314,10 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, schemaid = linitial_oid(search_path); list_free(search_path); - /* Filter out duplicates if user specifies "sch1, sch1" */ - *schemas = list_append_unique_oid(*schemas, schemaid); + ProcessSchemaExceptTables(schemaid, pubobj->except_tables, + pstate, schemas, + &schemas_with_except, + except_pubtables); break; default: /* shouldn't happen */ @@ -770,6 +864,195 @@ TransformPubWhereClauses(List *tables, const char *queryString, } } +/* + * Check that a table is not both excluded and published in the same DDL. + * + * Similar checks are present in publication_add_relation() and + * check_publication_add_relation(), but they rely on pg_publication_rel + * entries and ancestor lookups. Here, the checks are performed on the + * object lists collected during the statement, as the catalog state is + * not sufficient in the cases below: + * + * - CreatePublication() inserts the explicit tables and the EXCEPT tables in + * a single command, but rows inserted by the current command are not + * visible to later lookups within the same command. + * + * - For partitions, the excluded root's row might not yet exist because the + * root may be added to the EXCEPT list later. Detecting such contradictions + * when adding the root to the EXCEPT clause would require traversing + * downward through the partition hierarchy, whereas the existing ancestor + * lookups only traverse upward from the relation being added. + */ +static void +CheckExceptNotInTableList(List *except_rels, List *cross_schema_children, + List *explicitrelids) +{ + foreach_oid(explicitrelid, explicitrelids) + { + Oid root = InvalidOid; + + if (get_rel_relispartition(explicitrelid)) + { + List *ancestors = get_partition_ancestors(explicitrelid); + + /* + * ancestors is NIL for a partition with a pending DETACH + * CONCURRENTLY. + */ + if (ancestors != NIL) + root = llast_oid(ancestors); + list_free(ancestors); + } + + foreach_ptr(PublicationRelInfo, pri, except_rels) + { + Oid exceptrelid = RelationGetRelid(pri->relation); + + if (exceptrelid == explicitrelid) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" cannot be both published and excluded", + RelationGetQualifiedRelationName(pri->relation))); + + if (OidIsValid(root) && exceptrelid == root) + ereport(ERROR, + (errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("partition \"%s\" cannot be both published and excluded", + quote_qualified_identifier(get_namespace_name(get_rel_namespace(explicitrelid)), + get_rel_name(explicitrelid))), + errdetail("Partition root \"%s\" is named in the publication's EXCEPT clause for schema \"%s\".", + RelationGetQualifiedRelationName(pri->relation), + get_namespace_name(RelationGetNamespace(pri->relation))))); + } + + /* + * An EXCEPT clause also applies to inheritance children of a parent + * named without ONLY. Children in other schemas are not added to + * except_rels, but are still excluded by the EXCEPT clause. + * Explicitly publishing such a child therefore conflicts with the + * EXCEPT clause. + */ + if (list_member_oid(cross_schema_children, explicitrelid)) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" cannot be both published and excluded", + quote_qualified_identifier(get_namespace_name(get_rel_namespace(explicitrelid)), + get_rel_name(explicitrelid))), + errdetail("It inherits from a table named in an EXCEPT clause of this statement."), + errhint("Use ONLY in the EXCEPT clause to exclude just the parent, or do not publish this table explicitly.")); + } +} + +/* + * Check that an EXCEPT clause does not conflict with a TABLES IN SCHEMA + * clause in the same statement. + * + * cross_schema_children contains inheritance children excluded through a + * parent in another schema. If such a child is also included through a + * TABLES IN SCHEMA clause in the same statement, report the conflict. + * + * If the child's schema also has an EXCEPT clause specified through TABLES + * IN SCHEMA, there is no conflict, since both clauses exclude the child. + * + * Conflicts with explicitly listed tables are handled by + * CheckExceptNotInTableList(). + */ +static void +CheckExceptChildNotInSchemaList(List *cross_schema_children, List *schemaidlist, + List *except_rels) +{ + foreach_oid(childrelid, cross_schema_children) + { + Oid childnsp = get_rel_namespace(childrelid); + bool excluded = false; + + if (!list_member_oid(schemaidlist, childnsp)) + continue; + + foreach_ptr(PublicationRelInfo, pri, except_rels) + { + if (RelationGetRelid(pri->relation) == childrelid) + { + excluded = true; + break; + } + } + + if (excluded) + continue; + + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" cannot be both published and excluded", + quote_qualified_identifier(get_namespace_name(childnsp), + get_rel_name(childrelid))), + errdetail("It inherits from a table named in the EXCEPT clause of another schema, and its own schema \"%s\" is published in full.", + get_namespace_name(childnsp)), + errhint("Use ONLY in the EXCEPT clause to exclude just the parent, or name this table in the EXCEPT clause of schema \"%s\".", + get_namespace_name(childnsp))); + } +} + +/* + * Check that an EXCEPT clause naming a partitioned table does not conflict with + * a schema included by the same statement. + * + * Excluding a partitioned table excludes its whole partition tree, but that + * reach stops at the schema the EXCEPT clause belongs to: a partition in another + * schema is not covered, just as an inheritance child in another schema is not. + * If the statement also includes that partition's schema, the two clauses + * disagree about the partition, and there is no way to spell the intended + * result, since a partition can never be named in an EXCEPT clause itself. + * Report the conflict. + * + * Partitions in the same schema as the excluded table are covered by the + * EXCEPT clause and are not a conflict. + */ +static void +CheckExceptPartitionNotInSchemaList(List *except_rels, List *schemaidlist) +{ + foreach_ptr(PublicationRelInfo, pri, except_rels) + { + Oid rootrelid = RelationGetRelid(pri->relation); + Oid rootnsp = RelationGetNamespace(pri->relation); + List *parts; + + if (pri->relation->rd_rel->relkind != RELKIND_PARTITIONED_TABLE) + continue; + + /* + * No lock is taken on the partitions; the same is true of + * GetPubPartitionOptionRelations(), which walks the tree for the + * relcache invalidations that follow. + */ + parts = find_all_inheritors(rootrelid, NoLock, NULL); + + foreach_oid(partrelid, parts) + { + Oid partnsp = get_rel_namespace(partrelid); + + if (partnsp == rootnsp || !list_member_oid(schemaidlist, partnsp)) + continue; + + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" cannot be both published and excluded", + quote_qualified_identifier(get_namespace_name(partnsp), + get_rel_name(partrelid))), + errdetail("It is a partition of \"%s\", which is named in the EXCEPT clause of schema \"%s\", and its own schema \"%s\" is published in full.", + quote_qualified_identifier(get_namespace_name(rootnsp), + get_rel_name(rootrelid)), + get_namespace_name(rootnsp), + get_namespace_name(partnsp)), + errhint("Either do not publish schema \"%s\", or do not name \"%s\" in the EXCEPT clause.", + get_namespace_name(partnsp), + quote_qualified_identifier(get_namespace_name(rootnsp), + get_rel_name(rootrelid)))); + } + + list_free(parts); + } +} /* * Given a list of tables that are going to be added to a publication, @@ -849,7 +1132,7 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) char publish_generated_columns; AclResult aclresult; List *relations = NIL; - List *exceptrelations = NIL; + List *except_pubtables = NIL; List *schemaidlist = NIL; /* must have CREATE privilege on database */ @@ -936,16 +1219,16 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) /* Associate objects with the publication. */ ObjectsInPublicationToOids(stmt->pubobjects, pstate, &relations, - &exceptrelations, &schemaidlist); + &except_pubtables, &schemaidlist); if (stmt->for_all_tables) { /* Process EXCEPT table list */ - if (exceptrelations != NIL) + if (except_pubtables != NIL) { List *rels; - rels = OpenTableList(exceptrelations); + rels = OpenTableList(except_pubtables, NULL); PublicationAddTables(puboid, rels, true, NULL); CloseTableList(rels); } @@ -959,6 +1242,11 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) } else if (!stmt->for_all_sequences) { + List *explicitrelids = NIL; + + /* EXCEPT tables here always belong to a schema in schemaidlist */ + Assert(except_pubtables == NIL || schemaidlist != NIL); + /* FOR TABLES IN SCHEMA requires superuser */ if (schemaidlist != NIL && !superuser()) ereport(ERROR, @@ -969,7 +1257,7 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) { List *rels; - rels = OpenTableList(relations); + rels = OpenTableList(relations, NULL); TransformPubWhereClauses(rels, pstate->p_sourcetext, publish_via_partition_root); @@ -978,6 +1266,20 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) publish_via_partition_root); PublicationAddTables(puboid, rels, true, NULL); + + /* + * Collect explicit table OIDs now, before we close the relation + * list, so that the except-table validation for pub-included + * schemas below can check for contradictions without relying on a + * catalog scan that might not yet see the just-inserted rows. + */ + if (except_pubtables != NIL) + { + foreach_ptr(PublicationRelInfo, pri, rels) + explicitrelids = lappend_oid(explicitrelids, + RelationGetRelid(pri->relation)); + } + CloseTableList(rels); } @@ -989,6 +1291,38 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) */ LockSchemaList(schemaidlist); PublicationAddSchemas(puboid, schemaidlist, true, NULL); + + if (except_pubtables != NIL) + { + List *except_rels; + List *cross_schema_children = NIL; + + except_rels = OpenTableList(except_pubtables, + &cross_schema_children); + + /* + * Validate that a table is not both explicitly included and + * excluded by the schema's EXCEPT clause. + */ + CheckExceptNotInTableList(except_rels, cross_schema_children, + explicitrelids); + + /* + * Validate that an inheritance child is not both excluded by + * an EXCEPT clause and included by its schema. + */ + CheckExceptChildNotInSchemaList(cross_schema_children, + schemaidlist, except_rels); + + /* + * Validate that a partition is not both excluded through its + * root by an EXCEPT clause and included by its own schema. + */ + CheckExceptPartitionNotInSchemaList(except_rels, schemaidlist); + + PublicationAddTables(puboid, except_rels, false, NULL); + CloseTableList(except_rels); + } } } @@ -1255,7 +1589,7 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, if (!tables && stmt->action != AP_SetObjects) return; - rels = OpenTableList(tables); + rels = OpenTableList(tables, NULL); if (stmt->action == AP_AddObjects) { @@ -1295,8 +1629,15 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, } else { - oldrelids = GetIncludedPublicationRelations(pubid, - PUBLICATION_PART_ROOT); + /* + * SET replaces the publication's whole relation list, so every + * existing entry has to be reconciled against the new one -- an + * EXCEPT entry included. If the same relation is now requested + * with the opposite kind, the old entry is dropped below and the + * new one added, rather than the old one being silently kept. + */ + oldrelids = GetPublicationRelationsOfAnyKind(pubid, + PUBLICATION_PART_ROOT); TransformPubWhereClauses(rels, queryString, pubform->pubviaroot); @@ -1317,6 +1658,7 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, HeapTuple rftuple; Node *oldrelwhereclause = NULL; Bitmapset *oldcolumns = NULL; + bool oldexcept = false; /* look up the cache for the old relmap */ rftuple = SearchSysCache2(PUBLICATIONRELMAP, @@ -1348,6 +1690,8 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, if (!isnull) oldcolumns = pub_collist_to_bitmapset(NULL, columnListDatum, NULL); + oldexcept = ((Form_pg_publication_rel) GETSTRUCT(rftuple))->prexcept; + ReleaseSysCache(rftuple); } @@ -1371,14 +1715,17 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, /* * Check if any of the new set of relations matches with the - * existing relations in the publication. Additionally, if the + * existing relations in the publication. An entry matches + * only if it is of the same kind, that is, both are ordinary + * members or both are EXCEPT entries. Additionally, if the * relation has an associated WHERE clause, check the WHERE * expressions also match. Same for the column list. Drop the * rest. */ if (newrelid == oldrelid) { - if (equal(oldrelwhereclause, newpubrel->whereClause) && + if (newpubrel->except == oldexcept && + equal(oldrelwhereclause, newpubrel->whereClause) && bms_equal(oldcolumns, newcolumns)) { found = true; @@ -1829,13 +2176,69 @@ RemovePublicationSchemaById(Oid psoid) table_close(rel, RowExclusiveLock); } +/* + * Remove any EXCEPT clause entries for a relation from schema publications. + * Called when a table changes schema (ALTER TABLE ... SET SCHEMA), so that + * a schema-scoped exclusion does not silently follow the table to its new + * schema. + */ +void +RemoveSchemaPubExceptForRel(Oid relid, Oid oldNspOid, Oid newNspOid) +{ + List *pubids; + + /* + * If the table is not actually moving to a different schema (no-op ALTER + * TABLE ... SET SCHEMA <current_schema>), there is nothing to do. + */ + if (oldNspOid == newNspOid) + return; + + pubids = GetRelationExcludedPublications(relid); + + foreach_oid(pubid, pubids) + { + Oid proid; + + /* + * This problem does not apply to FOR ALL TABLES publications, because + * their EXCEPT clause is publication-scoped, not schema-scoped: the + * exclusion should persist regardless of what schema the table is in. + */ + if (!is_schema_publication(pubid)) + continue; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddress obj; + + ObjectAddressSet(obj, PublicationRelRelationId, proid); + + ereport(DEBUG2, + errmsg_internal("auto-remove exclusion of table \"%s.%s\" from publication \"%s\": table moved to schema \"%s\"", + get_namespace_name(oldNspOid), + get_rel_name(relid), + get_publication_name(pubid, false), + get_namespace_name(newNspOid))); + + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + list_free(pubids); +} + /* * Open relations specified by a PublicationTable list. * The returned tables are locked in ShareUpdateExclusiveLock mode in order to * add them to a publication. */ static List * -OpenTableList(List *tables) +OpenTableList(List *tables, List **cross_schema_children) { List *relids = NIL; List *rels = NIL; @@ -1911,6 +2314,7 @@ OpenTableList(List *tables) { List *children; ListCell *child; + Oid parentnsp = RelationGetNamespace(rel); children = find_all_inheritors(myrelid, ShareUpdateExclusiveLock, NULL); @@ -1922,6 +2326,21 @@ OpenTableList(List *tables) /* Allow query cancel in case this takes a long time */ CHECK_FOR_INTERRUPTS(); + /* + * An EXCEPT clause also excludes inheritance children in + * other schemas. Keep track of such children separately so + * the caller can detect if the same statement also includes + * them through another table or schema clause. + */ + if (t->except_in_schema && + get_rel_namespace(childrelid) != parentnsp) + { + if (cross_schema_children) + *cross_schema_children = lappend_oid(*cross_schema_children, + childrelid); + continue; + } + /* * Skip duplicates if user specified both parent and child * tables. diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 12beb37246f..250ee9a3cbf 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -49,6 +49,7 @@ #include "catalog/pg_opclass.h" #include "catalog/pg_policy.h" #include "catalog/pg_proc.h" +#include "catalog/pg_publication.h" #include "catalog/pg_publication_rel.h" #include "catalog/pg_rewrite.h" #include "catalog/pg_statistic_ext.h" @@ -63,6 +64,7 @@ #include "commands/event_trigger.h" #include "commands/extension.h" #include "commands/repack.h" +#include "commands/publicationcmds.h" #include "commands/sequence.h" #include "commands/tablecmds.h" #include "commands/tablespace.h" @@ -19802,6 +19804,16 @@ AlterTableNamespaceInternal(Relation rel, Oid oldNspOid, Oid nspOid, AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid, false, objsMoved); + /* + * Remove any EXCEPT clause entries for this relation from schema + * publications. A schema-scoped exclusion is no longer meaningful once + * the table moves to a different schema. + */ + if (rel->rd_rel->relkind == RELKIND_RELATION || + rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE) + RemoveSchemaPubExceptForRel(RelationGetRelid(rel), oldNspOid, + nspOid); + table_close(classRel, RowExclusiveLock); } @@ -21135,6 +21147,7 @@ ATExecAttachPartition(List **wqueue, Relation rel, PartitionCmd *cmd, if (exceptpuboids != NIL) { bool first = true; + bool has_alltables_pub = false; StringInfoData pubnames; initStringInfo(&pubnames); @@ -21148,17 +21161,22 @@ ATExecAttachPartition(List **wqueue, Relation rel, PartitionCmd *cmd, else appendStringInfo(&pubnames, _(", \"%s\""), pubname); first = false; + + if (GetPublication(pubid)->alltables) + has_alltables_pub = true; } ereport(ERROR, errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), - errmsg_plural("cannot attach table \"%s\" as partition because it is referenced in publication %s EXCEPT clause", - "cannot attach table \"%s\" as partition because it is referenced in publications %s EXCEPT clause", + errmsg_plural("cannot attach table \"%s\" as partition because it is named in EXCEPT clause of publication %s", + "cannot attach table \"%s\" as partition because it is named in EXCEPT clause of publications %s", list_length(exceptpuboids), RelationGetRelationName(attachrel), pubnames.data), errdetail("The publication EXCEPT clause cannot contain tables that are partitions."), - errhint("Change the publication's EXCEPT clause using ALTER PUBLICATION ... SET ALL TABLES.")); + errhint("%s", has_alltables_pub ? + _("Change the EXCEPT clause using ALTER PUBLICATION ... SET ALL TABLES ... EXCEPT.") : + _("Change the EXCEPT clause using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT."))); } list_free(exceptpuboids); diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y index 17035fb4d15..14520a5ccab 100644 --- a/src/backend/parser/gram.y +++ b/src/backend/parser/gram.y @@ -58,6 +58,7 @@ #include "nodes/makefuncs.h" #include "nodes/nodeFuncs.h" #include "parser/parser.h" +#include "utils/builtins.h" #include "utils/datetime.h" #include "utils/xml.h" @@ -11282,7 +11283,7 @@ AlterOwnerStmt: ALTER AGGREGATE aggregate_with_argtypes OWNER TO RoleSpec * pub_obj is one of: * * TABLE table [, ...] - * TABLES IN SCHEMA schema [, ...] + * TABLES IN SCHEMA schema [EXCEPT (TABLE table [, ...] )] [, ...] * *****************************************************************************/ @@ -11342,23 +11343,26 @@ PublicationObjSpec: $$->pubtable->columns = $3; $$->pubtable->whereClause = $4; } - | TABLES IN_P SCHEMA ColId + | TABLES IN_P SCHEMA ColId opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_SCHEMA; $$->name = $4; + $$->except_tables = $5; $$->location = @4; } - | TABLES IN_P SCHEMA CURRENT_SCHEMA + | TABLES IN_P SCHEMA CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_CUR_SCHEMA; + $$->except_tables = $5; $$->location = @4; } - | ColId opt_column_list OptWhereClause + | ColId opt_column_list OptWhereClause opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $4; /* * If either a row filter or column list is specified, create * a PublicationTable object. @@ -11402,10 +11406,11 @@ PublicationObjSpec: $$->pubtable->columns = $2; $$->pubtable->whereClause = $3; } - | CURRENT_SCHEMA + | CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $2; $$->location = @1; } ; @@ -20867,6 +20872,11 @@ preprocess_pub_all_objtype_list(List *all_objects_list, List **pubobjects, /* * Process pubobjspec_list to check for errors in any of the objects and * convert PUBLICATIONOBJ_CONTINUATION into appropriate PublicationObjSpecType. + * + * The except_tables attached to TABLES IN SCHEMA nodes are left in place here; + * ObjectsInPublicationToOids() qualifies their names, validates schema + * membership, and merges the qualified tables into its except_pubtables + * output list once the schema OID is known. */ static void preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) @@ -20895,6 +20905,13 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLE) { + /* EXCEPT is not valid for table objects */ + if (pubobj->except_tables != NIL) + ereport(ERROR, + errcode(ERRCODE_SYNTAX_ERROR), + errmsg("EXCEPT is not allowed for TABLE publication objects"), + parser_errposition(pubobj->location)); + /* relation name or pubtable must be set for this type of object */ if (!pubobj->name && !pubobj->pubtable) ereport(ERROR, diff --git a/src/backend/replication/pgoutput/pgoutput.c b/src/backend/replication/pgoutput/pgoutput.c index 484ffbe2cee..0a28533f6bc 100644 --- a/src/backend/replication/pgoutput/pgoutput.c +++ b/src/backend/replication/pgoutput/pgoutput.c @@ -2281,10 +2281,41 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) } } - if (list_member_oid(pubids, pub->oid) || - list_member_oid(schemaPubids, pub->oid) || - ancestor_published) + if (list_member_oid(pubids, pub->oid) || ancestor_published) publish = true; + else if (list_member_oid(schemaPubids, pub->oid)) + { + Oid root_relid; + bool root_is_except = false; + + /* + * schemaPubids is the list of publications that include + * relid's own schema, independent of the ancestor walk + * above -- a partition can live in a different schema + * than its root. Still need to check for exclusion here, + * using the top-most ancestor since only a root + * (non-partition) table can appear in an EXCEPT clause. + */ + if (am_partition) + { + List *ancestors = get_partition_ancestors(relid); + + /* + * ancestors is NIL for a partition with a pending + * DETACH CONCURRENTLY; + */ + root_relid = (ancestors == NIL) ? relid : + llast_oid(ancestors); + list_free(ancestors); + } + else + root_relid = relid; + + CheckPublicationRelEntry(pub->oid, root_relid, &root_is_except); + + if (!root_is_except) + publish = true; + } } /* diff --git a/src/backend/utils/cache/relcache.c b/src/backend/utils/cache/relcache.c index f475d703977..465e8a0ea02 100644 --- a/src/backend/utils/cache/relcache.c +++ b/src/backend/utils/cache/relcache.c @@ -5804,7 +5804,6 @@ RelationBuildPublicationDesc(Relation relation, PublicationDesc *pubdesc) { List *puboids = NIL; List *exceptpuboids = NIL; - List *alltablespuboids; ListCell *lc; MemoryContext oldcxt; Oid schemaid; @@ -5848,12 +5847,9 @@ RelationBuildPublicationDesc(Relation relation, PublicationDesc *pubdesc) if (relation->rd_rel->relispartition) { - Oid last_ancestor_relid; - - /* Add publications that the ancestors are in too. */ ancestors = get_partition_ancestors(relid); - last_ancestor_relid = llast_oid(ancestors); + /* Add publications that the ancestors are in too. */ foreach(lc, ancestors) { Oid ancestor = lfirst_oid(lc); @@ -5866,11 +5862,13 @@ RelationBuildPublicationDesc(Relation relation, PublicationDesc *pubdesc) } /* - * Only the top-most ancestor can appear in the EXCEPT clause. - * Therefore, for a partition, exclusion must be evaluated at the - * top-most ancestor. + * Only the topmost root of a partition hierarchy can appear in an + * EXCEPT clause, so that is where exclusion has to be evaluated. + * ancestors is NIL for a partition with a pending DETACH + * CONCURRENTLY, in which case there is no root to consult. */ - exceptpuboids = GetRelationExcludedPublications(last_ancestor_relid); + if (ancestors != NIL) + exceptpuboids = GetRelationExcludedPublications(llast_oid(ancestors)); } else { @@ -5881,10 +5879,12 @@ RelationBuildPublicationDesc(Relation relation, PublicationDesc *pubdesc) exceptpuboids = GetRelationExcludedPublications(relid); } - alltablespuboids = GetAllTablesPublications(); - puboids = list_concat_unique_oid(puboids, - list_difference_oid(alltablespuboids, - exceptpuboids)); + puboids = list_concat_unique_oid(puboids, GetAllTablesPublications()); + + /* Ignore the publications that exclude this relation. */ + if (exceptpuboids != NIL) + puboids = list_difference_oid(puboids, exceptpuboids); + foreach(lc, puboids) { Oid pubid = lfirst_oid(lc); diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c index 063e2555814..12acd18b9ef 100644 --- a/src/bin/psql/describe.c +++ b/src/bin/psql/describe.c @@ -3036,7 +3036,29 @@ describeOneTableDetails(const char *schemaname, "FROM pg_catalog.pg_publication p\n" " JOIN pg_catalog.pg_publication_namespace pn ON p.oid = pn.pnpubid\n" " JOIN pg_catalog.pg_class pc ON pc.relnamespace = pn.pnnspid\n" - "WHERE pc.oid ='%s' and pg_catalog.pg_relation_is_publishable('%s')\n" + "WHERE pc.oid ='%s' and pg_catalog.pg_relation_is_publishable('%s')\n", + oid, oid); + + if (pset.sversion >= 200000) + { + /* + * Publishing the schema does not publish a table named in the + * publication's EXCEPT clause, nor a partition whose root is + * named there, since excluding a root excludes the whole + * partition tree. Unlike the FOR ALL TABLES case below, a + * schema publication can have both kinds of + * pg_publication_rel row, so prexcept has to be tested. + */ + appendPQExpBuffer(&buf, + " AND NOT EXISTS (\n" + " SELECT 1\n" + " FROM pg_catalog.pg_publication_rel pr\n" + " WHERE pr.prpubid = p.oid AND pr.prexcept AND\n" + " (pr.prrelid = '%s' OR pr.prrelid = pg_catalog.pg_partition_root('%s')))\n", + oid, oid); + } + + appendPQExpBuffer(&buf, "UNION\n" "SELECT pubname\n" " , pg_catalog.pg_get_expr(pr.prqual, c.oid)\n" @@ -3060,7 +3082,7 @@ describeOneTableDetails(const char *schemaname, " FROM pg_catalog.pg_publication_namespace pn\n" " WHERE pn.pnpubid = p.oid\n" " AND pn.pnnspid = c.relnamespace)\n", - oid, oid, oid); + oid); if (pset.sversion >= 190000) { @@ -6839,6 +6861,24 @@ describePublications(const char *pattern) if (!addFooterToPublicationDesc(&buf, _("Tables from schemas:"), true, &cont)) goto error_return; + + if (pset.sversion >= 200000) + { + /* + * Get tables in the EXCEPT clause for this schema + * publication. + */ + printfPQExpBuffer(&buf, + "SELECT concat(c.relnamespace::regnamespace, '.', c.relname)\n" + "FROM pg_catalog.pg_class c\n" + " JOIN pg_catalog.pg_publication_rel pr ON c.oid = pr.prrelid\n" + "WHERE pr.prpubid = '%s'\n" + " AND pr.prexcept\n" + "ORDER BY 1", pubid); + if (!addFooterToPublicationDesc(&buf, _("Except tables:"), + true, &cont)) + goto error_return; + } } } else diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index 190fff7ea0e..f069e2654cc 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -1065,6 +1065,24 @@ static const SchemaQuery Query_for_trigger_of_table = { "SELECT nspname FROM pg_catalog.pg_namespace "\ " WHERE nspname LIKE '%s'" +#define Query_for_list_of_tables_in_schema \ +"SELECT n.nspname || '.' || c.relname "\ +" FROM pg_catalog.pg_class c "\ +" JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "\ +" WHERE c.relkind IN (" CppAsString2(RELKIND_RELATION) ", " \ + CppAsString2(RELKIND_PARTITIONED_TABLE) ") "\ +" AND (n.nspname || '.' || c.relname) LIKE '%s' "\ +" AND n.nspname = '%s'" + +#define Query_for_list_of_tables_in_current_schema \ +"SELECT c.relname "\ +" FROM pg_catalog.pg_class c "\ +" JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "\ +" WHERE c.relkind IN (" CppAsString2(RELKIND_RELATION) ", " \ + CppAsString2(RELKIND_PARTITIONED_TABLE) ") "\ +" AND c.relname LIKE '%s' "\ +" AND n.nspname = pg_catalog.current_schema()" + /* Use COMPLETE_WITH_QUERY_VERBATIM with these queries for GUC names: */ #define Query_for_list_of_alter_system_set_vars \ "SELECT pg_catalog.lower(name) FROM pg_catalog.pg_settings "\ @@ -3777,8 +3795,21 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); - else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && (!ends_with(prev_wd, ','))) - COMPLETE_WITH("WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE", "WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* Complete "CREATE PUBLICATION <name> [...] WITH" */ else if (Matches("CREATE", "PUBLICATION", MatchAnyN, "WITH", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/include/catalog/pg_publication.h b/src/include/catalog/pg_publication.h index 89b4bb14f62..451559552ad 100644 --- a/src/include/catalog/pg_publication.h +++ b/src/include/catalog/pg_publication.h @@ -179,6 +179,8 @@ extern List *GetIncludedPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt); extern List *GetExcludedPublicationTables(Oid pubid, PublicationPartOpt pub_partopt); +extern List *GetPublicationRelationsOfAnyKind(Oid pubid, + PublicationPartOpt pub_partopt); extern List *GetAllTablesPublications(void); extern List *GetAllPublicationRelations(Oid pubid, char relkind, bool pubviaroot); extern List *GetPublicationSchemas(Oid pubid); @@ -192,6 +194,7 @@ extern List *GetPubPartitionOptionRelations(List *result, Oid relid); extern Oid GetTopMostAncestorInPublication(Oid puboid, List *ancestors, int *ancestor_level); +extern bool CheckPublicationRelEntry(Oid pubid, Oid relid, bool *is_except); extern bool is_publishable_relation(Relation rel); extern bool is_schema_publication(Oid pubid); diff --git a/src/include/commands/publicationcmds.h b/src/include/commands/publicationcmds.h index 4cf45c17cc5..fb1703aa675 100644 --- a/src/include/commands/publicationcmds.h +++ b/src/include/commands/publicationcmds.h @@ -27,6 +27,8 @@ extern void AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt); extern void RemovePublicationById(Oid pubid); extern void RemovePublicationRelById(Oid proid); extern void RemovePublicationSchemaById(Oid psoid); +extern void RemoveSchemaPubExceptForRel(Oid relid, Oid oldNspOid, + Oid newNspOid); extern ObjectAddress AlterPublicationOwner(const char *name, Oid newOwnerId); extern void AlterPublicationOwner_oid(Oid pubid, Oid newOwnerId); diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h index 8a9df884276..0c7f2b9995c 100644 --- a/src/include/nodes/parsenodes.h +++ b/src/include/nodes/parsenodes.h @@ -4510,6 +4510,9 @@ typedef struct PublicationTable Node *whereClause; /* qualifications */ List *columns; /* List of columns in a publication table */ bool except; /* True if listed in the EXCEPT clause */ + bool except_in_schema; /* True if listed in the EXCEPT clause of + * a TABLES IN SCHEMA clause, whose scope + * is limited to that schema */ } PublicationTable; /* @@ -4531,6 +4534,8 @@ typedef struct PublicationObjSpec PublicationObjSpecType pubobjtype; /* type of this publication object */ char *name; PublicationTable *pubtable; + List *except_tables; /* tables specified in the EXCEPT clause (for + * TABLES IN SCHEMA) */ ParseLoc location; /* token location, or -1 if unknown */ } PublicationObjSpec; diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 4f21462cc17..9498ef9a7f8 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -279,6 +279,12 @@ CREATE PUBLICATION testpub_foralltables_excepttable2 FOR ALL TABLES EXCEPT (test ERROR: syntax error at or near "testpub_tbl1" LINE 1: ..._foralltables_excepttable2 FOR ALL TABLES EXCEPT (testpub_tb... ^ +-- fail - EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testpub_tbl3); +ERROR: EXCEPT is not allowed for TABLE publication objects +LINE 2: FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testp... + ^ --------------------------------------------- -- SET ALL TABLES/SEQUENCES --------------------------------------------- @@ -473,13 +479,292 @@ CREATE TABLE tab_main (a int) PARTITION BY RANGE(a); -- Attaching a partition is not allowed if the partitioned table appears in a -- publication's EXCEPT clause. ALTER TABLE tab_main ATTACH PARTITION testpub_root FOR VALUES FROM (0) TO (200); -ERROR: cannot attach table "testpub_root" as partition because it is referenced in publication "testpub8" EXCEPT clause +ERROR: cannot attach table "testpub_root" as partition because it is named in EXCEPT clause of publication "testpub8" DETAIL: The publication EXCEPT clause cannot contain tables that are partitions. -HINT: Change the publication's EXCEPT clause using ALTER PUBLICATION ... SET ALL TABLES. +HINT: Change the EXCEPT clause using ALTER PUBLICATION ... SET ALL TABLES ... EXCEPT. RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Create same-named tables in public to verify unqualified EXCEPT entries +-- are qualified with the named schema, not public +CREATE TABLE testpub_nopk (foo int, bar int); +CREATE TABLE testpub_tbl_s1 (a int primary key, b text); +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + Publication testpub_schema_except1 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- Exclude multiple tables using unqualified names; same-named tables exist in +-- public to confirm unqualified names resolve to pub_test, not public +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + Publication testpub_schema_except2 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_nopk" + "pub_test.testpub_tbl_s1" + +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testp... + ^ +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); +ERROR: table "pub_test.testpub_tbl_s1" in EXCEPT clause does not belong to schema "public" +LINE 2: ...R TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.t... + ^ +-- Multiple schemas each with their own EXCEPT clause +CREATE PUBLICATION testpub_schema_except_multi + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_schema_except_multi + Publication testpub_schema_except_multi + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- fail: same schema repeated with same EXCEPT clauses +CREATE PUBLICATION testpub_schema_except_conflict + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: conflicting or redundant EXCEPT clauses for schema "pub_test" +-- fail: same schema repeated with conflicting or no EXCEPT clauses +CREATE PUBLICATION testpub_schema_except_conflict2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2), + pub_test; +ERROR: conflicting or redundant EXCEPT clauses for schema "pub_test" +-- ALTER TABLE ... SET SCHEMA on a table excluded by a schema publication: +-- the schema-scoped exclusion is no longer meaningful once the table moves +-- out of its schema, so the exclusion is auto-removed. +CREATE PUBLICATION testpub_schema_except_setsch + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_schema_except_setsch + Publication testpub_schema_except_setsch + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s2" + +ALTER TABLE pub_test.testpub_tbl_s2 SET SCHEMA public; +\dRp+ testpub_schema_except_setsch + Publication testpub_schema_except_setsch + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + +DROP PUBLICATION testpub_schema_except_setsch; +-- Restore for further tests +ALTER TABLE public.testpub_tbl_s2 SET SCHEMA pub_test; +-- fail: table appears in both the explicit table list and the EXCEPT clause +CREATE PUBLICATION testpub_except_conflict + FOR TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot be both published and excluded +-- fail: nonexistent table in EXCEPT clause +CREATE PUBLICATION testpub_except_norel + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- fail: partition cannot appear in EXCEPT clause; only root tables are allowed +CREATE TABLE pub_test.testpub_parted_s (a int) PARTITION BY LIST (a); +CREATE TABLE pub_test.testpub_part_s PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (1); +CREATE PUBLICATION testpub_except_partition + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); +ERROR: cannot specify relation "pub_test.testpub_part_s" in the publication EXCEPT clause +DETAIL: This operation is not supported for individual partitions. +-- fail: TABLE keyword is required for the first entry in the EXCEPT clause +CREATE PUBLICATION testpub_except_nokw + FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +ERROR: syntax error at or near "testpub_nopk" +LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + ^ +-- Check that a table excluded from a schema publication is reported only as +-- excluded and not as published. +\d pub_test.testpub_nopk + Table "pub_test.testpub_nopk" + Column | Type | Collation | Nullable | Default +--------+---------+-----------+----------+--------- + foo | integer | | | + bar | integer | | | +Included in publications: + "testpub_schema_except1" + "testpub_schema_except_multi" +Excluded from publications: + "testpub_schema_except2" + +-- fail: ADD TABLE for a partition is rejected when a partition ancestor +-- is currently in the publication's EXCEPT list. +CREATE PUBLICATION testpub_except_ancestor + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ALTER PUBLICATION testpub_except_ancestor ADD TABLE pub_test.testpub_part_s; +ERROR: cannot add partition "pub_test.testpub_part_s" to publication "testpub_except_ancestor" +DETAIL: Partition root "pub_test.testpub_parted_s" is named in the publication's EXCEPT clause for schema "pub_test". +HINT: Change the EXCEPT clause using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT. +DROP PUBLICATION testpub_except_ancestor; +-- fail: same contradiction (explicit partition + EXCEPT-ed ancestor), but +-- given in a single statement instead of two separate ones +CREATE PUBLICATION testpub_except_ancestor_same_create + FOR TABLE pub_test.testpub_part_s, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ERROR: partition "pub_test.testpub_part_s" cannot be both published and excluded +DETAIL: Partition root "pub_test.testpub_parted_s" is named in the publication's EXCEPT clause for schema "pub_test". +-- fail: same contradiction as above, but the partition lives in a different +-- schema (public) than its EXCEPT-ed root (pub_test) +CREATE TABLE public.testpub_part_s2 PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (2); +CREATE PUBLICATION testpub_except_ancestor_cross_schema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s), + TABLE public.testpub_part_s2; +ERROR: partition "public.testpub_part_s2" cannot be both published and excluded +DETAIL: Partition root "pub_test.testpub_parted_s" is named in the publication's EXCEPT clause for schema "pub_test". +DROP TABLE public.testpub_part_s2; +-- ALTER PUBLICATION ... SET replaces the publication's whole relation list, so +-- an existing entry for a relation now requested with the opposite kind must be +-- dropped and re-added, not silently left in place. +CREATE PUBLICATION testpub_except_alter1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +-- the excluded table becomes an ordinary member: one non-EXCEPT entry, no +-- EXCEPT entry, and no schema left in the publication +ALTER PUBLICATION testpub_except_alter1 SET TABLE pub_test.testpub_tbl_s1; +\dRp+ testpub_except_alter1 + Publication testpub_except_alter1 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables: + "pub_test.testpub_tbl_s1" + +DROP PUBLICATION testpub_except_alter1; +-- and the reverse direction: an ordinary member becomes an EXCEPT entry +CREATE PUBLICATION testpub_except_alter2 FOR TABLE pub_test.testpub_tbl_s1; +ALTER PUBLICATION testpub_except_alter2 + SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_except_alter2 + Publication testpub_except_alter2 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +DROP PUBLICATION testpub_except_alter2; +-- Cross-schema inheritance children and EXCEPT. An EXCEPT clause also +-- excludes inheritance children of a parent named without ONLY. +CREATE TABLE pub_test.testpub_inh_parent (a int); +CREATE TABLE pub_test.testpub_inh_sibling (b int) INHERITS (pub_test.testpub_inh_parent); +CREATE TABLE testpub_inh_child (b int) INHERITS (pub_test.testpub_inh_parent); +CREATE PUBLICATION testpub_inh + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_inh_parent); +-- Two EXCEPT entries: the parent and the child in pub_test. +\dRp+ testpub_inh + Publication testpub_inh + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_inh_parent" + "pub_test.testpub_inh_sibling" + +DROP PUBLICATION testpub_inh; +-- fail: the child testpub_inh_child is also included through TABLES IN SCHEM +-- public +CREATE PUBLICATION testpub_inh + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_inh_parent), + TABLES IN SCHEMA public; +ERROR: table "public.testpub_inh_child" cannot be both published and excluded +DETAIL: It inherits from a table named in the EXCEPT clause of another schema, and its own schema "public" is published in full. +HINT: Use ONLY in the EXCEPT clause to exclude just the parent, or name this table in the EXCEPT clause of schema "public". +-- fail: the child is also explicitly included by the same statement +CREATE PUBLICATION testpub_inh + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_inh_parent), + TABLE testpub_inh_child; +ERROR: table "public.testpub_inh_child" cannot be both published and excluded +DETAIL: It inherits from a table named in an EXCEPT clause of this statement. +HINT: Use ONLY in the EXCEPT clause to exclude just the parent, or do not publish this table explicitly. +-- ONLY resolves the conflict: only the parent is excluded, so the child can +-- be published explicitly +CREATE PUBLICATION testpub_inh + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE ONLY pub_test.testpub_inh_parent), + TABLE testpub_inh_child; +\dRp+ testpub_inh + Publication testpub_inh + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables: + "public.testpub_inh_child" +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_inh_parent" + +DROP PUBLICATION testpub_inh; +-- An EXCEPT clause in the child's schema also excludes the child explicitly, +-- so both clauses agree and there is no conflict. +CREATE PUBLICATION testpub_inh + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_inh_parent), + TABLES IN SCHEMA public EXCEPT (TABLE testpub_inh_child); +\dRp+ testpub_inh + Publication testpub_inh + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_inh_parent" + "pub_test.testpub_inh_sibling" + "public.testpub_inh_child" + +DROP PUBLICATION testpub_inh; +DROP TABLE testpub_inh_child, pub_test.testpub_inh_sibling, + pub_test.testpub_inh_parent; +-- Cleanup +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP TABLE pub_test.testpub_parted_s CASCADE; +DROP TABLE testpub_nopk, testpub_tbl_s1; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +--------------------------------------------- +-- Tests for publications with SEQUENCES +--------------------------------------------- CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; -- FOR ALL SEQUENCES @@ -1970,6 +2255,54 @@ ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b); ERROR: column specification not allowed for schema LINE 1: ...TION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b)... ^ +-- EXCEPT clause with CURRENT_SCHEMA: cross-schema entry must be rejected +SET search_path = pub_test1; +-- qualified name from wrong schema -> error +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.tbl1); +ERROR: table "pub_test2.tbl1" in EXCEPT clause does not belong to schema "pub_test1" +LINE 1: ...FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.... + ^ +-- unqualified name implicitly qualified with current schema (pub_test1.tbl) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl); +RESET client_min_messages; +\dRp+ testpub_cursch_except + Publication testpub_cursch_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test1" +Except tables: + "pub_test1.tbl" + +DROP PUBLICATION testpub_cursch_except; +-- succeeds: CURRENT_SCHEMA and pub_test1 (same schema) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_named_same + FOR TABLES IN SCHEMA CURRENT_SCHEMA, pub_test1; +RESET client_min_messages; +\dRp+ testpub_cursch_named_same + Publication testpub_cursch_named_same + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test1" + +DROP PUBLICATION testpub_cursch_named_same; +-- fail: CURRENT_SCHEMA and pub_test1 (same schema) have +-- conflicting EXCEPT clauses +CREATE PUBLICATION testpub_cursch_named_conflict + FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl), + pub_test1 EXCEPT (TABLE tbl1); +ERROR: conflicting or redundant EXCEPT clauses for schema "pub_test1" +-- fail: two CURRENT_SCHEMA mentions with conflicting EXCEPT clauses +CREATE PUBLICATION testpub_cursch_cursch_conflict + FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl), + CURRENT_SCHEMA EXCEPT (TABLE tbl1); +ERROR: conflicting or redundant EXCEPT clauses for schema "pub_test1" +RESET search_path; -- cleanup pub_test1 schema for invalidation tests ALTER PUBLICATION testpub2_forschema DROP TABLES IN SCHEMA pub_test1; DROP PUBLICATION testpub3_forschema, testpub4_forschema, testpub5_forschema, testpub6_forschema, testpub_fortable; @@ -2321,6 +2654,7 @@ DROP ROLE regress_publication_user_dummy; -- Test pg_get_publication_tables(text[], oid) function CREATE SCHEMA gpt_test_sch; CREATE TABLE gpt_test_sch.tbl_sch (id int); +CREATE TABLE gpt_test_sch.tbl_sch2 (id int); CREATE TABLE tbl_normal (id int); CREATE TABLE tbl_parent (id1 int, id2 int, id3 int) PARTITION BY RANGE (id1); CREATE TABLE tbl_part1 PARTITION OF tbl_parent FOR VALUES FROM (1) TO (10); @@ -2331,6 +2665,7 @@ CREATE PUBLICATION pub_all_no_viaroot FOR ALL TABLES WITH (publish_via_partition CREATE PUBLICATION pub_all_except FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = true); CREATE PUBLICATION pub_all_except_no_viaroot FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_schema FOR TABLES IN SCHEMA gpt_test_sch; +CREATE PUBLICATION pub_schema_except FOR TABLES IN SCHEMA gpt_test_sch EXCEPT (TABLE gpt_test_sch.tbl_sch); CREATE PUBLICATION pub_normal FOR TABLE tbl_normal WHERE (id < 10); CREATE PUBLICATION pub_part_leaf FOR TABLE tbl_part1 WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_part_parent FOR TABLE tbl_parent (id1, id2) WHERE (id1 = 10) WITH (publish_via_partition_root = true); @@ -2482,6 +2817,51 @@ SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_part1'); -- no r ---------+---------+-------+------ (0 rows) +-- test for EXCEPT clause with schema publication +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch'); -- no result (excluded) + pubname | relname | attrs | qual +---------+---------+-------+------ +(0 rows) + +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch2'); -- one row (included via schema) + pubname | relname | attrs | qual +-------------------+----------+-------+------ + pub_schema_except | tbl_sch2 | 1 | +(1 row) + +-- test for EXCEPT clause with schema publication, where the excluded root's +-- partition lives in a different schema. Excluding the root also excludes its +-- partition, even though the partition is in another schema. Publishing that +-- schema as well creates a conflict because the partition would be both +-- published and excluded; without publishing the partition's schema, the +-- exclusion still cascades to the partition. +CREATE SCHEMA gpt_cross_sch1; +CREATE SCHEMA gpt_cross_sch2; +CREATE TABLE gpt_cross_sch1.croot (id int) PARTITION BY RANGE (id); +CREATE TABLE gpt_cross_sch2.cpart1 PARTITION OF gpt_cross_sch1.croot FOR VALUES FROM (1) TO (10); +-- fail: cpart1 would be published by its own schema and excluded through its root +CREATE PUBLICATION pub_cross_schema_except FOR TABLES IN SCHEMA gpt_cross_sch1 EXCEPT (TABLE gpt_cross_sch1.croot), TABLES IN SCHEMA gpt_cross_sch2; +ERROR: table "gpt_cross_sch2.cpart1" cannot be both published and excluded +DETAIL: It is a partition of "gpt_cross_sch1.croot", which is named in the EXCEPT clause of schema "gpt_cross_sch1", and its own schema "gpt_cross_sch2" is published in full. +HINT: Either do not publish schema "gpt_cross_sch2", or do not name "gpt_cross_sch1.croot" in the EXCEPT clause. +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION pub_cross_schema_except FOR TABLES IN SCHEMA gpt_cross_sch1 EXCEPT (TABLE gpt_cross_sch1.croot); +RESET client_min_messages; +SELECT * FROM test_gpt(ARRAY['pub_cross_schema_except'], 'gpt_cross_sch1.croot'); -- no result (excluded) + pubname | relname | attrs | qual +---------+---------+-------+------ +(0 rows) + +-- no result: the root's exclusion cascades to the partition even though the +-- partition lives in a schema this publication does not mention +SELECT * FROM test_gpt(ARRAY['pub_cross_schema_except'], 'gpt_cross_sch2.cpart1'); + pubname | relname | attrs | qual +---------+---------+-------+------ +(0 rows) + +DROP PUBLICATION pub_cross_schema_except; +DROP TABLE gpt_cross_sch2.cpart1, gpt_cross_sch1.croot; +DROP SCHEMA gpt_cross_sch1, gpt_cross_sch2; -- two rows with different row filter SELECT * FROM test_gpt(ARRAY['pub_all', 'pub_normal'], 'tbl_normal'); pubname | relname | attrs | qual @@ -2534,6 +2914,7 @@ DROP PUBLICATION pub_all_no_viaroot; DROP PUBLICATION pub_all_except; DROP PUBLICATION pub_all_except_no_viaroot; DROP PUBLICATION pub_schema; +DROP PUBLICATION pub_schema_except; DROP PUBLICATION pub_normal; DROP PUBLICATION pub_part_leaf; DROP PUBLICATION pub_part_parent; @@ -2542,7 +2923,9 @@ DROP PUBLICATION pub_part_parent_child; DROP VIEW gpt_test_view; DROP TABLE tbl_normal, tbl_parent, tbl_part1; DROP SCHEMA gpt_test_sch CASCADE; -NOTICE: drop cascades to table gpt_test_sch.tbl_sch +NOTICE: drop cascades to 2 other objects +DETAIL: drop cascades to table gpt_test_sch.tbl_sch +drop cascades to table gpt_test_sch.tbl_sch2 -- stage objects for pg_dump tests CREATE SCHEMA pubme CREATE TABLE t0 (c int, d int) CREATE TABLE t1 (c int); CREATE SCHEMA pubme2 CREATE TABLE t0 (c int, d int); diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index fac54b02e27..8258c0591da 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -125,6 +125,9 @@ CREATE PUBLICATION testpub_foralltables_excepttable1 FOR ALL TABLES EXCEPT (TABL \d testpub_tbl1 -- fail - first table in the EXCEPT list should use TABLE keyword CREATE PUBLICATION testpub_foralltables_excepttable2 FOR ALL TABLES EXCEPT (testpub_tbl1, testpub_tbl2); +-- fail - EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testpub_tbl3); --------------------------------------------- -- SET ALL TABLES/SEQUENCES @@ -222,7 +225,177 @@ RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Create same-named tables in public to verify unqualified EXCEPT entries +-- are qualified with the named schema, not public +CREATE TABLE testpub_nopk (foo int, bar int); +CREATE TABLE testpub_tbl_s1 (a int primary key, b text); + +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + +-- Exclude multiple tables using unqualified names; same-named tables exist in +-- public to confirm unqualified names resolve to pub_test, not public +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); + +-- Multiple schemas each with their own EXCEPT clause +CREATE PUBLICATION testpub_schema_except_multi + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_schema_except_multi + +-- fail: same schema repeated with same EXCEPT clauses +CREATE PUBLICATION testpub_schema_except_conflict + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: same schema repeated with conflicting or no EXCEPT clauses +CREATE PUBLICATION testpub_schema_except_conflict2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2), + pub_test; + +-- ALTER TABLE ... SET SCHEMA on a table excluded by a schema publication: +-- the schema-scoped exclusion is no longer meaningful once the table moves +-- out of its schema, so the exclusion is auto-removed. +CREATE PUBLICATION testpub_schema_except_setsch + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_schema_except_setsch +ALTER TABLE pub_test.testpub_tbl_s2 SET SCHEMA public; +\dRp+ testpub_schema_except_setsch +DROP PUBLICATION testpub_schema_except_setsch; +-- Restore for further tests +ALTER TABLE public.testpub_tbl_s2 SET SCHEMA pub_test; + +-- fail: table appears in both the explicit table list and the EXCEPT clause +CREATE PUBLICATION testpub_except_conflict + FOR TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: nonexistent table in EXCEPT clause +CREATE PUBLICATION testpub_except_norel + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- fail: partition cannot appear in EXCEPT clause; only root tables are allowed +CREATE TABLE pub_test.testpub_parted_s (a int) PARTITION BY LIST (a); +CREATE TABLE pub_test.testpub_part_s PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (1); +CREATE PUBLICATION testpub_except_partition + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); + +-- fail: TABLE keyword is required for the first entry in the EXCEPT clause +CREATE PUBLICATION testpub_except_nokw + FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + +-- Check that a table excluded from a schema publication is reported only as +-- excluded and not as published. +\d pub_test.testpub_nopk + +-- fail: ADD TABLE for a partition is rejected when a partition ancestor +-- is currently in the publication's EXCEPT list. +CREATE PUBLICATION testpub_except_ancestor + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ALTER PUBLICATION testpub_except_ancestor ADD TABLE pub_test.testpub_part_s; +DROP PUBLICATION testpub_except_ancestor; + +-- fail: same contradiction (explicit partition + EXCEPT-ed ancestor), but +-- given in a single statement instead of two separate ones +CREATE PUBLICATION testpub_except_ancestor_same_create + FOR TABLE pub_test.testpub_part_s, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); + +-- fail: same contradiction as above, but the partition lives in a different +-- schema (public) than its EXCEPT-ed root (pub_test) +CREATE TABLE public.testpub_part_s2 PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (2); +CREATE PUBLICATION testpub_except_ancestor_cross_schema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s), + TABLE public.testpub_part_s2; +DROP TABLE public.testpub_part_s2; + +-- ALTER PUBLICATION ... SET replaces the publication's whole relation list, so +-- an existing entry for a relation now requested with the opposite kind must be +-- dropped and re-added, not silently left in place. +CREATE PUBLICATION testpub_except_alter1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +-- the excluded table becomes an ordinary member: one non-EXCEPT entry, no +-- EXCEPT entry, and no schema left in the publication +ALTER PUBLICATION testpub_except_alter1 SET TABLE pub_test.testpub_tbl_s1; +\dRp+ testpub_except_alter1 +DROP PUBLICATION testpub_except_alter1; + +-- and the reverse direction: an ordinary member becomes an EXCEPT entry +CREATE PUBLICATION testpub_except_alter2 FOR TABLE pub_test.testpub_tbl_s1; +ALTER PUBLICATION testpub_except_alter2 + SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_except_alter2 +DROP PUBLICATION testpub_except_alter2; + +-- Cross-schema inheritance children and EXCEPT. An EXCEPT clause also +-- excludes inheritance children of a parent named without ONLY. +CREATE TABLE pub_test.testpub_inh_parent (a int); +CREATE TABLE pub_test.testpub_inh_sibling (b int) INHERITS (pub_test.testpub_inh_parent); +CREATE TABLE testpub_inh_child (b int) INHERITS (pub_test.testpub_inh_parent); +CREATE PUBLICATION testpub_inh + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_inh_parent); +-- Two EXCEPT entries: the parent and the child in pub_test. +\dRp+ testpub_inh +DROP PUBLICATION testpub_inh; + +-- fail: the child testpub_inh_child is also included through TABLES IN SCHEM +-- public +CREATE PUBLICATION testpub_inh + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_inh_parent), + TABLES IN SCHEMA public; + +-- fail: the child is also explicitly included by the same statement +CREATE PUBLICATION testpub_inh + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_inh_parent), + TABLE testpub_inh_child; + +-- ONLY resolves the conflict: only the parent is excluded, so the child can +-- be published explicitly +CREATE PUBLICATION testpub_inh + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE ONLY pub_test.testpub_inh_parent), + TABLE testpub_inh_child; +\dRp+ testpub_inh +DROP PUBLICATION testpub_inh; + +-- An EXCEPT clause in the child's schema also excludes the child explicitly, +-- so both clauses agree and there is no conflict. +CREATE PUBLICATION testpub_inh + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_inh_parent), + TABLES IN SCHEMA public EXCEPT (TABLE testpub_inh_child); +\dRp+ testpub_inh +DROP PUBLICATION testpub_inh; +DROP TABLE testpub_inh_child, pub_test.testpub_inh_sibling, + pub_test.testpub_inh_parent; + +-- Cleanup +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP TABLE pub_test.testpub_parted_s CASCADE; +DROP TABLE testpub_nopk, testpub_tbl_s1; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; + +--------------------------------------------- +-- Tests for publications with SEQUENCES +--------------------------------------------- CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; @@ -1194,6 +1367,38 @@ ALTER PUBLICATION testpub1_forschema SET TABLES IN SCHEMA pub_test1, pub_test1; ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo (a, b); ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b); +-- EXCEPT clause with CURRENT_SCHEMA: cross-schema entry must be rejected +SET search_path = pub_test1; +-- qualified name from wrong schema -> error +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.tbl1); +-- unqualified name implicitly qualified with current schema (pub_test1.tbl) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl); +RESET client_min_messages; +\dRp+ testpub_cursch_except +DROP PUBLICATION testpub_cursch_except; + +-- succeeds: CURRENT_SCHEMA and pub_test1 (same schema) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_named_same + FOR TABLES IN SCHEMA CURRENT_SCHEMA, pub_test1; +RESET client_min_messages; +\dRp+ testpub_cursch_named_same +DROP PUBLICATION testpub_cursch_named_same; + +-- fail: CURRENT_SCHEMA and pub_test1 (same schema) have +-- conflicting EXCEPT clauses +CREATE PUBLICATION testpub_cursch_named_conflict + FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl), + pub_test1 EXCEPT (TABLE tbl1); + +-- fail: two CURRENT_SCHEMA mentions with conflicting EXCEPT clauses +CREATE PUBLICATION testpub_cursch_cursch_conflict + FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl), + CURRENT_SCHEMA EXCEPT (TABLE tbl1); + +RESET search_path; + -- cleanup pub_test1 schema for invalidation tests ALTER PUBLICATION testpub2_forschema DROP TABLES IN SCHEMA pub_test1; DROP PUBLICATION testpub3_forschema, testpub4_forschema, testpub5_forschema, testpub6_forschema, testpub_fortable; @@ -1448,6 +1653,7 @@ DROP ROLE regress_publication_user_dummy; -- Test pg_get_publication_tables(text[], oid) function CREATE SCHEMA gpt_test_sch; CREATE TABLE gpt_test_sch.tbl_sch (id int); +CREATE TABLE gpt_test_sch.tbl_sch2 (id int); CREATE TABLE tbl_normal (id int); CREATE TABLE tbl_parent (id1 int, id2 int, id3 int) PARTITION BY RANGE (id1); CREATE TABLE tbl_part1 PARTITION OF tbl_parent FOR VALUES FROM (1) TO (10); @@ -1459,6 +1665,7 @@ CREATE PUBLICATION pub_all_no_viaroot FOR ALL TABLES WITH (publish_via_partition CREATE PUBLICATION pub_all_except FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = true); CREATE PUBLICATION pub_all_except_no_viaroot FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_schema FOR TABLES IN SCHEMA gpt_test_sch; +CREATE PUBLICATION pub_schema_except FOR TABLES IN SCHEMA gpt_test_sch EXCEPT (TABLE gpt_test_sch.tbl_sch); CREATE PUBLICATION pub_normal FOR TABLE tbl_normal WHERE (id < 10); CREATE PUBLICATION pub_part_leaf FOR TABLE tbl_part1 WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_part_parent FOR TABLE tbl_parent (id1, id2) WHERE (id1 = 10) WITH (publish_via_partition_root = true); @@ -1515,6 +1722,37 @@ SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'gpt_test_sch.tbl_sch SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_parent'); -- no result (excluded) SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_part1'); -- no result +-- test for EXCEPT clause with schema publication +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch'); -- no result (excluded) +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch2'); -- one row (included via schema) + +-- test for EXCEPT clause with schema publication, where the excluded root's +-- partition lives in a different schema. Excluding the root also excludes its +-- partition, even though the partition is in another schema. Publishing that +-- schema as well creates a conflict because the partition would be both +-- published and excluded; without publishing the partition's schema, the +-- exclusion still cascades to the partition. +CREATE SCHEMA gpt_cross_sch1; +CREATE SCHEMA gpt_cross_sch2; +CREATE TABLE gpt_cross_sch1.croot (id int) PARTITION BY RANGE (id); +CREATE TABLE gpt_cross_sch2.cpart1 PARTITION OF gpt_cross_sch1.croot FOR VALUES FROM (1) TO (10); + +-- fail: cpart1 would be published by its own schema and excluded through its root +CREATE PUBLICATION pub_cross_schema_except FOR TABLES IN SCHEMA gpt_cross_sch1 EXCEPT (TABLE gpt_cross_sch1.croot), TABLES IN SCHEMA gpt_cross_sch2; + +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION pub_cross_schema_except FOR TABLES IN SCHEMA gpt_cross_sch1 EXCEPT (TABLE gpt_cross_sch1.croot); +RESET client_min_messages; + +SELECT * FROM test_gpt(ARRAY['pub_cross_schema_except'], 'gpt_cross_sch1.croot'); -- no result (excluded) +-- no result: the root's exclusion cascades to the partition even though the +-- partition lives in a schema this publication does not mention +SELECT * FROM test_gpt(ARRAY['pub_cross_schema_except'], 'gpt_cross_sch2.cpart1'); + +DROP PUBLICATION pub_cross_schema_except; +DROP TABLE gpt_cross_sch2.cpart1, gpt_cross_sch1.croot; +DROP SCHEMA gpt_cross_sch1, gpt_cross_sch2; + -- two rows with different row filter SELECT * FROM test_gpt(ARRAY['pub_all', 'pub_normal'], 'tbl_normal'); @@ -1543,6 +1781,7 @@ DROP PUBLICATION pub_all_no_viaroot; DROP PUBLICATION pub_all_except; DROP PUBLICATION pub_all_except_no_viaroot; DROP PUBLICATION pub_schema; +DROP PUBLICATION pub_schema_except; DROP PUBLICATION pub_normal; DROP PUBLICATION pub_part_leaf; DROP PUBLICATION pub_part_parent; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 43b51c8ff71..de4e7dff7ba 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -24,14 +24,17 @@ my $result; sub test_except_root_partition { - my ($pubviaroot) = @_; + my ($pubviaroot, $pubsql) = @_; + $pubsql //= + "CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1)"; + $pubsql .= " WITH (publish_via_partition_root = $pubviaroot)"; # If the root partitioned table is in the EXCEPT clause, all its # partitions are excluded from publication, regardless of the # publish_via_partition_root setting. $node_publisher->safe_psql( 'postgres', qq( - CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1) WITH (publish_via_partition_root = $pubviaroot); + $pubsql; INSERT INTO root1 VALUES (1), (101); )); $node_subscriber->safe_psql('postgres', @@ -223,6 +226,208 @@ $node_subscriber->safe_psql( test_except_root_partition('false'); test_except_root_partition('true'); +# Same validation using TABLES IN SCHEMA instead of FOR ALL TABLES. +my $schema_pub = + "CREATE PUBLICATION tap_pub_part FOR TABLES IN SCHEMA public EXCEPT (TABLE public.root1)"; +test_except_root_partition('false', $schema_pub); +test_except_root_partition('true', $schema_pub); + +# ============================================ +# EXCEPT test cases for TABLES IN SCHEMA +# ============================================ + +# Create a dedicated schema with two tables: one to be published and one to be +# excluded. Also create inherited tables to verify ONLY semantics. +$node_publisher->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_published AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.tab_excluded AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.parent (a int); + CREATE TABLE sch1.child (b int) INHERITS (sch1.parent); +)); + +$node_subscriber->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_published (a int); + CREATE TABLE sch1.tab_excluded (a int); + CREATE TABLE sch1.parent (a int); + CREATE TABLE sch1.child (b int) INHERITS (sch1.parent); +)); + +# Basic test: initial sync respects EXCEPT. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_excluded)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: initial sync copies included table'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: initial sync skips excluded table'); + +# DML: only the included table should be replicated. +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (6); + INSERT INTO sch1.tab_excluded VALUES (6); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(6), + 'TABLES IN SCHEMA EXCEPT: DML on included table is replicated'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: DML on excluded table is not replicated'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Inherited tables: excluding the parent (without ONLY) also excludes the child. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.parent)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.child VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.child"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: excluding parent (without ONLY) also excludes child' +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Test that EXCEPT (TABLE ONLY parent) excludes only the parent itself, not its +# child. Truncate child first so rows from the previous test are not copied by +# the initial table sync of the next subscription. +$node_publisher->safe_psql('postgres', 'TRUNCATE sch1.child'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE sch1.child'); +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE ONLY sch1.parent)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.child VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.child"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: ONLY parent in EXCEPT does not exclude child'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Cleanup schema tables before the multi-publication section. +$node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); +$node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); + +# ============================================ +# EXCEPT test cases for TABLES IN SCHEMA with a cross-schema partition +# ============================================ + +# A partition can live in a different schema than its partitioned root. If +# the root is excluded via EXCEPT under its own schema's clause, the exclusion +# must cascade to all its partitions, including those in other schemas. +# +# The partition's own schema is deliberately not published here: naming it +# alongside the EXCEPT clause is rejected, because the clause's reach stops at +# its own schema and the two would then disagree about the partition. +$node_publisher->safe_psql( + 'postgres', qq( + CREATE SCHEMA csch1; + CREATE SCHEMA csch2; + CREATE TABLE csch1.croot(a int) PARTITION BY RANGE(a); + CREATE TABLE csch2.cpart1 PARTITION OF csch1.croot FOR VALUES FROM (0) TO (100); + INSERT INTO csch1.croot VALUES (generate_series(1,5)); +)); + +$node_subscriber->safe_psql( + 'postgres', qq( + CREATE SCHEMA csch1; + CREATE SCHEMA csch2; + CREATE TABLE csch1.croot(a int); + CREATE TABLE csch2.cpart1(a int); +)); + +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION cross_sch_pub FOR TABLES IN SCHEMA csch1 EXCEPT (TABLE csch1.croot) WITH (publish_via_partition_root = false)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION cross_sch_sub CONNECTION '$publisher_connstr' PUBLICATION cross_sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'cross_sch_sub'); + +# Baseline: the root itself, pre-populated with rows before the subscription +# was created, is excluded by its own schema's EXCEPT clause -- initial sync +# must not have copied it. +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM csch1.croot"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: cross-schema partition root is excluded by initial sync' +); + +# Regression case: the partition's own schema (csch2) is separately, fully +# included with no EXCEPT, but the root's exclusion must still cascade to it +# -- initial sync must not have copied the pre-existing rows routed into this +# partition via the root. +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM csch2.cpart1"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: cross-schema partition is excluded by initial sync via cascading root exclusion' +); + +# Insert distinct, identifiable data directly into the partition and verify +# it is not replicated either. +$node_publisher->safe_psql('postgres', + "INSERT INTO csch2.cpart1 VALUES (generate_series(1,5))"); +$node_publisher->wait_for_catchup('cross_sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM csch1.croot"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: cross-schema partition root remains excluded after DML' +); +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM csch2.cpart1"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: cross-schema partition remains excluded after DML via cascading root exclusion' +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION cross_sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION cross_sch_pub'); +$node_publisher->safe_psql('postgres', 'DROP SCHEMA csch1, csch2 CASCADE'); +$node_subscriber->safe_psql('postgres', 'DROP SCHEMA csch1, csch2 CASCADE'); + # ============================================ # Test when a subscription is subscribing to multiple publications # ============================================ @@ -254,6 +459,7 @@ $node_publisher->safe_psql( DROP PUBLICATION tap_pub2; TRUNCATE tab1; )); +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_subscriber->safe_psql('postgres', qq(TRUNCATE tab1)); # OK when a table is excluded by pub1 EXCEPT clause, but it is included by pub2 @@ -282,6 +488,59 @@ $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); +# OK when a table is excluded by the EXCEPT clause of one schema publication, +# but it is included by another publication that publishes the same schema in +# full. Inclusion wins, so the table is replicated. +$node_publisher->safe_psql( + 'postgres', qq( + CREATE SCHEMA msch; + CREATE TABLE msch.tab_excl (a int); + INSERT INTO msch.tab_excl VALUES (1); + CREATE PUBLICATION tap_pub_sch_with_except + FOR TABLES IN SCHEMA msch EXCEPT (TABLE msch.tab_excl); + CREATE PUBLICATION tap_pub_sch_without_except FOR TABLES IN SCHEMA msch; +)); + +$node_subscriber->safe_psql( + 'postgres', qq( + CREATE SCHEMA msch; + CREATE TABLE msch.tab_excl (a int); +)); + +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION tap_sub_multi CONNECTION '$publisher_connstr' PUBLICATION tap_pub_sch_with_except, tap_pub_sch_without_except" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, + 'tap_sub_multi'); + +# The initial table sync must copy the excluded table too, because +# tap_pub_sch_without_except publishes it. +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM msch.tab_excl"); +is($result, qq(1), + 'initial sync copies a table excluded by one publication but included by another' +); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO msch.tab_excl VALUES (2); +)); +$node_publisher->wait_for_catchup('tap_sub_multi'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM msch.tab_excl"); +is($result, qq(2), + 'DML on a table excluded by one publication but included by another is replicated' +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub_multi'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub_sch_with_except'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub_sch_without_except'); +$node_publisher->safe_psql('postgres', 'DROP SCHEMA msch CASCADE'); +$node_subscriber->safe_psql('postgres', 'DROP SCHEMA msch CASCADE'); + $node_publisher->stop('fast'); done_testing(); -- 2.55.0
^ permalink raw reply [nested|flat] 196+ messages in thread

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-18 08:04  Peter Smith <smithpb2250@gmail.com>
  parent: vignesh C <vignesh21@gmail.com>
  1 sibling, 2 replies; 196+ messages in thread

From: Peter Smith @ 2026-08-18 08:04 UTC (permalink / raw)
  To: vignesh C <vignesh21@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Nisha Moond <nisha.moond412@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

Hi Vignesh/Nisha,

IMO, it feels like these patches are doing too much work trying to
protect the user from themselves, and it is even making some
combinations difficult to specify.

Also, there is a lot of logic and many lines of code now just for
checking publication command "inconsistencies".

~

Anyway, I wanted to step back for a moment to reconsider if all this
jumping through hoops is really necessary... I'm not sure that it is.

I've been wondering about something much simpler. There are just 2 rules.

RULE 0:  Assume the user knows what they are doing!

RULE 1:  Fine-grained clauses take precedence (so anything the user
says about a TABLE takes precedence over whatever they say about a
SCHEMA)

e.g.

FOR TABLES IN SCHEMA s1, TABLE s1.t1; -- OK

⁠FOR TABLES IN SCHEMA s1 EXCEPT(TABLE s1.t1), s1; -- FAIL this is a
self-conflict because the same schema is specified 2 ways

⁠FOR TABLES IN SCHEMA s1 EXCEPT(TABLE s1.t1), TABLE s1.t1; -- FAIL
this is a self-conflict because the same table is excluded/include

FOR TABLES IN SCHEMA s1 EXCEPT(TABLE s1.root), s2 -- OK the tree
exclusion takes precedence, so s2.part is also excluded even though
rest of schema s2 is included

⁠FOR TABLES IN SCHEMA s1 EXCEPT(TABLE parent), s2 -- OK the hierarchy
exclusions (default *) take precedence so s2.child also excluded end
though the rest of schema s2 is included

FOR TABLES IN SCHEMA s1 EXCEPT(TABLE s1.parent), TABLE s2.child -- OK,
hierarchy exclusion would normally exclude s2.child too, but the user
says they want to keep it so it stays

FOR TABLES IN SCHEMA s1 EXCEPT(TABLE ONLY s1.parent), s2 -- OK, the
hierarchy exclusion does not go any further, so s2.child is published
along with everything else in s2.
⁠
~~

- Won't this reduce the amount of implementation code needed?
- Won't this simple precedence rule be easily explained/documented?

Thoughts?

Of course, I might have overlooked some fatal flaw, so feel free to
pop this thought bubble.

======
Kind Regards,
Peter Smith.
Fujitsu Austalia






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-18 13:27  vignesh C <vignesh21@gmail.com>
  parent: vignesh C <vignesh21@gmail.com>
  1 sibling, 0 replies; 196+ messages in thread

From: vignesh C @ 2026-08-18 13:27 UTC (permalink / raw)
  To: shveta malik <shveta.malik@gmail.com>; +Cc: Nisha Moond <nisha.moond412@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Peter Smith <smithpb2250@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Tue, 18 Aug 2026 at 10:24, vignesh C <vignesh21@gmail.com> wrote:
>
> The v28 version of the attached patch handles the changes to throw an
> error when a partition table is both included and excluded through an
> EXCEPT clause, keeping the behavior consistent with inheritance
> tables.

Few comments:
1) we are throwing this error at AlterPublicationSchemaExceptTables
which can be done from the grammar that way it need not process many
thing and then throw an error so late:
+       /*
+        * Dropping a schema from a publication removes all its EXCEPT
entries via
+        * cascade. The concept of "drop all schema tables from the publication
+        * EXCEPT these ones" is not supported.
+        */
+       if (stmt->action == AP_DropObjects)
+               ereport(ERROR,
+                               (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+                                errmsg("EXCEPT clause is not
supported with DROP in ALTER PUBLICATION")));

Attached a patch to handle this from gram.y file.

2) WITH options tab completion missing for:
create publication pub1 for tables in schema sch1 except ( table sch1.t1 )

3) CheckExceptConflicts prototype appears twice:
 static void CheckSchemaListNotExcluded(Oid pubid, List *schemaidlist);
+static void CheckExceptConflicts(Oid pubid, List *except_rels,
+                                                                List
*cross_schema_children,
+                                                                List
*explicitrelids, List *pubschemas,
+                                                                bool
existing_except_kept);
 static void PublicationAddExceptTables(Oid pubid, List *except_pubtables,

 and

 -
                  List *except_rels);
+
                 List *except_rels,
+
                 bool existing_except_kept);
+static void CheckExceptConflicts(Oid pubid, List *except_rels,
+                                                                List
*cross_schema_children,
+                                                                List
*explicitrelids, List *pubschemas,
+                                                                bool
existing_except_kept);

4) We have the following check in 0002 patch:
    /*
     * XXX EXCEPT with SET is not currently implemented.  Workaround: DROP and
     * re-ADD the schema with the desired EXCEPT list.
     */
    if (stmt->action == AP_SetObjects)
        ereport(ERROR,
                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                 errmsg("EXCEPT clause is not supported with SET in
ALTER PUBLICATION"),
                 errhint("Drop and re-add the schema with the desired
EXCEPT list.")));

Let's move this check to 0001 patch

5) Similarly we should add a similar check for ALTER PUBLICATION ...
ADD TABLES IN SCHEMA EXCEPT to throw an error from the first patch.

6) code compiles without this include, we can remove this:
inline patch 1: src/backend/parser/gram.y (+1/-0 lines) download inline-1.patchdiff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y index 17035fb4d15..14520a5ccab 100644 --- a/src/backend/parser/gram.y +++ b/src/backend/parser/gram.y @@ -58,6 +58,7 @@ #include "nodes/makefuncs.h" #include "nodes/nodeFuncs.h" #include "parser/parser.h" +#include "utils/builtins.h" #include "utils/datetime.h" #include "utils/xml.h"
7) Here the publicationcmds.h should be included before repack.h to maintain the ordering: #include "commands/extension.h" #include "commands/repack.h" +#include "commands/publicationcmds.h" #include "commands/sequence.h" 8) We can keep the same parameter ordering in both AlterPublicationSchemas and AlterPublicationSchemaExceptTables functions, except_pubtables and schemaidlist are placed differently in both: +static void AlterPublicationSchemas(AlterPublicationStmt *stmt, + HeapTuple tup, List *schemaidlist, + List *except_pubtables); +static void AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, + HeapTuple tup, + List *except_pubtables, + List *schemaidlist); Regards, Vignesh Patches and attachments: download all (2 files, .tar.gz)
Drop_Tables_throw_error_from_parser.patch (application/octet-stream, 3.8K) download diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 0f9790c4c0f..24a4d81588c 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -2095,15 +2095,8 @@ AlterPublicationSchemaExceptTables(AlterPublicationStmt *stmt, if (schemaidlist == NIL && !is_schema_publication(pubid)) return; - /* - * Dropping a schema from a publication removes all its EXCEPT entries via - * cascade. The concept of "drop all schema tables from the publication - * EXCEPT these ones" is not supported. - */ - if (stmt->action == AP_DropObjects) - ereport(ERROR, - (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"))); + /* DROP takes no EXCEPT clause; preprocess_pubobj_list() rejects that */ + Assert(stmt->action != AP_DropObjects); if (stmt->action == AP_AddObjects) { diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y index 14520a5ccab..f20efde5f85 100644 --- a/src/backend/parser/gram.y +++ b/src/backend/parser/gram.y @@ -207,7 +207,7 @@ static void preprocess_pub_all_objtype_list(List *all_objects_list, bool *all_tables, bool *all_sequences, core_yyscan_t yyscanner); -static void preprocess_pubobj_list(List *pubobjspec_list, +static void preprocess_pubobj_list(List *pubobjspec_list, bool allow_except, core_yyscan_t yyscanner); static Node *makeRecursiveViewSelect(char *relname, List *aliases, Node *query); @@ -11315,7 +11315,7 @@ CreatePublicationStmt: n->pubname = $3; n->options = $6; n->pubobjects = (List *) $5; - preprocess_pubobj_list(n->pubobjects, yyscanner); + preprocess_pubobj_list(n->pubobjects, true, yyscanner); $$ = (Node *) n; } ; @@ -11506,7 +11506,7 @@ AlterPublicationStmt: n->pubname = $3; n->pubobjects = $5; - preprocess_pubobj_list(n->pubobjects, yyscanner); + preprocess_pubobj_list(n->pubobjects, true, yyscanner); n->action = AP_AddObjects; n->for_all_tables = false; $$ = (Node *) n; @@ -11517,7 +11517,7 @@ AlterPublicationStmt: n->pubname = $3; n->pubobjects = $5; - preprocess_pubobj_list(n->pubobjects, yyscanner); + preprocess_pubobj_list(n->pubobjects, true, yyscanner); n->action = AP_SetObjects; n->for_all_tables = false; $$ = (Node *) n; @@ -11540,7 +11540,7 @@ AlterPublicationStmt: n->pubname = $3; n->pubobjects = $5; - preprocess_pubobj_list(n->pubobjects, yyscanner); + preprocess_pubobj_list(n->pubobjects, false, yyscanner); n->action = AP_DropObjects; n->for_all_tables = false; $$ = (Node *) n; @@ -20879,7 +20879,8 @@ preprocess_pub_all_objtype_list(List *all_objects_list, List **pubobjects, * output list once the schema OID is known. */ static void -preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) +preprocess_pubobj_list(List *pubobjspec_list, bool allow_except, + core_yyscan_t yyscanner) { ListCell *cell; PublicationObjSpec *pubobj; @@ -20903,6 +20904,18 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) if (pubobj->pubobjtype == PUBLICATIONOBJ_CONTINUATION) pubobj->pubobjtype = prevobjtype; + /* + * Dropping a schema from a publication removes all of its EXCEPT + * entries along with it. The concept of "drop all schema tables from + * the publication EXCEPT these ones" is not supported, so DROP takes + * no EXCEPT clause. + */ + if (!allow_except && pubobj->except_tables != NIL) + ereport(ERROR, + errcode(ERRCODE_SYNTAX_ERROR), + errmsg("EXCEPT clause is not supported with DROP in ALTER PUBLICATION"), + parser_errposition(pubobj->location)); + if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLE) { /* EXCEPT is not valid for table objects */
^ permalink raw reply [nested|flat] 196+ messages in thread

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-19 03:26  Nisha Moond <nisha.moond412@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  1 sibling, 0 replies; 196+ messages in thread

From: Nisha Moond @ 2026-08-19 03:26 UTC (permalink / raw)
  To: shveta malik <shveta.malik@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; vignesh C <vignesh21@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Fri, Aug 14, 2026 at 11:29 AM shveta malik <shveta.malik@gmail.com> wrote:
>
> On Thu, Aug 13, 2026 at 12:52 PM Peter Smith <smithpb2250@gmail.com> wrote:
> >
> >
> > 2b.
> > /In the partition case/For partitions/
> >
> > AFAICT this case is referring to something like:  "FOR TABLE part,
> > TABLES IN SCHEMA EXCEPT (part_root)"
> >
> > But, isn't that just a variation of the 1st case issue? e.g. where
> > table "part" is not yet visible for later lookup of "root", then you
> > wont be able to check integrity of the partition tree regardless of
> > the up/down traversal logic, so I wasn't sure why this 2nd case was
> > separately mentioned at all.
>
> The second point is different from the first. Consider this case:
>
> CREATE PUBLICATION pub1 FOR s2.tab_part;
> ALTER PUBLICATION pub1 ADD TABLES IN SCHEMA s2 EXCEPT (TABLE tab_root);
>
> Here, the partition entry in pg_publication_rel is visible to the
> second command in publication_add_relation() and in
> check_publication_add_relation(). But the checks there are not
> sufficient to identify the error. If we try to detect the error while
> adding tab_root in publication_add_relation(),
> we would need to perform a full descendant search to determine whether
> any of its descendants are already present in pg_publication_rel. This
> downward traversal is what we are trying to avoid in
> publication_add_relation(). Geenrally we rely on ancestor-lookup and
> we want to stick to that instead of introducing a new logic.
> Thus the logic in CheckExceptNotInTableList() is needed here. It reads
> all explicitly added entries from pg_publication_rel, looks up their
> ancestors to find the root, and checks the EXCEPT entries against that
> root.
>
> This is my understanding, let's wait for Nisha's comments as well.
>

Yes, your understanding is correct, that is precisely the reason.

> I feel the comment about the second case should be moved to patch002,
> where it actually makes sense and explains why it is needed even after
> point 1.
>

Agreed. I’ll move the 2nd point to patch-002, as it relates to the
ALTER PUBLICATION command.

--
Thanks,
Nisha





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-19 03:26  Nisha Moond <nisha.moond412@gmail.com>
  parent: Peter Smith <smithpb2250@gmail.com>
  1 sibling, 0 replies; 196+ messages in thread

From: Nisha Moond @ 2026-08-19 03:26 UTC (permalink / raw)
  To: Peter Smith <smithpb2250@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; vignesh C <vignesh21@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Fri, Aug 14, 2026 at 12:25 PM Peter Smith <smithpb2250@gmail.com> wrote:
>
> On Fri, Aug 14, 2026 at 3:59 PM shveta malik <shveta.malik@gmail.com> wrote:
> >
> > On Thu, Aug 13, 2026 at 12:52 PM Peter Smith <smithpb2250@gmail.com> wrote:
> > >
> > >
> > > 2b.
> > > /In the partition case/For partitions/
> > >
> > > AFAICT this case is referring to something like:  "FOR TABLE part,
> > > TABLES IN SCHEMA EXCEPT (part_root)"
> > >
> > > But, isn't that just a variation of the 1st case issue? e.g. where
> > > table "part" is not yet visible for later lookup of "root", then you
> > > wont be able to check integrity of the partition tree regardless of
> > > the up/down traversal logic, so I wasn't sure why this 2nd case was
> > > separately mentioned at all.
> >
> > The second point is different from the first. Consider this case:
> >
> > CREATE PUBLICATION pub1 FOR s2.tab_part;
> > ALTER PUBLICATION pub1 ADD TABLES IN SCHEMA s2 EXCEPT (TABLE tab_root);
> >
> > Here, the partition entry in pg_publication_rel is visible to the
> > second command in publication_add_relation() and in
> > check_publication_add_relation(). But the checks there are not
> > sufficient to identify the error. If we try to detect the error while
> > adding tab_root in publication_add_relation(),
> > we would need to perform a full descendant search to determine whether
> > any of its descendants are already present in pg_publication_rel. This
> > downward traversal is what we are trying to avoid in
> > publication_add_relation(). Geenrally we rely on ancestor-lookup and
> > we want to stick to that instead of introducing a new logic.
> > Thus the logic in CheckExceptNotInTableList() is needed here. It reads
> > all explicitly added entries from pg_publication_rel, looks up their
> > ancestors to find the root, and checks the EXCEPT entries against that
> > root.
> >
> > This is my understanding, let's wait for Nisha's comments as well.
> >
>
> Shveta, thanks for the explanation.
>
> In hindsight, my confusion was due to the comment wording -- the 1st
> case was referring to "a single command", and the 2nd case just said,
> "root may be added to the EXCEPT list later."....
> I misinterpreted "later" as meaning later in the *same* command, like:
> CREATE PUBLICATION pub1 FOR TABLE s2.tab_part, TABLES IN SHEMA s2
> EXCEPT(TABLE tab_root);
> which is entirely a different horse....
>
> Perhaps the comments for these tricky cases should include tiny SQL
> examples (just like you wrote) to clarify exactly what the comment is
> trying to say.
>

Okay, I'll add the ALTER PUB example to the comment in the next version.

--
Thanks,
Nisha





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-19 03:36  Nisha Moond <nisha.moond412@gmail.com>
  parent: Peter Smith <smithpb2250@gmail.com>
  0 siblings, 0 replies; 196+ messages in thread

From: Nisha Moond @ 2026-08-19 03:36 UTC (permalink / raw)
  To: Peter Smith <smithpb2250@gmail.com>; +Cc: vignesh C <vignesh21@gmail.com>; shveta malik <shveta.malik@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Tue, Aug 18, 2026 at 9:29 AM Peter Smith <smithpb2250@gmail.com> wrote:
>
> Some review comments for patch v27-0001.
>
> (Have not finished looking at the other patches yet)
>
> ======
> Commit Message
>
> 1.
> What are the implemented rules for parent/child (inherited) tables?
> Shouldn't the commit message have something to say about those?
> Perhaps it is covered by "A table cannot be both explicitly published
> and excluded in the same statement", but even so I still think the
> rule for inherited tables should be mentioned for clarity.
>
...

Hi Peter, thanks for the review.
The code handling partitions and inherited tables is not yet fully
stable and may change as we address some optimizations and open bugs.
I’ll revisit these comments once the code stabilizes and then
incorporate any improvements or rewording suggestions at that point.

--
Thanks,
Nisha





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-19 03:44  shveta malik <shveta.malik@gmail.com>
  parent: Peter Smith <smithpb2250@gmail.com>
  1 sibling, 0 replies; 196+ messages in thread

From: shveta malik @ 2026-08-19 03:44 UTC (permalink / raw)
  To: Peter Smith <smithpb2250@gmail.com>; +Cc: vignesh C <vignesh21@gmail.com>; Nisha Moond <nisha.moond412@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; shveta malik <shveta.malik@gmail.com>

On Tue, Aug 18, 2026 at 1:34 PM Peter Smith <smithpb2250@gmail.com> wrote:
>
> Hi Vignesh/Nisha,
>
> IMO, it feels like these patches are doing too much work trying to
> protect the user from themselves, and it is even making some
> combinations difficult to specify.
>
> Also, there is a lot of logic and many lines of code now just for
> checking publication command "inconsistencies".

After looking at v28, which has introduced new error scenarios as
concluded earlier, I completely agree that the code has become quite
complicated, especially when identifying Case 2 mentioned in [1]
(cross schema references when both schemas are mentioned in
publication)

[1]: https://www.postgresql.org/message-id/CAJpy0uAqvPBbQGfBmXVn2iugtTkw4uS7_H%3DXcGuzdgPNMsQOag%40mail.g...

> ~
>
> Anyway, I wanted to step back for a moment to reconsider if all this
> jumping through hoops is really necessary... I'm not sure that it is.

Yeah, looking at the code complexity, I would also like to step back
and rethink.

> I've been wondering about something much simpler. There are just 2 rules.
>
> RULE 0:  Assume the user knows what they are doing!
>
> RULE 1:  Fine-grained clauses take precedence (so anything the user
> says about a TABLE takes precedence over whatever they say about a
> SCHEMA)
>
> e.g.
>
> FOR TABLES IN SCHEMA s1, TABLE s1.t1; -- OK
>

Okay. Current behavior is the same.

> ⁠FOR TABLES IN SCHEMA s1 EXCEPT(TABLE s1.t1), s1; -- FAIL this is a
> self-conflict because the same schema is specified 2 ways

Okay. Current behavior is the same.

> ⁠FOR TABLES IN SCHEMA s1 EXCEPT(TABLE s1.t1), TABLE s1.t1; -- FAIL
> this is a self-conflict because the same table is excluded/include

Okay. Current behavior is the same.

> FOR TABLES IN SCHEMA s1 EXCEPT(TABLE s1.root), s2 -- OK the tree
> exclusion takes precedence, so s2.part is also excluded even though
> rest of schema s2 is included

Okay. Currently, v28 emits an error for the contradiction that
s2.child is excluded through the hierarchy rule but included through
schema inclusion. And emitting that error required introducing a lot
of code complexity in v28. So we can think about changing the
behaviour to accept rather than emit an error.

> ⁠FOR TABLES IN SCHEMA s1 EXCEPT(TABLE parent), s2 -- OK the hierarchy
> exclusions (default *) take precedence so s2.child also excluded end
> though the rest of schema s2 is included

Same comment as above.

> FOR TABLES IN SCHEMA s1 EXCEPT(TABLE s1.parent), TABLE s2.child -- OK,
> hierarchy exclusion would normally exclude s2.child too, but the user
> says they want to keep it so it stays

Okay. Currently, it emits an error for the contradiction that s2.child
is excluded through the hierarchy rule but included explicitly. No
code complexity is involved in identifying this case, nor is it a new
error addition in v28. But if we plan to change the behaviour for the
case 'FOR TABLES IN SCHEMA s1 EXCEPT(TABLE parent), s2 ', we can
change the behaviour of this command too, so that both are in sync
i.e. no error on  such contradictions. The only thing to notice here
is that when 'pub_via_parition_root' is  true, even though user has
included 's2.child' explicitly in publication, s2.child will still not
be published. But this case will not be any different from existing
case on HEAD where parition alone is included in publication with
publish_via_partition_root=true. Example:

create publication pub1 for table s2.part with
(publish_via_partition_root = true);


> FOR TABLES IN SCHEMA s1 EXCEPT(TABLE ONLY s1.parent), s2 -- OK, the
> hierarchy exclusion does not go any further, so s2.child is published
> along with everything else in s2.

Okay. Current behavior is the same.

> ~~
>
> - Won't this reduce the amount of implementation code needed?
> - Won't this simple precedence rule be easily explained/documented?

Yes, it will.

> Thoughts?
>

Given the code complexity of the error scenarios added in v28, I think
it is okay to take the approach to accept these scenarios rather than
emitting errors. But we can wait for others' opinion on this.

thanks
Shveta






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-19 10:17  vignesh C <vignesh21@gmail.com>
  parent: Peter Smith <smithpb2250@gmail.com>
  1 sibling, 2 replies; 196+ messages in thread

From: vignesh C @ 2026-08-19 10:17 UTC (permalink / raw)
  To: Peter Smith <smithpb2250@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Nisha Moond <nisha.moond412@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Tue, 18 Aug 2026 at 13:34, Peter Smith <smithpb2250@gmail.com> wrote:
>
> Hi Vignesh/Nisha,
>
> IMO, it feels like these patches are doing too much work trying to
> protect the user from themselves, and it is even making some
> combinations difficult to specify.
>
> Also, there is a lot of logic and many lines of code now just for
> checking publication command "inconsistencies".

I still feel we should throw the error at CREATE PUBLICATION itself.
That would make the conflict clear to the user and allow them to
modify the publication accordingly. Otherwise, in a conflicting case
like the following, it may be unclear whether the table will actually
be published:
CREATE TABLE s1.parent (a int);
CREATE TABLE s2.child (b int) INHERITS (s1.parent);
CREATE PUBLICATION pub1 FOR TABLES IN SCHEMA s1 EXCEPT (TABLE s1.parent), s2;

Here, it may not be obvious whether s2.child will be published because
schema s2 is included, or whether it will be skipped because its
parent s1.parent is specified in the EXCEPT clause.

I have tried to simplify the patch. The new version now only has two
changes to detect the new conflicts:
a) GetExceptCrossSchemaDescendants - Collects descendants of the
EXCEPT entries that reside outside the schema of the corresponding
TABLES IN SCHEMA clause.
b) Add few additional checks to the existing
CheckExceptConflicts(renamed from CheckExceptNotInTableList)
Checks whether any of these cross-schema descendants are also being
published, either explicitly or through another TABLES IN SCHEMA
clause, and throws an error if they are.

Please have a look and let me know whether the v29 version is simpler.

Regards,
Vignesh

Attachments:

v29-0001-Support-EXCEPT-clause-for-schema-level-publicati.patch (application/octet-stream, 107.2K) download From 10ae1e8c312e9e06d385e284f5c4cb970c9bd3b9 Mon Sep 17 00:00:00 2001 From: Vignesh C <c_vigneshwaran@apple.com> Date: Tue, 18 Aug 2026 08:51:08 +0530 Subject: [PATCH v29] Support EXCEPT clause for schema-level publications Extend table exclusion support in publications to allow specific tables to be excluded from schema-level publications using an EXCEPT clause in CREATE PUBLICATION. Supported syntax: CREATE PUBLICATION pub FOR TABLES IN SCHEMA s EXCEPT (TABLE t1,...); This reuses the existing opt_pub_except_clause grammar and stores excluded tables as pg_publication_rel entries with prexcept = true, requiring no catalog changes. NOTES - Each EXCEPT clause applies only to its own schema; cross-schema references are rejected. - A schema may appear only once with an EXCEPT clause. - A table cannot be both explicitly published and excluded in the same statement. - Only partition roots may be excluded. Excluding a root excludes the entire partition tree, including partitions in other published schemas. Individual partitions cannot be added while their root is excluded, and ATTACH PARTITION is rejected if the attached table is excluded. - ALTER TABLE ... SET SCHEMA removes schema-scoped exclusions, matching existing schema-publication behavior. - psql describe output and tab completion are updated to support the new syntax. --- src/backend/catalog/pg_publication.c | 274 +++++++++++-- src/backend/commands/publicationcmds.c | 420 +++++++++++++++++++- src/backend/commands/tablecmds.c | 24 +- src/backend/parser/gram.y | 27 +- src/backend/replication/pgoutput/pgoutput.c | 37 +- src/backend/utils/cache/relcache.c | 26 +- src/bin/psql/describe.c | 44 +- src/bin/psql/tab-complete.in.c | 35 +- src/include/catalog/pg_publication.h | 3 + src/include/commands/publicationcmds.h | 2 + src/include/nodes/parsenodes.h | 5 + src/test/regress/expected/publication.out | 388 +++++++++++++++++- src/test/regress/sql/publication.sql | 241 ++++++++++- src/test/subscription/t/037_except.pl | 263 +++++++++++- 14 files changed, 1697 insertions(+), 92 deletions(-) diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c index 12af7d15536..81e4166cfee 100644 --- a/src/backend/catalog/pg_publication.c +++ b/src/backend/catalog/pg_publication.c @@ -54,7 +54,7 @@ typedef struct * error if not. */ static void -check_publication_add_relation(PublicationRelInfo *pri) +check_publication_add_relation(PublicationRelInfo *pri, Oid pubid) { Relation targetrel = pri->relation; const char *relname; @@ -71,12 +71,51 @@ check_publication_add_relation(PublicationRelInfo *pri) errormsg = gettext_noop("cannot add relation \"%s\" to publication"); } - /* If in EXCEPT clause, must be root partitioned table */ - if (pri->except && targetrel->rd_rel->relispartition) - ereport(ERROR, - (errcode(ERRCODE_INVALID_PARAMETER_VALUE), - errmsg(errormsg, relname), - errdetail("This operation is not supported for individual partitions."))); + /* + * A partition cannot be added to a publication if its partition root is + * excluded by the publication. We follow the rule that excluding a + * partition root means that the entire partition tree is excluded. Thus, + * check whether the root is in the EXCEPT clause and reject adding the + * individual partition to the publication. + */ + if (targetrel->rd_rel->relispartition) + { + List *ancestors; + + if (pri->except) + { + /* If in EXCEPT clause, must be root partitioned table */ + ereport(ERROR, + (errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg(errormsg, relname), + errdetail("This operation is not supported for individual partitions."))); + } + + /* + * ancestors is NIL for a partition with a pending DETACH + * CONCURRENTLY, in which case there is no root to check. + */ + ancestors = get_partition_ancestors(RelationGetRelid(targetrel)); + if (ancestors != NIL) + { + Oid root = llast_oid(ancestors); + bool root_except; + + if (CheckPublicationRelEntry(pubid, root, &root_except) && root_except) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("cannot add partition \"%s\" to publication \"%s\"", + RelationGetQualifiedRelationName(targetrel), + get_publication_name(pubid, false)), + errdetail("Partition root \"%s\" is named in the publication's EXCEPT clause for schema \"%s\".", + quote_qualified_identifier(get_namespace_name(get_rel_namespace(root)), + get_rel_name(root)), + get_namespace_name(get_rel_namespace(root))), + errhint("Change the EXCEPT clause using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT.")); + } + + list_free(ancestors); + } /* Must be a regular or partitioned table */ if (RelationGetForm(targetrel)->relkind != RELKIND_RELATION && @@ -320,8 +359,7 @@ is_schema_publication(Oid pubid) } /* - * Returns true if the publication has explicitly included relation (i.e., - * not marked as EXCEPT). + * Returns true if the publication has a FOR TABLE clause. */ bool is_table_publication(Oid pubid) @@ -341,19 +379,23 @@ is_table_publication(Oid pubid) scan = systable_beginscan(pubrelsrel, PublicationRelPrpubidIndexId, true, NULL, 1, &scankey); - tup = systable_getnext(scan); - if (HeapTupleIsValid(tup)) - { - Form_pg_publication_rel pubrel; - - pubrel = (Form_pg_publication_rel) GETSTRUCT(tup); - /* - * For any publication, pg_publication_rel contains either only EXCEPT - * entries or only explicitly included tables. Therefore, examining - * the first tuple is sufficient to determine table inclusion. - */ - result = !pubrel->prexcept; + /* + * A publication can have both explicitly included (prexcept = false) and + * EXCEPT (prexcept = true) rows for the same pubid. For example: + * + * CREATE PUBLICATION pub1 FOR TABLE s1.t1, TABLES IN SCHEMA s2 EXCEPT + * (TABLE s2.t1); + * + * Scan until we find an explicitly included row. + */ + while (HeapTupleIsValid(tup = systable_getnext(scan))) + { + if (!((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept) + { + result = true; + break; + } } systable_endscan(scan); @@ -362,6 +404,27 @@ is_table_publication(Oid pubid) return result; } +/* + * Check whether a pg_publication_rel row exists for (pubid, relid); if so, + * set *is_except to its prexcept flag. + */ +bool +CheckPublicationRelEntry(Oid pubid, Oid relid, bool *is_except) +{ + HeapTuple tup; + + tup = SearchSysCache2(PUBLICATIONRELMAP, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (!HeapTupleIsValid(tup)) + return false; + + *is_except = ((Form_pg_publication_rel) GETSTRUCT(tup))->prexcept; + ReleaseSysCache(tup); + + return true; +} + /* * Returns true if the relation has column list associated with the * publication, false otherwise. @@ -457,11 +520,26 @@ GetPubPartitionOptionRelations(List *result, PublicationPartOpt pub_partopt, * ancestor is at the end of the list. */ Oid -GetTopMostAncestorInPublication(Oid puboid, List *ancestors, int *ancestor_level) +GetTopMostAncestorInPublication(Oid puboid, List *ancestors, + int *ancestor_level) { ListCell *lc; Oid topmost_relid = InvalidOid; int level = 0; + bool root_except; + + if (ancestors == NIL) + return InvalidOid; + + /* + * If the partition root is excluded from this publication via an EXCEPT + * clause, the partition is not published through this publication, so + * return InvalidOid. Since only partition roots can appear in an EXCEPT + * clause, the root is the only ancestor worth a catalog lookup. + */ + if (CheckPublicationRelEntry(puboid, llast_oid(ancestors), &root_except) && + root_except) + return InvalidOid; /* * Find the "topmost" ancestor that is in this publication. @@ -548,6 +626,7 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, List *relids = NIL; int i; bool inval_except_table; + bool is_except; rel = table_open(PublicationRelRelationId, RowExclusiveLock); @@ -556,21 +635,46 @@ publication_add_relation(Oid pubid, PublicationRelInfo *pri, * duplicates, it's here just to provide nicer error message in common * case. The real protection is the unique key on the catalog. */ - if (SearchSysCacheExists2(PUBLICATIONRELMAP, ObjectIdGetDatum(relid), - ObjectIdGetDatum(pubid))) + if (CheckPublicationRelEntry(pubid, relid, &is_except)) { table_close(rel, RowExclusiveLock); - if (if_not_exists) + /* + * if_not_exists asks us to skip an entry that is already present. An + * existing entry of the opposite kind is not the entry the caller + * asked for, though: skipping it would silently leave the relation + * excluded when the caller wanted it published, or published when the + * caller wanted it excluded. So only skip when the existing entry is + * of the same kind, and report the conflict otherwise. + */ + if (if_not_exists && is_except == pri->except) return InvalidObjectAddress; - ereport(ERROR, - (errcode(ERRCODE_DUPLICATE_OBJECT), - errmsg("relation \"%s\" is already a member of publication \"%s\"", - RelationGetRelationName(targetrel), pub->name))); + if (is_except) + ereport(ERROR, + (errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("cannot add table \"%s\" to publication \"%s\"", + RelationGetQualifiedRelationName(targetrel), + pub->name), + errdetail("The table is named in the publication's EXCEPT clause for schema \"%s\".", + get_namespace_name(RelationGetNamespace(targetrel))), + errhint("Change the EXCEPT clause using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT."))); + else if (pri->except) + ereport(ERROR, + (errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("cannot exclude table \"%s\" from publication \"%s\"", + RelationGetQualifiedRelationName(targetrel), + pub->name), + errdetail("The table is a member of the publication."), + errhint("Remove the table from the publication using ALTER PUBLICATION ... DROP TABLE."))); + else + ereport(ERROR, + (errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("relation \"%s\" is already a member of publication \"%s\"", + RelationGetRelationName(targetrel), pub->name))); } - check_publication_add_relation(pri); + check_publication_add_relation(pri, pubid); /* Validate and translate column names into a Bitmapset of attnums. */ attnums = pub_collist_validate(pri->relation, pri->columns); @@ -996,16 +1100,36 @@ GetIncludedPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) * Gets list of table oids that were specified in the EXCEPT clause for a * publication. * - * This should only be used FOR ALL TABLES publications. + * This is used for FOR ALL TABLES and FOR TABLES IN SCHEMA publications, + * both of which support EXCEPT TABLE. */ List * GetExcludedPublicationTables(Oid pubid, PublicationPartOpt pub_partopt) { - Assert(GetPublication(pubid)->alltables); + Assert(GetPublication(pubid)->alltables || is_schema_publication(pubid)); return get_publication_relations(pubid, pub_partopt, true); } +/* + * Gets list of relation oids associated with a publication, covering both + * explicitly included relations and relations named in an EXCEPT clause. + * + * This is used by ALTER PUBLICATION ... SET to replaces a publication's entire + * relation list. + */ +List * +GetPublicationRelationsOfAnyKind(Oid pubid, PublicationPartOpt pub_partopt) +{ + List *result; + + result = get_publication_relations(pubid, pub_partopt, false); + + return list_concat_unique_oid(result, + get_publication_relations(pubid, pub_partopt, + true)); +} + /* * Gets list of publication oids for publications marked as FOR ALL TABLES. */ @@ -1246,22 +1370,63 @@ GetSchemaPublicationRelations(Oid schemaid, PublicationPartOpt pub_partopt) /* * Gets the list of all relations published by FOR TABLES IN SCHEMA - * publication. + * publication, excluding any tables listed in EXCEPT clauses. */ List * GetAllSchemaPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt) { List *result = NIL; List *pubschemalist = GetPublicationSchemas(pubid); + List *except_relids = NIL; ListCell *cell; + /* get the list of tables excluded via EXCEPT TABLE for this publication */ + if (pubschemalist != NIL) + except_relids = GetExcludedPublicationTables(pubid, pub_partopt); + foreach(cell, pubschemalist) { Oid schemaid = lfirst_oid(cell); List *schemaRels = NIL; schemaRels = GetSchemaPublicationRelations(schemaid, pub_partopt); - result = list_concat(result, schemaRels); + + if (except_relids != NIL) + { + /* filter out any tables that appear in the EXCEPT list */ + foreach_oid(relid, schemaRels) + { + bool excluded = list_member_oid(except_relids, relid); + + /* + * A partition whose root is excluded from the publication is + * also excluded, even if the partition itself lives in a + * different (included) schema. Only the topmost root of a + * partition hierarchy can ever appear in EXCEPT (see + * check_publication_add_relation()), so it's enough to check + * the last element of the ancestors list, rather than walking + * the whole chain. + */ + if (!excluded && get_rel_relispartition(relid)) + { + List *ancestors = get_partition_ancestors(relid); + + if (ancestors != NIL) + { + excluded = list_member_oid(except_relids, + llast_oid(ancestors)); + list_free(ancestors); + } + } + + if (!excluded) + result = lappend_oid(result, relid); + } + + list_free(schemaRels); + } + else + result = list_concat(result, schemaRels); } return result; @@ -1338,6 +1503,7 @@ is_table_publishable_in_publication(Oid relid, Publication *pub) { bool relispartition; List *ancestors = NIL; + bool is_except; /* * For non-pubviaroot publications, a partitioned table is never the @@ -1385,6 +1551,10 @@ is_table_publishable_in_publication(Oid relid, Publication *pub) */ /* + * If the partition root is excluded via the EXCEPT clause, the partition + * is never considered to be published through this publication. Check + * this before checking whether an ancestor is published. + * * If an ancestor is published, the partition's status depends on * publish_via_partition_root value. * @@ -1394,20 +1564,38 @@ is_table_publishable_in_publication(Oid relid, Publication *pub) * If it's false, the partition is covered by its ancestor's presence in * the publication, it should be included (return true). */ - if (relispartition && - OidIsValid(GetTopMostAncestorInPublication(pub->oid, ancestors, NULL))) - return !pub->pubviaroot; + if (relispartition) + { + /* + * ancestors can be NIL for a partition whose DETACH ... CONCURRENTLY + * is pending, in which case there is no ancestor to check. + */ + if (ancestors != NIL && + CheckPublicationRelEntry(pub->oid, llast_oid(ancestors), &is_except) && + is_except) + return false; + + if (OidIsValid(GetTopMostAncestorInPublication(pub->oid, ancestors, NULL))) + return !pub->pubviaroot; + } /* * Check whether the table is explicitly published via pg_publication_rel * or pg_publication_namespace. + * + * A pg_publication_rel row with prexcept=true means the table is + * explicitly excluded via EXCEPT and must not be reported as published, + * even if its schema is otherwise included. A row with prexcept=false + * means it is explicitly included. If no pg_publication_rel row exists, + * the table is published iff its schema appears in + * pg_publication_namespace. */ - return (SearchSysCacheExists2(PUBLICATIONRELMAP, - ObjectIdGetDatum(relid), - ObjectIdGetDatum(pub->oid)) || - SearchSysCacheExists2(PUBLICATIONNAMESPACEMAP, - ObjectIdGetDatum(get_rel_namespace(relid)), - ObjectIdGetDatum(pub->oid))); + if (CheckPublicationRelEntry(pub->oid, relid, &is_except)) + return !is_except; + else + return SearchSysCacheExists2(PUBLICATIONNAMESPACEMAP, + ObjectIdGetDatum(get_rel_namespace(relid)), + ObjectIdGetDatum(pub->oid)); } /* diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c index 96838730fe1..8106ecb7a6a 100644 --- a/src/backend/commands/publicationcmds.c +++ b/src/backend/commands/publicationcmds.c @@ -22,6 +22,7 @@ #include "catalog/namespace.h" #include "catalog/objectaccess.h" #include "catalog/objectaddress.h" +#include "catalog/partition.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" #include "catalog/pg_namespace.h" @@ -61,6 +62,17 @@ typedef struct rf_context Oid parentid; /* relid of the parent relation */ } rf_context; +/* + * A descendant of an EXCEPT entry that lives in a different schema, and so is + * outside the reach of the clause the entry belongs to. The ancestor is kept + * as well, so that a conflict can name the entry responsible for it. + */ +typedef struct ExceptDescendant +{ + Oid ancestor; + Oid descendant; +} ExceptDescendant; + static List *OpenTableList(List *tables); static void CloseTableList(List *rels); static void LockSchemaList(List *schemalist); @@ -71,6 +83,14 @@ static void PublicationAddSchemas(Oid pubid, List *schemas, bool if_not_exists, AlterPublicationStmt *stmt); static void PublicationDropSchemas(Oid pubid, List *schemas, bool missing_ok); static char defGetGeneratedColsOption(DefElem *def); +static List *GetExceptCrossSchemaDescendants(List *except_pubtables); +static void CheckExceptConflicts(List *except_rels, + List *cross_schema_descendants, + List *explicitrelids, List *pubschemas); +static void ProcessSchemaExceptTables(Oid schemaid, List *except_tables, + ParseState *pstate, List **schemas, + List **schemas_with_except, + List **except_pubtables); static void @@ -175,16 +195,93 @@ parse_publication_options(ParseState *pstate, } } +/* + * Reject a schema being mentioned more than once with an EXCEPT clause, even + * if the EXCEPT clauses are identical — much like OpenTableList() rejects + * "FOR TABLE t1(a), t1(a)" despite the column lists matching. A schema can + * still be mentioned multiple times, just not more than once with EXCEPT. + * + * Also qualify unqualified EXCEPT table names with the given schema (rejecting + * any explicitly qualified with a different schema), and append them to + * *except_pubtables. + * + * schemaid: OID of the schema for this TABLES IN SCHEMA mention. + * except_tables: the EXCEPT list (or NIL) attached to this mention. + * pstate: parse state of the statement, used to report the error position of + * an offending EXCEPT entry. + * *schemas: accumulates all schema OIDs seen so far in this statement. + * *schemas_with_except: This is a subset of *schemas. Tracks which of + * the seen schemas of this statement had an EXCEPT clause. + * *except_pubtables: accumulates the (now schema-qualified) EXCEPT table + * entries across the whole statement. + */ +static void +ProcessSchemaExceptTables(Oid schemaid, List *except_tables, + ParseState *pstate, List **schemas, + List **schemas_with_except, List **except_pubtables) +{ + char *schema_name = get_namespace_name(schemaid); + bool schema_has_except = (except_tables != NIL); + + /* + * A repeating schema is only a problem if this mention has EXCEPT, or an + * earlier mention of the same schema did. + */ + if (list_member_oid(*schemas, schemaid)) + { + if (schema_has_except || + list_member_oid(*schemas_with_except, schemaid)) + ereport(ERROR, + errcode(ERRCODE_DUPLICATE_OBJECT), + errmsg("conflicting or redundant EXCEPT clauses for schema \"%s\"", + schema_name)); + } + + if (schema_has_except) + *schemas_with_except = lappend_oid(*schemas_with_except, schemaid); + + /* Filter out duplicates if the user specifies "sch1, sch1" */ + *schemas = list_append_unique_oid(*schemas, schemaid); + + if (!schema_has_except) + return; + + foreach_ptr(PublicationObjSpec, eobj, except_tables) + { + RangeVar *relation = eobj->pubtable->relation; + + if (relation->schemaname == NULL) + relation->schemaname = schema_name; + else if (strcmp(relation->schemaname, schema_name) != 0) + ereport(ERROR, + errcode(ERRCODE_INVALID_OBJECT_DEFINITION), + errmsg("table \"%s\" in EXCEPT clause does not belong to schema \"%s\"", + quote_qualified_identifier(relation->schemaname, relation->relname), + schema_name), + parser_errposition(pstate, eobj->location)); + + /* + * Mark this EXCEPT entry as schema-scoped. Descendants in the same + * schema are handled by OpenTableList(), while descendants in other + * schemas are handled by GetExceptCrossSchemaDescendants(). + */ + eobj->pubtable->except_in_schema = true; + + *except_pubtables = lappend(*except_pubtables, eobj->pubtable); + } +} + /* * Convert the PublicationObjSpecType list into schema oid list and * PublicationTable list. */ static void ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, - List **rels, List **exceptrels, List **schemas) + List **rels, List **except_pubtables, List **schemas) { ListCell *cell; PublicationObjSpec *pubobj; + List *schemas_with_except = NIL; if (!pubobjspec_list) return; @@ -200,7 +297,7 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, { case PUBLICATIONOBJ_EXCEPT_TABLE: pubobj->pubtable->except = true; - *exceptrels = lappend(*exceptrels, pubobj->pubtable); + *except_pubtables = lappend(*except_pubtables, pubobj->pubtable); break; case PUBLICATIONOBJ_TABLE: pubobj->pubtable->except = false; @@ -209,8 +306,10 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, case PUBLICATIONOBJ_TABLES_IN_SCHEMA: schemaid = get_namespace_oid(pubobj->name, false); - /* Filter out duplicates if user specifies "sch1, sch1" */ - *schemas = list_append_unique_oid(*schemas, schemaid); + ProcessSchemaExceptTables(schemaid, pubobj->except_tables, + pstate, schemas, + &schemas_with_except, + except_pubtables); break; case PUBLICATIONOBJ_TABLES_IN_CUR_SCHEMA: search_path = fetch_search_path(false); @@ -222,8 +321,10 @@ ObjectsInPublicationToOids(List *pubobjspec_list, ParseState *pstate, schemaid = linitial_oid(search_path); list_free(search_path); - /* Filter out duplicates if user specifies "sch1, sch1" */ - *schemas = list_append_unique_oid(*schemas, schemaid); + ProcessSchemaExceptTables(schemaid, pubobj->except_tables, + pstate, schemas, + &schemas_with_except, + except_pubtables); break; default: /* shouldn't happen */ @@ -770,6 +871,177 @@ TransformPubWhereClauses(List *tables, const char *queryString, } } +/* + * Collect the descendants of the given EXCEPT entries that live outside the + * schema of the clause the entry belongs to. + * + * The entries must already have been opened by OpenTableList(), which is what + * holds the lock on them; no further lock is taken here. + */ +static List * +GetExceptCrossSchemaDescendants(List *except_pubtables) +{ + List *result = NIL; + + foreach_node(PublicationTable, t, except_pubtables) + { + Oid relid; + Oid relnsp; + List *descendants; + + /* An EXCEPT clause of FOR ALL TABLES is not scoped to a schema. */ + if (!t->except_in_schema) + continue; + + relid = RangeVarGetRelid(t->relation, NoLock, false); + + /* + * There are no descendants to collect when ONLY is specified for a + * plain table. For a partitioned table, ONLY has no effect, so its + * partitions are always covered by the clause. + */ + if (!t->relation->inh && + get_rel_relkind(relid) != RELKIND_PARTITIONED_TABLE) + continue; + + relnsp = get_rel_namespace(relid); + + /* + * Find all partitions and inheritance children of the relation. The + * given relation itself is also returned as the first member and is + * skipped below. + */ + descendants = find_all_inheritors(relid, NoLock, NULL); + + foreach_oid(descrelid, descendants) + { + ExceptDescendant *ed; + + /* Allow query cancel in case this takes a long time */ + CHECK_FOR_INTERRUPTS(); + + /* Descendants in the same schema are already excluded */ + if (get_rel_namespace(descrelid) == relnsp) + continue; + + ed = palloc_object(ExceptDescendant); + ed->ancestor = relid; + ed->descendant = descrelid; + result = lappend(result, ed); + } + + list_free(descendants); + } + + return result; +} + +/* + * Check that a table is not both excluded and published in the same DDL. + * + * Similar checks are present in publication_add_relation() and + * check_publication_add_relation(), but they rely on pg_publication_rel + * entries and ancestor lookups. Here, the checks are performed on the + * object lists collected during the statement, as the catalog state is + * not sufficient in the cases below: + * + * - CreatePublication() inserts the explicit tables and the EXCEPT tables in + * a single command, but rows inserted by the current command are not + * visible to later lookups within the same command. + * + * - For partitions, the excluded root's row might not yet exist because the + * root may be added to the EXCEPT list later. Detecting such contradictions + * when adding the root to the EXCEPT clause would require traversing + * downward through the partition hierarchy, whereas the existing ancestor + * lookups only traverse upward from the relation being added. + */ +static void +CheckExceptConflicts(List *except_rels, List *cross_schema_descendants, + List *explicitrelids, List *pubschemas) +{ + /* Check the tables the statement publishes by name. */ + foreach_oid(explicitrelid, explicitrelids) + { + Oid root = InvalidOid; + + if (get_rel_relispartition(explicitrelid)) + { + List *ancestors = get_partition_ancestors(explicitrelid); + + /* + * ancestors is NIL for a partition with a pending DETACH + * CONCURRENTLY. + */ + if (ancestors != NIL) + root = llast_oid(ancestors); + list_free(ancestors); + } + + foreach_ptr(PublicationRelInfo, pri, except_rels) + { + Oid exceptrelid = RelationGetRelid(pri->relation); + + if (exceptrelid == explicitrelid) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" cannot be both published and excluded", + RelationGetQualifiedRelationName(pri->relation))); + + if (OidIsValid(root) && exceptrelid == root) + ereport(ERROR, + (errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("partition \"%s\" cannot be both published and excluded", + quote_qualified_identifier(get_namespace_name(get_rel_namespace(explicitrelid)), + get_rel_name(explicitrelid))), + errdetail("Partition root \"%s\" is named in the publication's EXCEPT clause for schema \"%s\".", + RelationGetQualifiedRelationName(pri->relation), + get_namespace_name(RelationGetNamespace(pri->relation))))); + } + } + + /* + * Check descendants that are excluded by an EXCEPT clause but reside in a + * different schema from the clause. + */ + foreach_ptr(ExceptDescendant, ed, cross_schema_descendants) + { + Oid descnsp = get_rel_namespace(ed->descendant); + Oid ancestornsp = get_rel_namespace(ed->ancestor); + bool excluded = false; + + /* + * A descendant that is not published explicitly or through a TABLES IN + * SCHEMA clause cannot conflict with the EXCEPT clause. + */ + if (list_member_oid(explicitrelids, ed->descendant) || + list_member_oid(pubschemas, descnsp)) + { + /* + * The descendant may also be excluded by an EXCEPT clause in its + * own schema. In that case, it is not both published and excluded. + */ + foreach_ptr(PublicationRelInfo, other, except_rels) + { + if (RelationGetRelid(other->relation) == ed->descendant) + { + excluded = true; + break; + } + } + + if (!excluded) + ereport(ERROR, + errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("table \"%s\" cannot be both published and excluded", + quote_qualified_identifier(get_namespace_name(descnsp), + get_rel_name(ed->descendant))), + errdetail("It descends from \"%s\", which is named in the EXCEPT clause of schema \"%s\".", + quote_qualified_identifier(get_namespace_name(ancestornsp), + get_rel_name(ed->ancestor)), + get_namespace_name(ancestornsp))); + } + } +} /* * Given a list of tables that are going to be added to a publication, @@ -849,7 +1121,7 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) char publish_generated_columns; AclResult aclresult; List *relations = NIL; - List *exceptrelations = NIL; + List *except_pubtables = NIL; List *schemaidlist = NIL; /* must have CREATE privilege on database */ @@ -936,16 +1208,16 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) /* Associate objects with the publication. */ ObjectsInPublicationToOids(stmt->pubobjects, pstate, &relations, - &exceptrelations, &schemaidlist); + &except_pubtables, &schemaidlist); if (stmt->for_all_tables) { /* Process EXCEPT table list */ - if (exceptrelations != NIL) + if (except_pubtables != NIL) { List *rels; - rels = OpenTableList(exceptrelations); + rels = OpenTableList(except_pubtables); PublicationAddTables(puboid, rels, true, NULL); CloseTableList(rels); } @@ -959,6 +1231,11 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) } else if (!stmt->for_all_sequences) { + List *explicitrelids = NIL; + + /* EXCEPT tables here always belong to a schema in schemaidlist */ + Assert(except_pubtables == NIL || schemaidlist != NIL); + /* FOR TABLES IN SCHEMA requires superuser */ if (schemaidlist != NIL && !superuser()) ereport(ERROR, @@ -978,6 +1255,20 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) publish_via_partition_root); PublicationAddTables(puboid, rels, true, NULL); + + /* + * Collect explicit table OIDs now, before we close the relation + * list, so that the except-table validation for pub-included + * schemas below can check for contradictions without relying on a + * catalog scan that might not yet see the just-inserted rows. + */ + if (except_pubtables != NIL) + { + foreach_ptr(PublicationRelInfo, pri, rels) + explicitrelids = lappend_oid(explicitrelids, + RelationGetRelid(pri->relation)); + } + CloseTableList(rels); } @@ -989,6 +1280,26 @@ CreatePublication(ParseState *pstate, CreatePublicationStmt *stmt) */ LockSchemaList(schemaidlist); PublicationAddSchemas(puboid, schemaidlist, true, NULL); + + if (except_pubtables != NIL) + { + List *except_rels; + List *cross_schema_descendants; + + except_rels = OpenTableList(except_pubtables); + cross_schema_descendants = + GetExceptCrossSchemaDescendants(except_pubtables); + + /* + * Validate that a table is not both included and excluded by + * this statement. + */ + CheckExceptConflicts(except_rels, cross_schema_descendants, + explicitrelids, schemaidlist); + + PublicationAddTables(puboid, except_rels, false, NULL); + CloseTableList(except_rels); + } } } @@ -1295,8 +1606,15 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, } else { - oldrelids = GetIncludedPublicationRelations(pubid, - PUBLICATION_PART_ROOT); + /* + * SET replaces the publication's whole relation list, so every + * existing entry has to be reconciled against the new one -- an + * EXCEPT entry included. If the same relation is now requested + * with the opposite kind, the old entry is dropped below and the + * new one added, rather than the old one being silently kept. + */ + oldrelids = GetPublicationRelationsOfAnyKind(pubid, + PUBLICATION_PART_ROOT); TransformPubWhereClauses(rels, queryString, pubform->pubviaroot); @@ -1317,6 +1635,7 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, HeapTuple rftuple; Node *oldrelwhereclause = NULL; Bitmapset *oldcolumns = NULL; + bool oldexcept = false; /* look up the cache for the old relmap */ rftuple = SearchSysCache2(PUBLICATIONRELMAP, @@ -1348,6 +1667,8 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, if (!isnull) oldcolumns = pub_collist_to_bitmapset(NULL, columnListDatum, NULL); + oldexcept = ((Form_pg_publication_rel) GETSTRUCT(rftuple))->prexcept; + ReleaseSysCache(rftuple); } @@ -1371,14 +1692,17 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup, /* * Check if any of the new set of relations matches with the - * existing relations in the publication. Additionally, if the + * existing relations in the publication. An entry matches + * only if it is of the same kind, that is, both are ordinary + * members or both are EXCEPT entries. Additionally, if the * relation has an associated WHERE clause, check the WHERE * expressions also match. Same for the column list. Drop the * rest. */ if (newrelid == oldrelid) { - if (equal(oldrelwhereclause, newpubrel->whereClause) && + if (newpubrel->except == oldexcept && + equal(oldrelwhereclause, newpubrel->whereClause) && bms_equal(oldcolumns, newcolumns)) { found = true; @@ -1829,6 +2153,62 @@ RemovePublicationSchemaById(Oid psoid) table_close(rel, RowExclusiveLock); } +/* + * Remove any EXCEPT clause entries for a relation from schema publications. + * Called when a table changes schema (ALTER TABLE ... SET SCHEMA), so that + * a schema-scoped exclusion does not silently follow the table to its new + * schema. + */ +void +RemoveSchemaPubExceptForRel(Oid relid, Oid oldNspOid, Oid newNspOid) +{ + List *pubids; + + /* + * If the table is not actually moving to a different schema (no-op ALTER + * TABLE ... SET SCHEMA <current_schema>), there is nothing to do. + */ + if (oldNspOid == newNspOid) + return; + + pubids = GetRelationExcludedPublications(relid); + + foreach_oid(pubid, pubids) + { + Oid proid; + + /* + * This problem does not apply to FOR ALL TABLES publications, because + * their EXCEPT clause is publication-scoped, not schema-scoped: the + * exclusion should persist regardless of what schema the table is in. + */ + if (!is_schema_publication(pubid)) + continue; + + proid = GetSysCacheOid2(PUBLICATIONRELMAP, + Anum_pg_publication_rel_oid, + ObjectIdGetDatum(relid), + ObjectIdGetDatum(pubid)); + if (OidIsValid(proid)) + { + ObjectAddress obj; + + ObjectAddressSet(obj, PublicationRelRelationId, proid); + + ereport(DEBUG2, + errmsg_internal("auto-remove exclusion of table \"%s.%s\" from publication \"%s\": table moved to schema \"%s\"", + get_namespace_name(oldNspOid), + get_rel_name(relid), + get_publication_name(pubid, false), + get_namespace_name(newNspOid))); + + performDeletion(&obj, DROP_CASCADE, 0); + } + } + + list_free(pubids); +} + /* * Open relations specified by a PublicationTable list. * The returned tables are locked in ShareUpdateExclusiveLock mode in order to @@ -1911,6 +2291,7 @@ OpenTableList(List *tables) { List *children; ListCell *child; + Oid parentnsp = RelationGetNamespace(rel); children = find_all_inheritors(myrelid, ShareUpdateExclusiveLock, NULL); @@ -1922,6 +2303,17 @@ OpenTableList(List *tables) /* Allow query cancel in case this takes a long time */ CHECK_FOR_INTERRUPTS(); + /* + * An EXCEPT clause attached to a schema does not reach the + * inheritance children that live in other schemas, so they + * get no entry of their own. Such a child is instead + * collected by GetExceptCrossSchemaDescendants(), which lets + * the statement be rejected if it publishes the child anyway. + */ + if (t->except_in_schema && + get_rel_namespace(childrelid) != parentnsp) + continue; + /* * Skip duplicates if user specified both parent and child * tables. diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 12beb37246f..250ee9a3cbf 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -49,6 +49,7 @@ #include "catalog/pg_opclass.h" #include "catalog/pg_policy.h" #include "catalog/pg_proc.h" +#include "catalog/pg_publication.h" #include "catalog/pg_publication_rel.h" #include "catalog/pg_rewrite.h" #include "catalog/pg_statistic_ext.h" @@ -63,6 +64,7 @@ #include "commands/event_trigger.h" #include "commands/extension.h" #include "commands/repack.h" +#include "commands/publicationcmds.h" #include "commands/sequence.h" #include "commands/tablecmds.h" #include "commands/tablespace.h" @@ -19802,6 +19804,16 @@ AlterTableNamespaceInternal(Relation rel, Oid oldNspOid, Oid nspOid, AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid, false, objsMoved); + /* + * Remove any EXCEPT clause entries for this relation from schema + * publications. A schema-scoped exclusion is no longer meaningful once + * the table moves to a different schema. + */ + if (rel->rd_rel->relkind == RELKIND_RELATION || + rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE) + RemoveSchemaPubExceptForRel(RelationGetRelid(rel), oldNspOid, + nspOid); + table_close(classRel, RowExclusiveLock); } @@ -21135,6 +21147,7 @@ ATExecAttachPartition(List **wqueue, Relation rel, PartitionCmd *cmd, if (exceptpuboids != NIL) { bool first = true; + bool has_alltables_pub = false; StringInfoData pubnames; initStringInfo(&pubnames); @@ -21148,17 +21161,22 @@ ATExecAttachPartition(List **wqueue, Relation rel, PartitionCmd *cmd, else appendStringInfo(&pubnames, _(", \"%s\""), pubname); first = false; + + if (GetPublication(pubid)->alltables) + has_alltables_pub = true; } ereport(ERROR, errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), - errmsg_plural("cannot attach table \"%s\" as partition because it is referenced in publication %s EXCEPT clause", - "cannot attach table \"%s\" as partition because it is referenced in publications %s EXCEPT clause", + errmsg_plural("cannot attach table \"%s\" as partition because it is named in EXCEPT clause of publication %s", + "cannot attach table \"%s\" as partition because it is named in EXCEPT clause of publications %s", list_length(exceptpuboids), RelationGetRelationName(attachrel), pubnames.data), errdetail("The publication EXCEPT clause cannot contain tables that are partitions."), - errhint("Change the publication's EXCEPT clause using ALTER PUBLICATION ... SET ALL TABLES.")); + errhint("%s", has_alltables_pub ? + _("Change the EXCEPT clause using ALTER PUBLICATION ... SET ALL TABLES ... EXCEPT.") : + _("Change the EXCEPT clause using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT."))); } list_free(exceptpuboids); diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y index 17035fb4d15..14520a5ccab 100644 --- a/src/backend/parser/gram.y +++ b/src/backend/parser/gram.y @@ -58,6 +58,7 @@ #include "nodes/makefuncs.h" #include "nodes/nodeFuncs.h" #include "parser/parser.h" +#include "utils/builtins.h" #include "utils/datetime.h" #include "utils/xml.h" @@ -11282,7 +11283,7 @@ AlterOwnerStmt: ALTER AGGREGATE aggregate_with_argtypes OWNER TO RoleSpec * pub_obj is one of: * * TABLE table [, ...] - * TABLES IN SCHEMA schema [, ...] + * TABLES IN SCHEMA schema [EXCEPT (TABLE table [, ...] )] [, ...] * *****************************************************************************/ @@ -11342,23 +11343,26 @@ PublicationObjSpec: $$->pubtable->columns = $3; $$->pubtable->whereClause = $4; } - | TABLES IN_P SCHEMA ColId + | TABLES IN_P SCHEMA ColId opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_SCHEMA; $$->name = $4; + $$->except_tables = $5; $$->location = @4; } - | TABLES IN_P SCHEMA CURRENT_SCHEMA + | TABLES IN_P SCHEMA CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_TABLES_IN_CUR_SCHEMA; + $$->except_tables = $5; $$->location = @4; } - | ColId opt_column_list OptWhereClause + | ColId opt_column_list OptWhereClause opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $4; /* * If either a row filter or column list is specified, create * a PublicationTable object. @@ -11402,10 +11406,11 @@ PublicationObjSpec: $$->pubtable->columns = $2; $$->pubtable->whereClause = $3; } - | CURRENT_SCHEMA + | CURRENT_SCHEMA opt_pub_except_clause { $$ = makeNode(PublicationObjSpec); $$->pubobjtype = PUBLICATIONOBJ_CONTINUATION; + $$->except_tables = $2; $$->location = @1; } ; @@ -20867,6 +20872,11 @@ preprocess_pub_all_objtype_list(List *all_objects_list, List **pubobjects, /* * Process pubobjspec_list to check for errors in any of the objects and * convert PUBLICATIONOBJ_CONTINUATION into appropriate PublicationObjSpecType. + * + * The except_tables attached to TABLES IN SCHEMA nodes are left in place here; + * ObjectsInPublicationToOids() qualifies their names, validates schema + * membership, and merges the qualified tables into its except_pubtables + * output list once the schema OID is known. */ static void preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) @@ -20895,6 +20905,13 @@ preprocess_pubobj_list(List *pubobjspec_list, core_yyscan_t yyscanner) if (pubobj->pubobjtype == PUBLICATIONOBJ_TABLE) { + /* EXCEPT is not valid for table objects */ + if (pubobj->except_tables != NIL) + ereport(ERROR, + errcode(ERRCODE_SYNTAX_ERROR), + errmsg("EXCEPT is not allowed for TABLE publication objects"), + parser_errposition(pubobj->location)); + /* relation name or pubtable must be set for this type of object */ if (!pubobj->name && !pubobj->pubtable) ereport(ERROR, diff --git a/src/backend/replication/pgoutput/pgoutput.c b/src/backend/replication/pgoutput/pgoutput.c index 484ffbe2cee..0a28533f6bc 100644 --- a/src/backend/replication/pgoutput/pgoutput.c +++ b/src/backend/replication/pgoutput/pgoutput.c @@ -2281,10 +2281,41 @@ get_rel_sync_entry(PGOutputData *data, Relation relation) } } - if (list_member_oid(pubids, pub->oid) || - list_member_oid(schemaPubids, pub->oid) || - ancestor_published) + if (list_member_oid(pubids, pub->oid) || ancestor_published) publish = true; + else if (list_member_oid(schemaPubids, pub->oid)) + { + Oid root_relid; + bool root_is_except = false; + + /* + * schemaPubids is the list of publications that include + * relid's own schema, independent of the ancestor walk + * above -- a partition can live in a different schema + * than its root. Still need to check for exclusion here, + * using the top-most ancestor since only a root + * (non-partition) table can appear in an EXCEPT clause. + */ + if (am_partition) + { + List *ancestors = get_partition_ancestors(relid); + + /* + * ancestors is NIL for a partition with a pending + * DETACH CONCURRENTLY; + */ + root_relid = (ancestors == NIL) ? relid : + llast_oid(ancestors); + list_free(ancestors); + } + else + root_relid = relid; + + CheckPublicationRelEntry(pub->oid, root_relid, &root_is_except); + + if (!root_is_except) + publish = true; + } } /* diff --git a/src/backend/utils/cache/relcache.c b/src/backend/utils/cache/relcache.c index f475d703977..465e8a0ea02 100644 --- a/src/backend/utils/cache/relcache.c +++ b/src/backend/utils/cache/relcache.c @@ -5804,7 +5804,6 @@ RelationBuildPublicationDesc(Relation relation, PublicationDesc *pubdesc) { List *puboids = NIL; List *exceptpuboids = NIL; - List *alltablespuboids; ListCell *lc; MemoryContext oldcxt; Oid schemaid; @@ -5848,12 +5847,9 @@ RelationBuildPublicationDesc(Relation relation, PublicationDesc *pubdesc) if (relation->rd_rel->relispartition) { - Oid last_ancestor_relid; - - /* Add publications that the ancestors are in too. */ ancestors = get_partition_ancestors(relid); - last_ancestor_relid = llast_oid(ancestors); + /* Add publications that the ancestors are in too. */ foreach(lc, ancestors) { Oid ancestor = lfirst_oid(lc); @@ -5866,11 +5862,13 @@ RelationBuildPublicationDesc(Relation relation, PublicationDesc *pubdesc) } /* - * Only the top-most ancestor can appear in the EXCEPT clause. - * Therefore, for a partition, exclusion must be evaluated at the - * top-most ancestor. + * Only the topmost root of a partition hierarchy can appear in an + * EXCEPT clause, so that is where exclusion has to be evaluated. + * ancestors is NIL for a partition with a pending DETACH + * CONCURRENTLY, in which case there is no root to consult. */ - exceptpuboids = GetRelationExcludedPublications(last_ancestor_relid); + if (ancestors != NIL) + exceptpuboids = GetRelationExcludedPublications(llast_oid(ancestors)); } else { @@ -5881,10 +5879,12 @@ RelationBuildPublicationDesc(Relation relation, PublicationDesc *pubdesc) exceptpuboids = GetRelationExcludedPublications(relid); } - alltablespuboids = GetAllTablesPublications(); - puboids = list_concat_unique_oid(puboids, - list_difference_oid(alltablespuboids, - exceptpuboids)); + puboids = list_concat_unique_oid(puboids, GetAllTablesPublications()); + + /* Ignore the publications that exclude this relation. */ + if (exceptpuboids != NIL) + puboids = list_difference_oid(puboids, exceptpuboids); + foreach(lc, puboids) { Oid pubid = lfirst_oid(lc); diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c index 063e2555814..12acd18b9ef 100644 --- a/src/bin/psql/describe.c +++ b/src/bin/psql/describe.c @@ -3036,7 +3036,29 @@ describeOneTableDetails(const char *schemaname, "FROM pg_catalog.pg_publication p\n" " JOIN pg_catalog.pg_publication_namespace pn ON p.oid = pn.pnpubid\n" " JOIN pg_catalog.pg_class pc ON pc.relnamespace = pn.pnnspid\n" - "WHERE pc.oid ='%s' and pg_catalog.pg_relation_is_publishable('%s')\n" + "WHERE pc.oid ='%s' and pg_catalog.pg_relation_is_publishable('%s')\n", + oid, oid); + + if (pset.sversion >= 200000) + { + /* + * Publishing the schema does not publish a table named in the + * publication's EXCEPT clause, nor a partition whose root is + * named there, since excluding a root excludes the whole + * partition tree. Unlike the FOR ALL TABLES case below, a + * schema publication can have both kinds of + * pg_publication_rel row, so prexcept has to be tested. + */ + appendPQExpBuffer(&buf, + " AND NOT EXISTS (\n" + " SELECT 1\n" + " FROM pg_catalog.pg_publication_rel pr\n" + " WHERE pr.prpubid = p.oid AND pr.prexcept AND\n" + " (pr.prrelid = '%s' OR pr.prrelid = pg_catalog.pg_partition_root('%s')))\n", + oid, oid); + } + + appendPQExpBuffer(&buf, "UNION\n" "SELECT pubname\n" " , pg_catalog.pg_get_expr(pr.prqual, c.oid)\n" @@ -3060,7 +3082,7 @@ describeOneTableDetails(const char *schemaname, " FROM pg_catalog.pg_publication_namespace pn\n" " WHERE pn.pnpubid = p.oid\n" " AND pn.pnnspid = c.relnamespace)\n", - oid, oid, oid); + oid); if (pset.sversion >= 190000) { @@ -6839,6 +6861,24 @@ describePublications(const char *pattern) if (!addFooterToPublicationDesc(&buf, _("Tables from schemas:"), true, &cont)) goto error_return; + + if (pset.sversion >= 200000) + { + /* + * Get tables in the EXCEPT clause for this schema + * publication. + */ + printfPQExpBuffer(&buf, + "SELECT concat(c.relnamespace::regnamespace, '.', c.relname)\n" + "FROM pg_catalog.pg_class c\n" + " JOIN pg_catalog.pg_publication_rel pr ON c.oid = pr.prrelid\n" + "WHERE pr.prpubid = '%s'\n" + " AND pr.prexcept\n" + "ORDER BY 1", pubid); + if (!addFooterToPublicationDesc(&buf, _("Except tables:"), + true, &cont)) + goto error_return; + } } } else diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c index 190fff7ea0e..f069e2654cc 100644 --- a/src/bin/psql/tab-complete.in.c +++ b/src/bin/psql/tab-complete.in.c @@ -1065,6 +1065,24 @@ static const SchemaQuery Query_for_trigger_of_table = { "SELECT nspname FROM pg_catalog.pg_namespace "\ " WHERE nspname LIKE '%s'" +#define Query_for_list_of_tables_in_schema \ +"SELECT n.nspname || '.' || c.relname "\ +" FROM pg_catalog.pg_class c "\ +" JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "\ +" WHERE c.relkind IN (" CppAsString2(RELKIND_RELATION) ", " \ + CppAsString2(RELKIND_PARTITIONED_TABLE) ") "\ +" AND (n.nspname || '.' || c.relname) LIKE '%s' "\ +" AND n.nspname = '%s'" + +#define Query_for_list_of_tables_in_current_schema \ +"SELECT c.relname "\ +" FROM pg_catalog.pg_class c "\ +" JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "\ +" WHERE c.relkind IN (" CppAsString2(RELKIND_RELATION) ", " \ + CppAsString2(RELKIND_PARTITIONED_TABLE) ") "\ +" AND c.relname LIKE '%s' "\ +" AND n.nspname = pg_catalog.current_schema()" + /* Use COMPLETE_WITH_QUERY_VERBATIM with these queries for GUC names: */ #define Query_for_list_of_alter_system_set_vars \ "SELECT pg_catalog.lower(name) FROM pg_catalog.pg_settings "\ @@ -3777,8 +3795,21 @@ match_previous_words(int pattern_id, COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas " AND nspname NOT LIKE E'pg\\\\_%%'", "CURRENT_SCHEMA"); - else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && (!ends_with(prev_wd, ','))) - COMPLETE_WITH("WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && !ends_with(prev_wd, ',')) + COMPLETE_WITH("EXCEPT ( TABLE", "WITH ("); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT")) + COMPLETE_WITH("( TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(")) + COMPLETE_WITH("TABLE"); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", "CURRENT_SCHEMA", "EXCEPT", "(", "TABLE")) + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_current_schema); + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE")) + { + set_completion_reference(prev4_wd); + COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_tables_in_schema); + } + else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny, "EXCEPT", "(", "TABLE", MatchAnyN) && !ends_with(prev_wd, ',')) + COMPLETE_WITH(")"); /* Complete "CREATE PUBLICATION <name> [...] WITH" */ else if (Matches("CREATE", "PUBLICATION", MatchAnyN, "WITH", "(")) COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root"); diff --git a/src/include/catalog/pg_publication.h b/src/include/catalog/pg_publication.h index 89b4bb14f62..451559552ad 100644 --- a/src/include/catalog/pg_publication.h +++ b/src/include/catalog/pg_publication.h @@ -179,6 +179,8 @@ extern List *GetIncludedPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt); extern List *GetExcludedPublicationTables(Oid pubid, PublicationPartOpt pub_partopt); +extern List *GetPublicationRelationsOfAnyKind(Oid pubid, + PublicationPartOpt pub_partopt); extern List *GetAllTablesPublications(void); extern List *GetAllPublicationRelations(Oid pubid, char relkind, bool pubviaroot); extern List *GetPublicationSchemas(Oid pubid); @@ -192,6 +194,7 @@ extern List *GetPubPartitionOptionRelations(List *result, Oid relid); extern Oid GetTopMostAncestorInPublication(Oid puboid, List *ancestors, int *ancestor_level); +extern bool CheckPublicationRelEntry(Oid pubid, Oid relid, bool *is_except); extern bool is_publishable_relation(Relation rel); extern bool is_schema_publication(Oid pubid); diff --git a/src/include/commands/publicationcmds.h b/src/include/commands/publicationcmds.h index 4cf45c17cc5..fb1703aa675 100644 --- a/src/include/commands/publicationcmds.h +++ b/src/include/commands/publicationcmds.h @@ -27,6 +27,8 @@ extern void AlterPublication(ParseState *pstate, AlterPublicationStmt *stmt); extern void RemovePublicationById(Oid pubid); extern void RemovePublicationRelById(Oid proid); extern void RemovePublicationSchemaById(Oid psoid); +extern void RemoveSchemaPubExceptForRel(Oid relid, Oid oldNspOid, + Oid newNspOid); extern ObjectAddress AlterPublicationOwner(const char *name, Oid newOwnerId); extern void AlterPublicationOwner_oid(Oid pubid, Oid newOwnerId); diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h index 8a9df884276..0c7f2b9995c 100644 --- a/src/include/nodes/parsenodes.h +++ b/src/include/nodes/parsenodes.h @@ -4510,6 +4510,9 @@ typedef struct PublicationTable Node *whereClause; /* qualifications */ List *columns; /* List of columns in a publication table */ bool except; /* True if listed in the EXCEPT clause */ + bool except_in_schema; /* True if listed in the EXCEPT clause of + * a TABLES IN SCHEMA clause, whose scope + * is limited to that schema */ } PublicationTable; /* @@ -4531,6 +4534,8 @@ typedef struct PublicationObjSpec PublicationObjSpecType pubobjtype; /* type of this publication object */ char *name; PublicationTable *pubtable; + List *except_tables; /* tables specified in the EXCEPT clause (for + * TABLES IN SCHEMA) */ ParseLoc location; /* token location, or -1 if unknown */ } PublicationObjSpec; diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out index 4f21462cc17..e6ae084dc8a 100644 --- a/src/test/regress/expected/publication.out +++ b/src/test/regress/expected/publication.out @@ -279,6 +279,12 @@ CREATE PUBLICATION testpub_foralltables_excepttable2 FOR ALL TABLES EXCEPT (test ERROR: syntax error at or near "testpub_tbl1" LINE 1: ..._foralltables_excepttable2 FOR ALL TABLES EXCEPT (testpub_tb... ^ +-- fail - EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testpub_tbl3); +ERROR: EXCEPT is not allowed for TABLE publication objects +LINE 2: FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testp... + ^ --------------------------------------------- -- SET ALL TABLES/SEQUENCES --------------------------------------------- @@ -473,13 +479,290 @@ CREATE TABLE tab_main (a int) PARTITION BY RANGE(a); -- Attaching a partition is not allowed if the partitioned table appears in a -- publication's EXCEPT clause. ALTER TABLE tab_main ATTACH PARTITION testpub_root FOR VALUES FROM (0) TO (200); -ERROR: cannot attach table "testpub_root" as partition because it is referenced in publication "testpub8" EXCEPT clause +ERROR: cannot attach table "testpub_root" as partition because it is named in EXCEPT clause of publication "testpub8" DETAIL: The publication EXCEPT clause cannot contain tables that are partitions. -HINT: Change the publication's EXCEPT clause using ALTER PUBLICATION ... SET ALL TABLES. +HINT: Change the EXCEPT clause using ALTER PUBLICATION ... SET ALL TABLES ... EXCEPT. RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Create same-named tables in public to verify unqualified EXCEPT entries +-- are qualified with the named schema, not public +CREATE TABLE testpub_nopk (foo int, bar int); +CREATE TABLE testpub_tbl_s1 (a int primary key, b text); +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + Publication testpub_schema_except1 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +-- Exclude multiple tables using unqualified names; same-named tables exist in +-- public to confirm unqualified names resolve to pub_test, not public +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + Publication testpub_schema_except2 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_nopk" + "pub_test.testpub_tbl_s1" + +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); +ERROR: table "public.testpub_tbl1" in EXCEPT clause does not belong to schema "pub_test" +LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testp... + ^ +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); +ERROR: table "pub_test.testpub_tbl_s1" in EXCEPT clause does not belong to schema "public" +LINE 2: ...R TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.t... + ^ +-- Multiple schemas each with their own EXCEPT clause +CREATE PUBLICATION testpub_schema_except_multi + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_schema_except_multi + Publication testpub_schema_except_multi + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_tbl_s1" + "public.testpub_tbl1" + +-- fail: same schema repeated with same EXCEPT clauses +CREATE PUBLICATION testpub_schema_except_conflict + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: conflicting or redundant EXCEPT clauses for schema "pub_test" +-- fail: same schema repeated with conflicting or no EXCEPT clauses +CREATE PUBLICATION testpub_schema_except_conflict2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2), + pub_test; +ERROR: conflicting or redundant EXCEPT clauses for schema "pub_test" +-- ALTER TABLE ... SET SCHEMA on a table excluded by a schema publication: +-- the schema-scoped exclusion is no longer meaningful once the table moves +-- out of its schema, so the exclusion is auto-removed. +CREATE PUBLICATION testpub_schema_except_setsch + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_schema_except_setsch + Publication testpub_schema_except_setsch + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s2" + +ALTER TABLE pub_test.testpub_tbl_s2 SET SCHEMA public; +\dRp+ testpub_schema_except_setsch + Publication testpub_schema_except_setsch + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + +DROP PUBLICATION testpub_schema_except_setsch; +-- Restore for further tests +ALTER TABLE public.testpub_tbl_s2 SET SCHEMA pub_test; +-- fail: table appears in both the explicit table list and the EXCEPT clause +CREATE PUBLICATION testpub_except_conflict + FOR TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +ERROR: table "pub_test.testpub_tbl_s1" cannot be both published and excluded +-- fail: nonexistent table in EXCEPT clause +CREATE PUBLICATION testpub_except_norel + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); +ERROR: relation "pub_test.nonexistent_table" does not exist +-- fail: partition cannot appear in EXCEPT clause; only root tables are allowed +CREATE TABLE pub_test.testpub_parted_s (a int) PARTITION BY LIST (a); +CREATE TABLE pub_test.testpub_part_s PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (1); +CREATE PUBLICATION testpub_except_partition + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); +ERROR: cannot specify relation "pub_test.testpub_part_s" in the publication EXCEPT clause +DETAIL: This operation is not supported for individual partitions. +-- fail: TABLE keyword is required for the first entry in the EXCEPT clause +CREATE PUBLICATION testpub_except_nokw + FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); +ERROR: syntax error at or near "testpub_nopk" +LINE 2: FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + ^ +-- Check that a table excluded from a schema publication is reported only as +-- excluded and not as published. +\d pub_test.testpub_nopk + Table "pub_test.testpub_nopk" + Column | Type | Collation | Nullable | Default +--------+---------+-----------+----------+--------- + foo | integer | | | + bar | integer | | | +Included in publications: + "testpub_schema_except1" + "testpub_schema_except_multi" +Excluded from publications: + "testpub_schema_except2" + +-- fail: ADD TABLE for a partition is rejected when a partition ancestor +-- is currently in the publication's EXCEPT list. +CREATE PUBLICATION testpub_except_ancestor + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ALTER PUBLICATION testpub_except_ancestor ADD TABLE pub_test.testpub_part_s; +ERROR: cannot add partition "pub_test.testpub_part_s" to publication "testpub_except_ancestor" +DETAIL: Partition root "pub_test.testpub_parted_s" is named in the publication's EXCEPT clause for schema "pub_test". +HINT: Change the EXCEPT clause using ALTER PUBLICATION ... SET TABLES IN SCHEMA ... EXCEPT. +DROP PUBLICATION testpub_except_ancestor; +-- fail: same contradiction (explicit partition + EXCEPT-ed ancestor), but +-- given in a single statement instead of two separate ones +CREATE PUBLICATION testpub_except_ancestor_same_create + FOR TABLE pub_test.testpub_part_s, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ERROR: partition "pub_test.testpub_part_s" cannot be both published and excluded +DETAIL: Partition root "pub_test.testpub_parted_s" is named in the publication's EXCEPT clause for schema "pub_test". +-- fail: same contradiction as above, but the partition lives in a different +-- schema (public) than its EXCEPT-ed root (pub_test) +CREATE TABLE public.testpub_part_s2 PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (2); +CREATE PUBLICATION testpub_except_ancestor_cross_schema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s), + TABLE public.testpub_part_s2; +ERROR: partition "public.testpub_part_s2" cannot be both published and excluded +DETAIL: Partition root "pub_test.testpub_parted_s" is named in the publication's EXCEPT clause for schema "pub_test". +DROP TABLE public.testpub_part_s2; +-- ALTER PUBLICATION ... SET replaces the publication's whole relation list, so +-- an existing entry for a relation now requested with the opposite kind must be +-- dropped and re-added, not silently left in place. +CREATE PUBLICATION testpub_except_alter1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +-- the excluded table becomes an ordinary member: one non-EXCEPT entry, no +-- EXCEPT entry, and no schema left in the publication +ALTER PUBLICATION testpub_except_alter1 SET TABLE pub_test.testpub_tbl_s1; +\dRp+ testpub_except_alter1 + Publication testpub_except_alter1 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables: + "pub_test.testpub_tbl_s1" + +DROP PUBLICATION testpub_except_alter1; +-- and the reverse direction: an ordinary member becomes an EXCEPT entry +CREATE PUBLICATION testpub_except_alter2 FOR TABLE pub_test.testpub_tbl_s1; +ALTER PUBLICATION testpub_except_alter2 + SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_except_alter2 + Publication testpub_except_alter2 + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_tbl_s1" + +DROP PUBLICATION testpub_except_alter2; +-- Cross-schema inheritance children and EXCEPT. An EXCEPT clause also +-- excludes inheritance children of a parent named without ONLY. +CREATE TABLE pub_test.testpub_inh_parent (a int); +CREATE TABLE pub_test.testpub_inh_sibling (b int) INHERITS (pub_test.testpub_inh_parent); +CREATE TABLE testpub_inh_child (b int) INHERITS (pub_test.testpub_inh_parent); +CREATE PUBLICATION testpub_inh + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_inh_parent); +-- Two EXCEPT entries: the parent and the child in pub_test. +\dRp+ testpub_inh + Publication testpub_inh + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_inh_parent" + "pub_test.testpub_inh_sibling" + +DROP PUBLICATION testpub_inh; +-- fail: the child testpub_inh_child is also included through TABLES IN SCHEM +-- public +CREATE PUBLICATION testpub_inh + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_inh_parent), + TABLES IN SCHEMA public; +ERROR: table "public.testpub_inh_child" cannot be both published and excluded +DETAIL: It descends from "pub_test.testpub_inh_parent", which is named in the EXCEPT clause of schema "pub_test". +-- fail: the child is also explicitly included by the same statement +CREATE PUBLICATION testpub_inh + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_inh_parent), + TABLE testpub_inh_child; +ERROR: table "public.testpub_inh_child" cannot be both published and excluded +DETAIL: It descends from "pub_test.testpub_inh_parent", which is named in the EXCEPT clause of schema "pub_test". +-- ONLY resolves the conflict: only the parent is excluded, so the child can +-- be published explicitly +CREATE PUBLICATION testpub_inh + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE ONLY pub_test.testpub_inh_parent), + TABLE testpub_inh_child; +\dRp+ testpub_inh + Publication testpub_inh + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables: + "public.testpub_inh_child" +Tables from schemas: + "pub_test" +Except tables: + "pub_test.testpub_inh_parent" + +DROP PUBLICATION testpub_inh; +-- An EXCEPT clause in the child's schema also excludes the child explicitly, +-- so both clauses agree and there is no conflict. +CREATE PUBLICATION testpub_inh + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_inh_parent), + TABLES IN SCHEMA public EXCEPT (TABLE testpub_inh_child); +\dRp+ testpub_inh + Publication testpub_inh + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test" + "public" +Except tables: + "pub_test.testpub_inh_parent" + "pub_test.testpub_inh_sibling" + "public.testpub_inh_child" + +DROP PUBLICATION testpub_inh; +DROP TABLE testpub_inh_child, pub_test.testpub_inh_sibling, + pub_test.testpub_inh_parent; +-- Cleanup +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP TABLE pub_test.testpub_parted_s CASCADE; +DROP TABLE testpub_nopk, testpub_tbl_s1; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; +--------------------------------------------- +-- Tests for publications with SEQUENCES +--------------------------------------------- CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; -- FOR ALL SEQUENCES @@ -1970,6 +2253,54 @@ ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b); ERROR: column specification not allowed for schema LINE 1: ...TION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b)... ^ +-- EXCEPT clause with CURRENT_SCHEMA: cross-schema entry must be rejected +SET search_path = pub_test1; +-- qualified name from wrong schema -> error +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.tbl1); +ERROR: table "pub_test2.tbl1" in EXCEPT clause does not belong to schema "pub_test1" +LINE 1: ...FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.... + ^ +-- unqualified name implicitly qualified with current schema (pub_test1.tbl) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl); +RESET client_min_messages; +\dRp+ testpub_cursch_except + Publication testpub_cursch_except + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test1" +Except tables: + "pub_test1.tbl" + +DROP PUBLICATION testpub_cursch_except; +-- succeeds: CURRENT_SCHEMA and pub_test1 (same schema) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_named_same + FOR TABLES IN SCHEMA CURRENT_SCHEMA, pub_test1; +RESET client_min_messages; +\dRp+ testpub_cursch_named_same + Publication testpub_cursch_named_same + Owner | All tables | All sequences | Inserts | Updates | Deletes | Truncates | Generated columns | Via root | Description +--------------------------+------------+---------------+---------+---------+---------+-----------+-------------------+----------+------------- + regress_publication_user | f | f | t | t | t | t | none | f | +Tables from schemas: + "pub_test1" + +DROP PUBLICATION testpub_cursch_named_same; +-- fail: CURRENT_SCHEMA and pub_test1 (same schema) have +-- conflicting EXCEPT clauses +CREATE PUBLICATION testpub_cursch_named_conflict + FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl), + pub_test1 EXCEPT (TABLE tbl1); +ERROR: conflicting or redundant EXCEPT clauses for schema "pub_test1" +-- fail: two CURRENT_SCHEMA mentions with conflicting EXCEPT clauses +CREATE PUBLICATION testpub_cursch_cursch_conflict + FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl), + CURRENT_SCHEMA EXCEPT (TABLE tbl1); +ERROR: conflicting or redundant EXCEPT clauses for schema "pub_test1" +RESET search_path; -- cleanup pub_test1 schema for invalidation tests ALTER PUBLICATION testpub2_forschema DROP TABLES IN SCHEMA pub_test1; DROP PUBLICATION testpub3_forschema, testpub4_forschema, testpub5_forschema, testpub6_forschema, testpub_fortable; @@ -2321,6 +2652,7 @@ DROP ROLE regress_publication_user_dummy; -- Test pg_get_publication_tables(text[], oid) function CREATE SCHEMA gpt_test_sch; CREATE TABLE gpt_test_sch.tbl_sch (id int); +CREATE TABLE gpt_test_sch.tbl_sch2 (id int); CREATE TABLE tbl_normal (id int); CREATE TABLE tbl_parent (id1 int, id2 int, id3 int) PARTITION BY RANGE (id1); CREATE TABLE tbl_part1 PARTITION OF tbl_parent FOR VALUES FROM (1) TO (10); @@ -2331,6 +2663,7 @@ CREATE PUBLICATION pub_all_no_viaroot FOR ALL TABLES WITH (publish_via_partition CREATE PUBLICATION pub_all_except FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = true); CREATE PUBLICATION pub_all_except_no_viaroot FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_schema FOR TABLES IN SCHEMA gpt_test_sch; +CREATE PUBLICATION pub_schema_except FOR TABLES IN SCHEMA gpt_test_sch EXCEPT (TABLE gpt_test_sch.tbl_sch); CREATE PUBLICATION pub_normal FOR TABLE tbl_normal WHERE (id < 10); CREATE PUBLICATION pub_part_leaf FOR TABLE tbl_part1 WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_part_parent FOR TABLE tbl_parent (id1, id2) WHERE (id1 = 10) WITH (publish_via_partition_root = true); @@ -2482,6 +2815,50 @@ SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_part1'); -- no r ---------+---------+-------+------ (0 rows) +-- test for EXCEPT clause with schema publication +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch'); -- no result (excluded) + pubname | relname | attrs | qual +---------+---------+-------+------ +(0 rows) + +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch2'); -- one row (included via schema) + pubname | relname | attrs | qual +-------------------+----------+-------+------ + pub_schema_except | tbl_sch2 | 1 | +(1 row) + +-- test for EXCEPT clause with schema publication, where the excluded root's +-- partition lives in a different schema. Excluding the root also excludes its +-- partition, even though the partition is in another schema. Publishing that +-- schema as well creates a conflict because the partition would be both +-- published and excluded; without publishing the partition's schema, the +-- exclusion still cascades to the partition. +CREATE SCHEMA gpt_cross_sch1; +CREATE SCHEMA gpt_cross_sch2; +CREATE TABLE gpt_cross_sch1.croot (id int) PARTITION BY RANGE (id); +CREATE TABLE gpt_cross_sch2.cpart1 PARTITION OF gpt_cross_sch1.croot FOR VALUES FROM (1) TO (10); +-- fail: cpart1 would be published by its own schema and excluded through its root +CREATE PUBLICATION pub_cross_schema_except FOR TABLES IN SCHEMA gpt_cross_sch1 EXCEPT (TABLE gpt_cross_sch1.croot), TABLES IN SCHEMA gpt_cross_sch2; +ERROR: table "gpt_cross_sch2.cpart1" cannot be both published and excluded +DETAIL: It descends from "gpt_cross_sch1.croot", which is named in the EXCEPT clause of schema "gpt_cross_sch1". +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION pub_cross_schema_except FOR TABLES IN SCHEMA gpt_cross_sch1 EXCEPT (TABLE gpt_cross_sch1.croot); +RESET client_min_messages; +SELECT * FROM test_gpt(ARRAY['pub_cross_schema_except'], 'gpt_cross_sch1.croot'); -- no result (excluded) + pubname | relname | attrs | qual +---------+---------+-------+------ +(0 rows) + +-- no result: the root's exclusion cascades to the partition even though the +-- partition lives in a schema this publication does not mention +SELECT * FROM test_gpt(ARRAY['pub_cross_schema_except'], 'gpt_cross_sch2.cpart1'); + pubname | relname | attrs | qual +---------+---------+-------+------ +(0 rows) + +DROP PUBLICATION pub_cross_schema_except; +DROP TABLE gpt_cross_sch2.cpart1, gpt_cross_sch1.croot; +DROP SCHEMA gpt_cross_sch1, gpt_cross_sch2; -- two rows with different row filter SELECT * FROM test_gpt(ARRAY['pub_all', 'pub_normal'], 'tbl_normal'); pubname | relname | attrs | qual @@ -2534,6 +2911,7 @@ DROP PUBLICATION pub_all_no_viaroot; DROP PUBLICATION pub_all_except; DROP PUBLICATION pub_all_except_no_viaroot; DROP PUBLICATION pub_schema; +DROP PUBLICATION pub_schema_except; DROP PUBLICATION pub_normal; DROP PUBLICATION pub_part_leaf; DROP PUBLICATION pub_part_parent; @@ -2542,7 +2920,9 @@ DROP PUBLICATION pub_part_parent_child; DROP VIEW gpt_test_view; DROP TABLE tbl_normal, tbl_parent, tbl_part1; DROP SCHEMA gpt_test_sch CASCADE; -NOTICE: drop cascades to table gpt_test_sch.tbl_sch +NOTICE: drop cascades to 2 other objects +DETAIL: drop cascades to table gpt_test_sch.tbl_sch +drop cascades to table gpt_test_sch.tbl_sch2 -- stage objects for pg_dump tests CREATE SCHEMA pubme CREATE TABLE t0 (c int, d int) CREATE TABLE t1 (c int); CREATE SCHEMA pubme2 CREATE TABLE t0 (c int, d int); diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql index fac54b02e27..8258c0591da 100644 --- a/src/test/regress/sql/publication.sql +++ b/src/test/regress/sql/publication.sql @@ -125,6 +125,9 @@ CREATE PUBLICATION testpub_foralltables_excepttable1 FOR ALL TABLES EXCEPT (TABL \d testpub_tbl1 -- fail - first table in the EXCEPT list should use TABLE keyword CREATE PUBLICATION testpub_foralltables_excepttable2 FOR ALL TABLES EXCEPT (testpub_tbl1, testpub_tbl2); +-- fail - EXCEPT is not allowed for FOR TABLE publications +CREATE PUBLICATION testpub_except_err + FOR TABLE testpub_tbl1, testpub_tbl2 EXCEPT (TABLE testpub_tbl3); --------------------------------------------- -- SET ALL TABLES/SEQUENCES @@ -222,7 +225,177 @@ RESET client_min_messages; DROP TABLE testpub_root, testpub_part1, tab_main; DROP PUBLICATION testpub8; ---- Tests for publications with SEQUENCES +--------------------------------------------- +-- EXCEPT tests for TABLES IN SCHEMA +--------------------------------------------- +SET client_min_messages = 'ERROR'; +-- Create tables in pub_test for these tests +CREATE TABLE pub_test.testpub_tbl_s1 (a int primary key, b text); +CREATE TABLE pub_test.testpub_tbl_s2 (x int primary key, y text); +-- Create same-named tables in public to verify unqualified EXCEPT entries +-- are qualified with the named schema, not public +CREATE TABLE testpub_nopk (foo int, bar int); +CREATE TABLE testpub_tbl_s1 (a int primary key, b text); + +-- Basic: exclude one table from a schema publication +CREATE PUBLICATION testpub_schema_except1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_schema_except1 + +-- Exclude multiple tables using unqualified names; same-named tables exist in +-- public to confirm unqualified names resolve to pub_test, not public +CREATE PUBLICATION testpub_schema_except2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE testpub_nopk, testpub_tbl_s1); +\dRp+ testpub_schema_except2 + +-- fail: EXCEPT table belongs to a different schema +CREATE PUBLICATION testpub_except_wrongschema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE public.testpub_tbl1); + +-- fail: cross-schema EXCEPT not allowed; each EXCEPT is bound to its immediate schema +CREATE PUBLICATION testpub_except_crossschema + FOR TABLES IN SCHEMA pub_test, public EXCEPT (TABLE pub_test.testpub_tbl_s1, public.testpub_tbl1); + +-- Multiple schemas each with their own EXCEPT clause +CREATE PUBLICATION testpub_schema_except_multi + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + public EXCEPT (TABLE testpub_tbl1); +\dRp+ testpub_schema_except_multi + +-- fail: same schema repeated with same EXCEPT clauses +CREATE PUBLICATION testpub_schema_except_conflict + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: same schema repeated with conflicting or no EXCEPT clauses +CREATE PUBLICATION testpub_schema_except_conflict2 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1), + pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2), + pub_test; + +-- ALTER TABLE ... SET SCHEMA on a table excluded by a schema publication: +-- the schema-scoped exclusion is no longer meaningful once the table moves +-- out of its schema, so the exclusion is auto-removed. +CREATE PUBLICATION testpub_schema_except_setsch + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s2); +\dRp+ testpub_schema_except_setsch +ALTER TABLE pub_test.testpub_tbl_s2 SET SCHEMA public; +\dRp+ testpub_schema_except_setsch +DROP PUBLICATION testpub_schema_except_setsch; +-- Restore for further tests +ALTER TABLE public.testpub_tbl_s2 SET SCHEMA pub_test; + +-- fail: table appears in both the explicit table list and the EXCEPT clause +CREATE PUBLICATION testpub_except_conflict + FOR TABLE pub_test.testpub_tbl_s1, TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); + +-- fail: nonexistent table in EXCEPT clause +CREATE PUBLICATION testpub_except_norel + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.nonexistent_table); + +-- fail: partition cannot appear in EXCEPT clause; only root tables are allowed +CREATE TABLE pub_test.testpub_parted_s (a int) PARTITION BY LIST (a); +CREATE TABLE pub_test.testpub_part_s PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (1); +CREATE PUBLICATION testpub_except_partition + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_part_s); + +-- fail: TABLE keyword is required for the first entry in the EXCEPT clause +CREATE PUBLICATION testpub_except_nokw + FOR TABLES IN SCHEMA pub_test EXCEPT (testpub_nopk); + +-- Check that a table excluded from a schema publication is reported only as +-- excluded and not as published. +\d pub_test.testpub_nopk + +-- fail: ADD TABLE for a partition is rejected when a partition ancestor +-- is currently in the publication's EXCEPT list. +CREATE PUBLICATION testpub_except_ancestor + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); +ALTER PUBLICATION testpub_except_ancestor ADD TABLE pub_test.testpub_part_s; +DROP PUBLICATION testpub_except_ancestor; + +-- fail: same contradiction (explicit partition + EXCEPT-ed ancestor), but +-- given in a single statement instead of two separate ones +CREATE PUBLICATION testpub_except_ancestor_same_create + FOR TABLE pub_test.testpub_part_s, + TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s); + +-- fail: same contradiction as above, but the partition lives in a different +-- schema (public) than its EXCEPT-ed root (pub_test) +CREATE TABLE public.testpub_part_s2 PARTITION OF pub_test.testpub_parted_s FOR VALUES IN (2); +CREATE PUBLICATION testpub_except_ancestor_cross_schema + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_parted_s), + TABLE public.testpub_part_s2; +DROP TABLE public.testpub_part_s2; + +-- ALTER PUBLICATION ... SET replaces the publication's whole relation list, so +-- an existing entry for a relation now requested with the opposite kind must be +-- dropped and re-added, not silently left in place. +CREATE PUBLICATION testpub_except_alter1 + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +-- the excluded table becomes an ordinary member: one non-EXCEPT entry, no +-- EXCEPT entry, and no schema left in the publication +ALTER PUBLICATION testpub_except_alter1 SET TABLE pub_test.testpub_tbl_s1; +\dRp+ testpub_except_alter1 +DROP PUBLICATION testpub_except_alter1; + +-- and the reverse direction: an ordinary member becomes an EXCEPT entry +CREATE PUBLICATION testpub_except_alter2 FOR TABLE pub_test.testpub_tbl_s1; +ALTER PUBLICATION testpub_except_alter2 + SET TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_tbl_s1); +\dRp+ testpub_except_alter2 +DROP PUBLICATION testpub_except_alter2; + +-- Cross-schema inheritance children and EXCEPT. An EXCEPT clause also +-- excludes inheritance children of a parent named without ONLY. +CREATE TABLE pub_test.testpub_inh_parent (a int); +CREATE TABLE pub_test.testpub_inh_sibling (b int) INHERITS (pub_test.testpub_inh_parent); +CREATE TABLE testpub_inh_child (b int) INHERITS (pub_test.testpub_inh_parent); +CREATE PUBLICATION testpub_inh + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_inh_parent); +-- Two EXCEPT entries: the parent and the child in pub_test. +\dRp+ testpub_inh +DROP PUBLICATION testpub_inh; + +-- fail: the child testpub_inh_child is also included through TABLES IN SCHEM +-- public +CREATE PUBLICATION testpub_inh + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_inh_parent), + TABLES IN SCHEMA public; + +-- fail: the child is also explicitly included by the same statement +CREATE PUBLICATION testpub_inh + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_inh_parent), + TABLE testpub_inh_child; + +-- ONLY resolves the conflict: only the parent is excluded, so the child can +-- be published explicitly +CREATE PUBLICATION testpub_inh + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE ONLY pub_test.testpub_inh_parent), + TABLE testpub_inh_child; +\dRp+ testpub_inh +DROP PUBLICATION testpub_inh; + +-- An EXCEPT clause in the child's schema also excludes the child explicitly, +-- so both clauses agree and there is no conflict. +CREATE PUBLICATION testpub_inh + FOR TABLES IN SCHEMA pub_test EXCEPT (TABLE pub_test.testpub_inh_parent), + TABLES IN SCHEMA public EXCEPT (TABLE testpub_inh_child); +\dRp+ testpub_inh +DROP PUBLICATION testpub_inh; +DROP TABLE testpub_inh_child, pub_test.testpub_inh_sibling, + pub_test.testpub_inh_parent; + +-- Cleanup +RESET client_min_messages; +DROP TABLE pub_test.testpub_tbl_s1, pub_test.testpub_tbl_s2; +DROP TABLE pub_test.testpub_parted_s CASCADE; +DROP TABLE testpub_nopk, testpub_tbl_s1; +DROP PUBLICATION testpub_schema_except1, testpub_schema_except2, testpub_schema_except_multi; + +--------------------------------------------- +-- Tests for publications with SEQUENCES +--------------------------------------------- CREATE SEQUENCE regress_pub_seq0; CREATE SEQUENCE pub_test.regress_pub_seq1; @@ -1194,6 +1367,38 @@ ALTER PUBLICATION testpub1_forschema SET TABLES IN SCHEMA pub_test1, pub_test1; ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo (a, b); ALTER PUBLICATION testpub1_forschema ADD TABLES IN SCHEMA foo, bar (a, b); +-- EXCEPT clause with CURRENT_SCHEMA: cross-schema entry must be rejected +SET search_path = pub_test1; +-- qualified name from wrong schema -> error +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE pub_test2.tbl1); +-- unqualified name implicitly qualified with current schema (pub_test1.tbl) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_except FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl); +RESET client_min_messages; +\dRp+ testpub_cursch_except +DROP PUBLICATION testpub_cursch_except; + +-- succeeds: CURRENT_SCHEMA and pub_test1 (same schema) +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION testpub_cursch_named_same + FOR TABLES IN SCHEMA CURRENT_SCHEMA, pub_test1; +RESET client_min_messages; +\dRp+ testpub_cursch_named_same +DROP PUBLICATION testpub_cursch_named_same; + +-- fail: CURRENT_SCHEMA and pub_test1 (same schema) have +-- conflicting EXCEPT clauses +CREATE PUBLICATION testpub_cursch_named_conflict + FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl), + pub_test1 EXCEPT (TABLE tbl1); + +-- fail: two CURRENT_SCHEMA mentions with conflicting EXCEPT clauses +CREATE PUBLICATION testpub_cursch_cursch_conflict + FOR TABLES IN SCHEMA CURRENT_SCHEMA EXCEPT (TABLE tbl), + CURRENT_SCHEMA EXCEPT (TABLE tbl1); + +RESET search_path; + -- cleanup pub_test1 schema for invalidation tests ALTER PUBLICATION testpub2_forschema DROP TABLES IN SCHEMA pub_test1; DROP PUBLICATION testpub3_forschema, testpub4_forschema, testpub5_forschema, testpub6_forschema, testpub_fortable; @@ -1448,6 +1653,7 @@ DROP ROLE regress_publication_user_dummy; -- Test pg_get_publication_tables(text[], oid) function CREATE SCHEMA gpt_test_sch; CREATE TABLE gpt_test_sch.tbl_sch (id int); +CREATE TABLE gpt_test_sch.tbl_sch2 (id int); CREATE TABLE tbl_normal (id int); CREATE TABLE tbl_parent (id1 int, id2 int, id3 int) PARTITION BY RANGE (id1); CREATE TABLE tbl_part1 PARTITION OF tbl_parent FOR VALUES FROM (1) TO (10); @@ -1459,6 +1665,7 @@ CREATE PUBLICATION pub_all_no_viaroot FOR ALL TABLES WITH (publish_via_partition CREATE PUBLICATION pub_all_except FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = true); CREATE PUBLICATION pub_all_except_no_viaroot FOR ALL TABLES EXCEPT (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_schema FOR TABLES IN SCHEMA gpt_test_sch; +CREATE PUBLICATION pub_schema_except FOR TABLES IN SCHEMA gpt_test_sch EXCEPT (TABLE gpt_test_sch.tbl_sch); CREATE PUBLICATION pub_normal FOR TABLE tbl_normal WHERE (id < 10); CREATE PUBLICATION pub_part_leaf FOR TABLE tbl_part1 WITH (publish_via_partition_root = false); CREATE PUBLICATION pub_part_parent FOR TABLE tbl_parent (id1, id2) WHERE (id1 = 10) WITH (publish_via_partition_root = true); @@ -1515,6 +1722,37 @@ SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'gpt_test_sch.tbl_sch SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_parent'); -- no result (excluded) SELECT * FROM test_gpt(ARRAY['pub_all_except_no_viaroot'], 'tbl_part1'); -- no result +-- test for EXCEPT clause with schema publication +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch'); -- no result (excluded) +SELECT * FROM test_gpt(ARRAY['pub_schema_except'], 'gpt_test_sch.tbl_sch2'); -- one row (included via schema) + +-- test for EXCEPT clause with schema publication, where the excluded root's +-- partition lives in a different schema. Excluding the root also excludes its +-- partition, even though the partition is in another schema. Publishing that +-- schema as well creates a conflict because the partition would be both +-- published and excluded; without publishing the partition's schema, the +-- exclusion still cascades to the partition. +CREATE SCHEMA gpt_cross_sch1; +CREATE SCHEMA gpt_cross_sch2; +CREATE TABLE gpt_cross_sch1.croot (id int) PARTITION BY RANGE (id); +CREATE TABLE gpt_cross_sch2.cpart1 PARTITION OF gpt_cross_sch1.croot FOR VALUES FROM (1) TO (10); + +-- fail: cpart1 would be published by its own schema and excluded through its root +CREATE PUBLICATION pub_cross_schema_except FOR TABLES IN SCHEMA gpt_cross_sch1 EXCEPT (TABLE gpt_cross_sch1.croot), TABLES IN SCHEMA gpt_cross_sch2; + +SET client_min_messages = 'ERROR'; +CREATE PUBLICATION pub_cross_schema_except FOR TABLES IN SCHEMA gpt_cross_sch1 EXCEPT (TABLE gpt_cross_sch1.croot); +RESET client_min_messages; + +SELECT * FROM test_gpt(ARRAY['pub_cross_schema_except'], 'gpt_cross_sch1.croot'); -- no result (excluded) +-- no result: the root's exclusion cascades to the partition even though the +-- partition lives in a schema this publication does not mention +SELECT * FROM test_gpt(ARRAY['pub_cross_schema_except'], 'gpt_cross_sch2.cpart1'); + +DROP PUBLICATION pub_cross_schema_except; +DROP TABLE gpt_cross_sch2.cpart1, gpt_cross_sch1.croot; +DROP SCHEMA gpt_cross_sch1, gpt_cross_sch2; + -- two rows with different row filter SELECT * FROM test_gpt(ARRAY['pub_all', 'pub_normal'], 'tbl_normal'); @@ -1543,6 +1781,7 @@ DROP PUBLICATION pub_all_no_viaroot; DROP PUBLICATION pub_all_except; DROP PUBLICATION pub_all_except_no_viaroot; DROP PUBLICATION pub_schema; +DROP PUBLICATION pub_schema_except; DROP PUBLICATION pub_normal; DROP PUBLICATION pub_part_leaf; DROP PUBLICATION pub_part_parent; diff --git a/src/test/subscription/t/037_except.pl b/src/test/subscription/t/037_except.pl index 43b51c8ff71..de4e7dff7ba 100644 --- a/src/test/subscription/t/037_except.pl +++ b/src/test/subscription/t/037_except.pl @@ -24,14 +24,17 @@ my $result; sub test_except_root_partition { - my ($pubviaroot) = @_; + my ($pubviaroot, $pubsql) = @_; + $pubsql //= + "CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1)"; + $pubsql .= " WITH (publish_via_partition_root = $pubviaroot)"; # If the root partitioned table is in the EXCEPT clause, all its # partitions are excluded from publication, regardless of the # publish_via_partition_root setting. $node_publisher->safe_psql( 'postgres', qq( - CREATE PUBLICATION tap_pub_part FOR ALL TABLES EXCEPT (TABLE root1) WITH (publish_via_partition_root = $pubviaroot); + $pubsql; INSERT INTO root1 VALUES (1), (101); )); $node_subscriber->safe_psql('postgres', @@ -223,6 +226,208 @@ $node_subscriber->safe_psql( test_except_root_partition('false'); test_except_root_partition('true'); +# Same validation using TABLES IN SCHEMA instead of FOR ALL TABLES. +my $schema_pub = + "CREATE PUBLICATION tap_pub_part FOR TABLES IN SCHEMA public EXCEPT (TABLE public.root1)"; +test_except_root_partition('false', $schema_pub); +test_except_root_partition('true', $schema_pub); + +# ============================================ +# EXCEPT test cases for TABLES IN SCHEMA +# ============================================ + +# Create a dedicated schema with two tables: one to be published and one to be +# excluded. Also create inherited tables to verify ONLY semantics. +$node_publisher->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_published AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.tab_excluded AS SELECT generate_series(1,5) AS a; + CREATE TABLE sch1.parent (a int); + CREATE TABLE sch1.child (b int) INHERITS (sch1.parent); +)); + +$node_subscriber->safe_psql( + 'postgres', qq( + CREATE SCHEMA sch1; + CREATE TABLE sch1.tab_published (a int); + CREATE TABLE sch1.tab_excluded (a int); + CREATE TABLE sch1.parent (a int); + CREATE TABLE sch1.child (b int) INHERITS (sch1.parent); +)); + +# Basic test: initial sync respects EXCEPT. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.tab_excluded)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: initial sync copies included table'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: initial sync skips excluded table'); + +# DML: only the included table should be replicated. +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO sch1.tab_published VALUES (6); + INSERT INTO sch1.tab_excluded VALUES (6); +)); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_published"); +is($result, qq(6), + 'TABLES IN SCHEMA EXCEPT: DML on included table is replicated'); +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM sch1.tab_excluded"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: DML on excluded table is not replicated'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Inherited tables: excluding the parent (without ONLY) also excludes the child. +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE sch1.parent)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.child VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.child"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: excluding parent (without ONLY) also excludes child' +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Test that EXCEPT (TABLE ONLY parent) excludes only the parent itself, not its +# child. Truncate child first so rows from the previous test are not copied by +# the initial table sync of the next subscription. +$node_publisher->safe_psql('postgres', 'TRUNCATE sch1.child'); +$node_subscriber->safe_psql('postgres', 'TRUNCATE sch1.child'); +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION sch_pub FOR TABLES IN SCHEMA sch1 EXCEPT (TABLE ONLY sch1.parent)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION sch_sub CONNECTION '$publisher_connstr' PUBLICATION sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'sch_sub'); + +$node_publisher->safe_psql('postgres', + "INSERT INTO sch1.child VALUES (generate_series(1,5), generate_series(1,5))" +); +$node_publisher->wait_for_catchup('sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM sch1.child"); +is($result, qq(5), + 'TABLES IN SCHEMA EXCEPT: ONLY parent in EXCEPT does not exclude child'); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION sch_pub'); + +# Cleanup schema tables before the multi-publication section. +$node_publisher->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); +$node_subscriber->safe_psql('postgres', 'DROP SCHEMA sch1 CASCADE'); + +# ============================================ +# EXCEPT test cases for TABLES IN SCHEMA with a cross-schema partition +# ============================================ + +# A partition can live in a different schema than its partitioned root. If +# the root is excluded via EXCEPT under its own schema's clause, the exclusion +# must cascade to all its partitions, including those in other schemas. +# +# The partition's own schema is deliberately not published here: naming it +# alongside the EXCEPT clause is rejected, because the clause's reach stops at +# its own schema and the two would then disagree about the partition. +$node_publisher->safe_psql( + 'postgres', qq( + CREATE SCHEMA csch1; + CREATE SCHEMA csch2; + CREATE TABLE csch1.croot(a int) PARTITION BY RANGE(a); + CREATE TABLE csch2.cpart1 PARTITION OF csch1.croot FOR VALUES FROM (0) TO (100); + INSERT INTO csch1.croot VALUES (generate_series(1,5)); +)); + +$node_subscriber->safe_psql( + 'postgres', qq( + CREATE SCHEMA csch1; + CREATE SCHEMA csch2; + CREATE TABLE csch1.croot(a int); + CREATE TABLE csch2.cpart1(a int); +)); + +$node_publisher->safe_psql('postgres', + "CREATE PUBLICATION cross_sch_pub FOR TABLES IN SCHEMA csch1 EXCEPT (TABLE csch1.croot) WITH (publish_via_partition_root = false)" +); +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION cross_sch_sub CONNECTION '$publisher_connstr' PUBLICATION cross_sch_pub" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, 'cross_sch_sub'); + +# Baseline: the root itself, pre-populated with rows before the subscription +# was created, is excluded by its own schema's EXCEPT clause -- initial sync +# must not have copied it. +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM csch1.croot"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: cross-schema partition root is excluded by initial sync' +); + +# Regression case: the partition's own schema (csch2) is separately, fully +# included with no EXCEPT, but the root's exclusion must still cascade to it +# -- initial sync must not have copied the pre-existing rows routed into this +# partition via the root. +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM csch2.cpart1"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: cross-schema partition is excluded by initial sync via cascading root exclusion' +); + +# Insert distinct, identifiable data directly into the partition and verify +# it is not replicated either. +$node_publisher->safe_psql('postgres', + "INSERT INTO csch2.cpart1 VALUES (generate_series(1,5))"); +$node_publisher->wait_for_catchup('cross_sch_sub'); + +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM csch1.croot"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: cross-schema partition root remains excluded after DML' +); +$result = + $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM csch2.cpart1"); +is($result, qq(0), + 'TABLES IN SCHEMA EXCEPT: cross-schema partition remains excluded after DML via cascading root exclusion' +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION cross_sch_sub'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION cross_sch_pub'); +$node_publisher->safe_psql('postgres', 'DROP SCHEMA csch1, csch2 CASCADE'); +$node_subscriber->safe_psql('postgres', 'DROP SCHEMA csch1, csch2 CASCADE'); + # ============================================ # Test when a subscription is subscribing to multiple publications # ============================================ @@ -254,6 +459,7 @@ $node_publisher->safe_psql( DROP PUBLICATION tap_pub2; TRUNCATE tab1; )); +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_subscriber->safe_psql('postgres', qq(TRUNCATE tab1)); # OK when a table is excluded by pub1 EXCEPT clause, but it is included by pub2 @@ -282,6 +488,59 @@ $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub1'); $node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub2'); +# OK when a table is excluded by the EXCEPT clause of one schema publication, +# but it is included by another publication that publishes the same schema in +# full. Inclusion wins, so the table is replicated. +$node_publisher->safe_psql( + 'postgres', qq( + CREATE SCHEMA msch; + CREATE TABLE msch.tab_excl (a int); + INSERT INTO msch.tab_excl VALUES (1); + CREATE PUBLICATION tap_pub_sch_with_except + FOR TABLES IN SCHEMA msch EXCEPT (TABLE msch.tab_excl); + CREATE PUBLICATION tap_pub_sch_without_except FOR TABLES IN SCHEMA msch; +)); + +$node_subscriber->safe_psql( + 'postgres', qq( + CREATE SCHEMA msch; + CREATE TABLE msch.tab_excl (a int); +)); + +$node_subscriber->safe_psql('postgres', + "CREATE SUBSCRIPTION tap_sub_multi CONNECTION '$publisher_connstr' PUBLICATION tap_pub_sch_with_except, tap_pub_sch_without_except" +); +$node_subscriber->wait_for_subscription_sync($node_publisher, + 'tap_sub_multi'); + +# The initial table sync must copy the excluded table too, because +# tap_pub_sch_without_except publishes it. +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM msch.tab_excl"); +is($result, qq(1), + 'initial sync copies a table excluded by one publication but included by another' +); + +$node_publisher->safe_psql( + 'postgres', qq( + INSERT INTO msch.tab_excl VALUES (2); +)); +$node_publisher->wait_for_catchup('tap_sub_multi'); + +$result = + $node_subscriber->safe_psql('postgres', + "SELECT count(*) FROM msch.tab_excl"); +is($result, qq(2), + 'DML on a table excluded by one publication but included by another is replicated' +); + +$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub_multi'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub_sch_with_except'); +$node_publisher->safe_psql('postgres', 'DROP PUBLICATION tap_pub_sch_without_except'); +$node_publisher->safe_psql('postgres', 'DROP SCHEMA msch CASCADE'); +$node_subscriber->safe_psql('postgres', 'DROP SCHEMA msch CASCADE'); + $node_publisher->stop('fast'); done_testing(); -- 2.55.0
^ permalink raw reply [nested|flat] 196+ messages in thread

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-19 22:47  Peter Smith <smithpb2250@gmail.com>
  parent: vignesh C <vignesh21@gmail.com>
  1 sibling, 1 reply; 196+ messages in thread

From: Peter Smith @ 2026-08-19 22:47 UTC (permalink / raw)
  To: vignesh C <vignesh21@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Nisha Moond <nisha.moond412@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Wed, Aug 19, 2026 at 8:17 PM vignesh C <vignesh21@gmail.com> wrote:
>
> On Tue, 18 Aug 2026 at 13:34, Peter Smith <smithpb2250@gmail.com> wrote:
> >
> > Hi Vignesh/Nisha,
> >
> > IMO, it feels like these patches are doing too much work trying to
> > protect the user from themselves, and it is even making some
> > combinations difficult to specify.
> >
> > Also, there is a lot of logic and many lines of code now just for
> > checking publication command "inconsistencies".
>
> I still feel we should throw the error at CREATE PUBLICATION itself.
> That would make the conflict clear to the user and allow them to
> modify the publication accordingly. Otherwise, in a conflicting case
> like the following, it may be unclear whether the table will actually
> be published:
> CREATE TABLE s1.parent (a int);
> CREATE TABLE s2.child (b int) INHERITS (s1.parent);
> CREATE PUBLICATION pub1 FOR TABLES IN SCHEMA s1 EXCEPT (TABLE s1.parent), s2;
>

Yeah, but is that even a conflict? AFAICT, it is considered a
"conflict" only because you assume the user has made a mistake. OTOH,
if you trust the user really wanted a publication with "everything
from schemas s1 and s2 but excluding the parent/children tree", then
the command could be considered valid, right?

> Here, it may not be obvious whether s2.child will be published because
> schema s2 is included, or whether it will be skipped because its
> parent s1.parent is specified in the EXCEPT clause.

It is unambiguous by this simple rule:
"RULE 1:  Fine-grained clauses take precedence (so anything the user
says about a TABLE takes precedence over whatever they say about a
SCHEMA)"
In your example, the exclusion of the TABLE `parent` and its children
takes precedence over the inclusion of all tables from SCHEMA s2.

~

The patches have grown a lot with the recent conflict checking code:
v25-0001 -- 2001 lines
v26-0001 -- 2085 lines
v27-0001 -- 2514 lines
v28-0001 -- 2597 lines
v29-0001 -- 2541 lines

Perhaps my proposed rule has unknown flaws in it, but I'd hoped to
explore how much simpler the patch implementation would be if we just
assumed users know what they are doing.

======
Kind Regards,
Peter Smith.
Fujitsu Australia






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-19 23:35  Peter Smith <smithpb2250@gmail.com>
  parent: Peter Smith <smithpb2250@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: Peter Smith @ 2026-08-19 23:35 UTC (permalink / raw)
  To: vignesh C <vignesh21@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Nisha Moond <nisha.moond412@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Thu, Aug 20, 2026 at 8:47 AM Peter Smith <smithpb2250@gmail.com> wrote:
>
> On Wed, Aug 19, 2026 at 8:17 PM vignesh C <vignesh21@gmail.com> wrote:
> >
> > On Tue, 18 Aug 2026 at 13:34, Peter Smith <smithpb2250@gmail.com> wrote:
> > >
> > > Hi Vignesh/Nisha,
> > >
> > > IMO, it feels like these patches are doing too much work trying to
> > > protect the user from themselves, and it is even making some
> > > combinations difficult to specify.
> > >
> > > Also, there is a lot of logic and many lines of code now just for
> > > checking publication command "inconsistencies".
> >
> > I still feel we should throw the error at CREATE PUBLICATION itself.
> > That would make the conflict clear to the user and allow them to
> > modify the publication accordingly. Otherwise, in a conflicting case
> > like the following, it may be unclear whether the table will actually
> > be published:
> > CREATE TABLE s1.parent (a int);
> > CREATE TABLE s2.child (b int) INHERITS (s1.parent);
> > CREATE PUBLICATION pub1 FOR TABLES IN SCHEMA s1 EXCEPT (TABLE s1.parent), s2;
> >
>
> Yeah, but is that even a conflict? AFAICT, it is considered a
> "conflict" only because you assume the user has made a mistake. OTOH,
> if you trust the user really wanted a publication with "everything
> from schemas s1 and s2 but excluding the parent/children tree", then
> the command could be considered valid, right?
>
> > Here, it may not be obvious whether s2.child will be published because
> > schema s2 is included, or whether it will be skipped because its
> > parent s1.parent is specified in the EXCEPT clause.
>
> It is unambiguous by this simple rule:
> "RULE 1:  Fine-grained clauses take precedence (so anything the user
> says about a TABLE takes precedence over whatever they say about a
> SCHEMA)"
> In your example, the exclusion of the TABLE `parent` and its children
> takes precedence over the inclusion of all tables from SCHEMA s2.
>
> ~
>
> The patches have grown a lot with the recent conflict checking code:
> v25-0001 -- 2001 lines
> v26-0001 -- 2085 lines
> v27-0001 -- 2514 lines
> v28-0001 -- 2597 lines
> v29-0001 -- 2541 lines
>
> Perhaps my proposed rule has unknown flaws in it, but I'd hoped to
> explore how much simpler the patch implementation would be if we just
> assumed users know what they are doing.
>

Hmm... One problem with my "fine-grained TABLE versus coarse-grained
SCHEMA" rule is exposed in this trickier example:
Ex1. ... FOR TABLES IN SCHEMA s1 EXCEPT (TABLE s1.parent), s2;

I'd earlier suggested the parent INHERITS should reach across into the
schema s2 and exclude s2.child there too, because that looks like what
the user was asking for.

But for this:
Ex2. ... FOR TABLE s1.parent, TABLES IN SCHEMA s2 EXCEPT (TABLE s2.child);

Saying the INHERITS reaches into schema s2 is new behaviour, and it
may be ambiguous
- Is s2.child included because parent INHERITS reached into schema s2
and included it?
- Or is s2.child excluded because of the EXCEPT (TABLE s2.child)?

======
Kind Regards,
Peter Smith.
Fujitsu Australia






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-20 08:39  shveta malik <shveta.malik@gmail.com>
  parent: vignesh C <vignesh21@gmail.com>
  1 sibling, 1 reply; 196+ messages in thread

From: shveta malik @ 2026-08-20 08:39 UTC (permalink / raw)
  To: vignesh C <vignesh21@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; Nisha Moond <nisha.moond412@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; shveta malik <shveta.malik@gmail.com>

On Wed, Aug 19, 2026 at 3:47 PM vignesh C <vignesh21@gmail.com> wrote:
>
> On Tue, 18 Aug 2026 at 13:34, Peter Smith <smithpb2250@gmail.com> wrote:
> >
> > Hi Vignesh/Nisha,
> >
> > IMO, it feels like these patches are doing too much work trying to
> > protect the user from themselves, and it is even making some
> > combinations difficult to specify.
> >
> > Also, there is a lot of logic and many lines of code now just for
> > checking publication command "inconsistencies".
>
> I still feel we should throw the error at CREATE PUBLICATION itself.
> That would make the conflict clear to the user and allow them to
> modify the publication accordingly.

Okay. Noted.

> Otherwise, in a conflicting case
> like the following, it may be unclear whether the table will actually
> be published:
> CREATE TABLE s1.parent (a int);
> CREATE TABLE s2.child (b int) INHERITS (s1.parent);
> CREATE PUBLICATION pub1 FOR TABLES IN SCHEMA s1 EXCEPT (TABLE s1.parent), s2;
>
> Here, it may not be obvious whether s2.child will be published because
> schema s2 is included, or whether it will be skipped because its
> parent s1.parent is specified in the EXCEPT clause.
>
> I have tried to simplify the patch.

Yes, it looks simpler compared to v28.

> The new version now only has two
> changes to detect the new conflicts:
> a) GetExceptCrossSchemaDescendants - Collects descendants of the
> EXCEPT entries that reside outside the schema of the corresponding
> TABLES IN SCHEMA clause.
> b) Add few additional checks to the existing
> CheckExceptConflicts(renamed from CheckExceptNotInTableList)
> Checks whether any of these cross-schema descendants are also being
> published, either explicitly or through another TABLES IN SCHEMA
> clause, and throws an error if they are.
>
> Please have a look and let me know whether the v29 version is simpler.
>

I had a quick look, it looks better than v28. I will review and
validate it in detail by tomorrow.

thanks
Shveta





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-20 09:03  shveta malik <shveta.malik@gmail.com>
  parent: Peter Smith <smithpb2250@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: shveta malik @ 2026-08-20 09:03 UTC (permalink / raw)
  To: Peter Smith <smithpb2250@gmail.com>; +Cc: vignesh C <vignesh21@gmail.com>; Nisha Moond <nisha.moond412@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; shveta malik <shveta.malik@gmail.com>

On Thu, Aug 20, 2026 at 5:05 AM Peter Smith <smithpb2250@gmail.com> wrote:
>
> On Thu, Aug 20, 2026 at 8:47 AM Peter Smith <smithpb2250@gmail.com> wrote:
> >
> > On Wed, Aug 19, 2026 at 8:17 PM vignesh C <vignesh21@gmail.com> wrote:
> > >
> > > On Tue, 18 Aug 2026 at 13:34, Peter Smith <smithpb2250@gmail.com> wrote:
> > > >
> > > > Hi Vignesh/Nisha,
> > > >
> > > > IMO, it feels like these patches are doing too much work trying to
> > > > protect the user from themselves, and it is even making some
> > > > combinations difficult to specify.
> > > >
> > > > Also, there is a lot of logic and many lines of code now just for
> > > > checking publication command "inconsistencies".
> > >
> > > I still feel we should throw the error at CREATE PUBLICATION itself.
> > > That would make the conflict clear to the user and allow them to
> > > modify the publication accordingly. Otherwise, in a conflicting case
> > > like the following, it may be unclear whether the table will actually
> > > be published:
> > > CREATE TABLE s1.parent (a int);
> > > CREATE TABLE s2.child (b int) INHERITS (s1.parent);
> > > CREATE PUBLICATION pub1 FOR TABLES IN SCHEMA s1 EXCEPT (TABLE s1.parent), s2;
> > >
> >
> > Yeah, but is that even a conflict? AFAICT, it is considered a
> > "conflict" only because you assume the user has made a mistake. OTOH,
> > if you trust the user really wanted a publication with "everything
> > from schemas s1 and s2 but excluding the parent/children tree", then
> > the command could be considered valid, right?
> >
> > > Here, it may not be obvious whether s2.child will be published because
> > > schema s2 is included, or whether it will be skipped because its
> > > parent s1.parent is specified in the EXCEPT clause.
> >
> > It is unambiguous by this simple rule:
> > "RULE 1:  Fine-grained clauses take precedence (so anything the user
> > says about a TABLE takes precedence over whatever they say about a
> > SCHEMA)"
> > In your example, the exclusion of the TABLE `parent` and its children
> > takes precedence over the inclusion of all tables from SCHEMA s2.
> >
> > ~
> >
> > The patches have grown a lot with the recent conflict checking code:
> > v25-0001 -- 2001 lines
> > v26-0001 -- 2085 lines
> > v27-0001 -- 2514 lines
> > v28-0001 -- 2597 lines
> > v29-0001 -- 2541 lines
> >
> > Perhaps my proposed rule has unknown flaws in it, but I'd hoped to
> > explore how much simpler the patch implementation would be if we just
> > assumed users know what they are doing.
> >
>
> Hmm... One problem with my "fine-grained TABLE versus coarse-grained
> SCHEMA" rule is exposed in this trickier example:
> Ex1. ... FOR TABLES IN SCHEMA s1 EXCEPT (TABLE s1.parent), s2;
>
> I'd earlier suggested the parent INHERITS should reach across into the
> schema s2 and exclude s2.child there too, because that looks like what
> the user was asking for.
>
> But for this:
> Ex2. ... FOR TABLE s1.parent, TABLES IN SCHEMA s2 EXCEPT (TABLE s2.child);
>
> Saying the INHERITS reaches into schema s2 is new behaviour, and it
> may be ambiguous
> - Is s2.child included because parent INHERITS reached into schema s2
> and included it?
> - Or is s2.child excluded because of the EXCEPT (TABLE s2.child)?
>

Yes, it is certainly an ambiguous scenario, and we cannot reliably
guess the user's intent. IMO, throwing an error in such cases is the
most appropriate approach. If we do that, we should apply the same
principle to the other cases as well, which would bring us back to the
approach implemented in v28 (optimized further in v29). What do you
say?

thanks
Shveta






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-21 04:30  Peter Smith <smithpb2250@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  0 siblings, 0 replies; 196+ messages in thread

From: Peter Smith @ 2026-08-21 04:30 UTC (permalink / raw)
  To: shveta malik <shveta.malik@gmail.com>; +Cc: vignesh C <vignesh21@gmail.com>; Nisha Moond <nisha.moond412@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Thu, Aug 20, 2026 at 7:04 PM shveta malik <shveta.malik@gmail.com> wrote:
>
> On Thu, Aug 20, 2026 at 5:05 AM Peter Smith <smithpb2250@gmail.com> wrote:
> >
> > On Thu, Aug 20, 2026 at 8:47 AM Peter Smith <smithpb2250@gmail.com> wrote:
> > >
> > > On Wed, Aug 19, 2026 at 8:17 PM vignesh C <vignesh21@gmail.com> wrote:
> > > >
> > > > On Tue, 18 Aug 2026 at 13:34, Peter Smith <smithpb2250@gmail.com> wrote:
> > > > >
> > > > > Hi Vignesh/Nisha,
> > > > >
> > > > > IMO, it feels like these patches are doing too much work trying to
> > > > > protect the user from themselves, and it is even making some
> > > > > combinations difficult to specify.
> > > > >
> > > > > Also, there is a lot of logic and many lines of code now just for
> > > > > checking publication command "inconsistencies".
> > > >
> > > > I still feel we should throw the error at CREATE PUBLICATION itself.
> > > > That would make the conflict clear to the user and allow them to
> > > > modify the publication accordingly. Otherwise, in a conflicting case
> > > > like the following, it may be unclear whether the table will actually
> > > > be published:
> > > > CREATE TABLE s1.parent (a int);
> > > > CREATE TABLE s2.child (b int) INHERITS (s1.parent);
> > > > CREATE PUBLICATION pub1 FOR TABLES IN SCHEMA s1 EXCEPT (TABLE s1.parent), s2;
> > > >
> > >
> > > Yeah, but is that even a conflict? AFAICT, it is considered a
> > > "conflict" only because you assume the user has made a mistake. OTOH,
> > > if you trust the user really wanted a publication with "everything
> > > from schemas s1 and s2 but excluding the parent/children tree", then
> > > the command could be considered valid, right?
> > >
> > > > Here, it may not be obvious whether s2.child will be published because
> > > > schema s2 is included, or whether it will be skipped because its
> > > > parent s1.parent is specified in the EXCEPT clause.
> > >
> > > It is unambiguous by this simple rule:
> > > "RULE 1:  Fine-grained clauses take precedence (so anything the user
> > > says about a TABLE takes precedence over whatever they say about a
> > > SCHEMA)"
> > > In your example, the exclusion of the TABLE `parent` and its children
> > > takes precedence over the inclusion of all tables from SCHEMA s2.
> > >
> > > ~
> > >
> > > The patches have grown a lot with the recent conflict checking code:
> > > v25-0001 -- 2001 lines
> > > v26-0001 -- 2085 lines
> > > v27-0001 -- 2514 lines
> > > v28-0001 -- 2597 lines
> > > v29-0001 -- 2541 lines
> > >
> > > Perhaps my proposed rule has unknown flaws in it, but I'd hoped to
> > > explore how much simpler the patch implementation would be if we just
> > > assumed users know what they are doing.
> > >
> >
> > Hmm... One problem with my "fine-grained TABLE versus coarse-grained
> > SCHEMA" rule is exposed in this trickier example:
> > Ex1. ... FOR TABLES IN SCHEMA s1 EXCEPT (TABLE s1.parent), s2;
> >
> > I'd earlier suggested the parent INHERITS should reach across into the
> > schema s2 and exclude s2.child there too, because that looks like what
> > the user was asking for.
> >
> > But for this:
> > Ex2. ... FOR TABLE s1.parent, TABLES IN SCHEMA s2 EXCEPT (TABLE s2.child);
> >
> > Saying the INHERITS reaches into schema s2 is new behaviour, and it
> > may be ambiguous
> > - Is s2.child included because parent INHERITS reached into schema s2
> > and included it?
> > - Or is s2.child excluded because of the EXCEPT (TABLE s2.child)?
> >
>
> Yes, it is certainly an ambiguous scenario, and we cannot reliably
> guess the user's intent. IMO, throwing an error in such cases is the
> most appropriate approach. If we do that, we should apply the same
> principle to the other cases as well, which would bring us back to the
> approach implemented in v28 (optimized further in v29). What do you
> say?

Yes, my goal was to make things better, If, as it appears to, my
proposal just ends up trading one set of issues for a different set,
of issues then we can forget about it and stick with what we already
have with v28/29.

======
Kind Reagrds,
Peter Smith.
Fujitsu Australia





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-21 04:54  shveta malik <shveta.malik@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: shveta malik @ 2026-08-21 04:54 UTC (permalink / raw)
  To: vignesh C <vignesh21@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; Nisha Moond <nisha.moond412@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; shveta malik <shveta.malik@gmail.com>

On Thu, Aug 20, 2026 at 2:09 PM shveta malik <shveta.malik@gmail.com> wrote:
>
> I had a quick look, it looks better than v28. I will review and
> validate it in detail by tomorrow.
>

The code looks simpler IMO and manageable for supporting all these
contradictory error scenarios.

I verified the inherited table cases alone. I have a few concerns:

1)
postgres=# CREATE PUBLICATION pub1 FOR TABLE s2.child, TABLES IN
SCHEMA s1 EXCEPT (TABLE s1.parent);
ERROR:  table "s2.child" cannot be both published and excluded
DETAIL:  It descends from "s1.parent", which is named in the EXCEPT
clause of schema "s1".

postgres=# CREATE PUBLICATION pub1 FOR TABLE s1.parent*, TABLES IN
SCHEMA s2 EXCEPT (TABLE s2.child);
ERROR:  table "s2.child" cannot be both published and excluded

Can we have a similar DETAIL message in second as well?

2)
I find this case still a little ambiguous:

CREATE PUBLICATION pub1 FOR TABLES IN SCHEMA s1, TABLES IN SCHEMA s2
EXCEPT (TABLE s2.child);

Currently it works, but should it?

a) Should s2.child be published because s1.parent is included, and
schema s2 is also included, meaning cross-schema inheritance
boundaries are respected and brought back in?

b) Or should s2.child remain excluded because of the explicit EXCEPT
(TABLE s2.child) clause?

Currently, we throw an error for the reverse scenario:

CREATE PUBLICATION pub1 FOR TABLES IN SCHEMA s1 EXCEPT (TABLE
s1.parent), TABLES IN SCHEMA s2;
ERROR:  table "s2.child" cannot be both published and excluded
DETAIL:  It descends from "s1.parent", which is named in the EXCEPT
clause of schema "s1".

(Because s1.parent implicitly acts like s1.parent* and s2 is also
included, meaning s2.child is available for a decision to be made).

Given this, isn't the first scenario fundamentally the same kind of conflict?

thanks
Shveta






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-21 06:53  Peter Smith <smithpb2250@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: Peter Smith @ 2026-08-21 06:53 UTC (permalink / raw)
  To: shveta malik <shveta.malik@gmail.com>; +Cc: vignesh C <vignesh21@gmail.com>; Nisha Moond <nisha.moond412@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Fri, Aug 21, 2026 at 2:55 PM shveta malik <shveta.malik@gmail.com> wrote:
>
> On Thu, Aug 20, 2026 at 2:09 PM shveta malik <shveta.malik@gmail.com> wrote:
> >
> > I had a quick look, it looks better than v28. I will review and
> > validate it in detail by tomorrow.
> >
>
> The code looks simpler IMO and manageable for supporting all these
> contradictory error scenarios.
>
> I verified the inherited table cases alone. I have a few concerns:
>
> 1)
> postgres=# CREATE PUBLICATION pub1 FOR TABLE s2.child, TABLES IN
> SCHEMA s1 EXCEPT (TABLE s1.parent);
> ERROR:  table "s2.child" cannot be both published and excluded
> DETAIL:  It descends from "s1.parent", which is named in the EXCEPT
> clause of schema "s1".

Hmm. See below.

>
> postgres=# CREATE PUBLICATION pub1 FOR TABLE s1.parent*, TABLES IN
> SCHEMA s2 EXCEPT (TABLE s2.child);
> ERROR:  table "s2.child" cannot be both published and excluded
>
> Can we have a similar DETAIL message in second as well?
>
> 2)
> I find this case still a little ambiguous:
>
> CREATE PUBLICATION pub1 FOR TABLES IN SCHEMA s1, TABLES IN SCHEMA s2
> EXCEPT (TABLE s2.child);
>
> Currently it works, but should it?
>
> a) Should s2.child be published because s1.parent is included, and
> schema s2 is also included, meaning cross-schema inheritance
> boundaries are respected and brought back in?
>
> b) Or should s2.child remain excluded because of the explicit EXCEPT
> (TABLE s2.child) clause?
>

From the documentation [1] it explicitly says:

"FOR TABLE" ... "If ONLY is not specified, the table and all its
descendant tables (if any) are added."
That means "FOR TABLE s1.parent" (without ONLY) should reach out and
drag in the s2.child even though the schema s2 is not published.

OTOH, there is no special documentation about inheritance for "TABLE IN SCHEMA"
That means "FOR TABLES IN SCHEMA s1" will *not* reach out to drag in
the s2.child from the otherwise unpublished s2 schema.

~~

That documented behaviour is the same as what I observed by experimentation

CASE 1.

-- Setup
DROP SCHEMA IF EXISTS s1 CASCADE;
DROP SCHEMA IF EXISTS s2 CASCADE;
CREATE SCHEMA s1;
CREATE SCHEMA s2;

CREATE TABLE s1.parent (id int PRIMARY KEY, val text);
CREATE TABLE s2.child (extra text) INHERITS (s1.parent);

-- Publish just the parent, no ONLY keyword, no schema clause
CREATE PUBLICATION pub FOR TABLE s1.parent;


The following result shows s2.child gets dragged in:

test_pub=# SELECT schemaname, tablename FROM pg_publication_tables
WHERE pubname = 'pub';
 schemaname | tablename
------------+-----------
 s1         | parent
 s2         | child
(2 rows)

~~~

And CASE 2:

test_pub=# CREATE PUBLICATION pub2 FOR TABLES IN SCHEMA s1;
CREATE PUBLICATION

The following result shows s2.child is NOT dragged in:

test_pub=# SELECT schemaname, tablename FROM pg_publication_tables
WHERE pubname = 'pub2';
 schemaname | tablename
------------+-----------
 s1         | parent
(1 row)

~~~

I think this answers your question about:
CREATE PUBLICATION pub1 FOR TABLES IN SCHEMA s1, TABLES IN SCHEMA s2
EXCEPT (TABLE s2.child);

AFAICT -- s2.child should be excluded.

It is not a conflict. Why? Because the s1.parent trying to include
s2.child, because FOR TABLES IN SCHEMA does *not* reach across schemas
to include the descendant tables. So it's only the TABLES IN SCHEMA s2
that was causing s2.child to be published in the first place, and the
EXCEPT negates that.

~~~

In fact, it is this other example that I think may be broken:

> postgres=# CREATE PUBLICATION pub1 FOR TABLE s2.child, TABLES IN
> SCHEMA s1 EXCEPT (TABLE s1.parent);
> ERROR:  table "s2.child" cannot be both published and excluded
> DETAIL:  It descends from "s1.parent", which is named in the EXCEPT
> clause of schema "s1".

Having shown above already that TABLES IN SCHEMA does *not* reach
across into unpublished schemas to include descendants, we cannot turn
around to say the EXCEPT case *will* reach across schemas and exclude
them!  So that means that s2.child is not being excluded at all by the
parent. So AFAICT that means that there is really no conflict here at
all.

======
[1] https://www.postgresql.org/docs/current/sql-createpublication.html

Kind Regards,
Peter Smith.
Fujitsu Australia





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-21 17:30  Nisha Moond <nisha.moond412@gmail.com>
  parent: Peter Smith <smithpb2250@gmail.com>
  0 siblings, 2 replies; 196+ messages in thread

From: Nisha Moond @ 2026-08-21 17:30 UTC (permalink / raw)
  To: Peter Smith <smithpb2250@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; vignesh C <vignesh21@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

Hi,
After considering the discussion upthread, I think it is difficult to
handle all combinations with a simple rule without making the code
more complex. The main problematic cases seem to be when a
partition/inherited child is in a different schema from its root.

For example, s1.root has two partitions: s1.p1 and s2.p2.
With the current patch v28/v29, if we do not allow:
  CREATE PUBLICATION pub1 FOR TABLES IN SCHEMA s1 EXCEPT (s1.root), s2; (ERROR)
then, we would also need to block several DDL operations to ensure the
publication can never reach this state later. Say if s2.p2 does not
exist yet and the creation of pub1 succeeds, then:

1. A partition of s1.root cannot later be created in another schema:
   Block: CREATE TABLE s2.p2 PARTITION OF s1.root ...

2. A partition from a published schema cannot be attached to an excluded root:
   Block: ALTER TABLE s1.root ATTACH PARTITION s2.p2 ...

3. A partition of the excluded root cannot be moved to another schema:
   Block: ALTER TABLE s1.p1 SET SCHEMA s2;

4. Another schema s3 having s3.p3 (root's part) cannot later be added
to the publication:
   Block: ALTER PUBLICATION pub1 ADD TABLES IN SCHEMA s3;

IMO, especially for cases 1 and 3, table DDL should not depend on
publication metadata. So I don't think adding these DDL restrictions
is a good approach.

Another option is to simply allow FOR TABLES IN SCHEMA s1 EXCEPT
(s1.root), s2; and exclude the full s1.root tree along with s2.p2. as
suggested at [1]
However, this conflicts with the other case where FOR TABLES IN SCHEMA
s1 EXCEPT (s1.root), TABLE s2.p2; is rejected, as discussed earlier.

So the question is whether we can simplify the rule further.
On HEAD, I tested combinations where multiple publications in the same
subscription have conflicting rules.
For example:
pub1: FOR ALL TABLES EXCEPT (s1.root);
pub2: FOR TABLE s1.root;

If the subscription includes both publications, s1.root is still
replicated through pub2.

Similarly:
pub1: FOR ALL TABLES EXCEPT (s1.root);
pub2: FOR TABLE s1.p1;

and

pub1: FOR ALL TABLES EXCEPT (s1.root);
pub2: FOR TABLE s2.p2;

In both cases, the subscriber receives s1.p1 / s2.p2 through pub2.

This is because pgoutput makes the publication decision independently
for each publication. So effectively, INCLUSION wins over EXCLUSION. I
think we could apply the same rule to the publication definition
itself.

For example: (Partitions case)

1. FOR TABLES IN SCHEMA s1 EXCEPT (s1.root), s2;
 -- Exclude s1.root and its children in s1, such as s1.p1.
 -- Publish s2.p2 because s2 is explicitly included.

The limitation is that there is still no way to exclude the complete
s1.root tree when publishing both s1 and s2. This could potentially be
addressed later by allowing partition children in the EXCEPT clause.

2. FOR TABLE s1.p1, FOR TABLES IN SCHEMA s1 EXCEPT (s1.root);
 -- Allow s1.p1 to be published. The EXCEPT only excludes s1.root and
other children in the same schema.

3. FOR TABLE s2.p2, FOR TABLES IN SCHEMA s1 EXCEPT (s1.root);
 -- Same as case 1. Exclude s1.root and its children in s1, while
s2.p2 is published.

4. FOR TABLE s1.root, FOR TABLES IN SCHEMA s1 EXCEPT (s1.root);
 -- Allow s1.root to be published and ignore the EXCEPT entry, with a
notice/warning.

For partitions, we may need some changes in pgoutput and the relevant
ancestor lookup code to ensure inclusion always wins over exclusion.

I think the same rule can simplify inheritance trees as well:

5. FOR TABLES IN SCHEMA s1 EXCEPT (TABLE s1.parent), s2;
 -- Exclude s1.parent and its children in s1, but publish s2.child.

6. FOR TABLE s1.parent, TABLES IN SCHEMA s2 EXCEPT (TABLE s2.child);
 -- Publish the full s1.parent tree. The explicit inclusion of
s1.parent tree overrides the exclusion of s2.child, with a
notice/warning.

7. FOR TABLE s2.child, TABLES IN SCHEMA s1 EXCEPT (TABLE s1.parent);
 -- Same as case 5: publish s2.child, while excluding s1.parent and
its children in s1.

8. FOR TABLES IN SCHEMA s1, TABLES IN SCHEMA s2 EXCEPT (TABLE s2.child);
 -- Same as case 6: publish the full s1.parent tree, since s1 is
included, so s2.child is published. The inclusion overrides the
EXCEPT, with a notice/warning.

With this approach, I don't think we need additional DDL restrictions.
New tables/partitions added under an explicitly included schema would
simply be included.

I tried to cover the conflicting combinations including the ones
discussed upthread. Please let me know if there are other cases that
would still be ambiguous with this rule.

Thoughts?

[1] https://www.postgresql.org/message-id/CAHut%2BPvTPcEFtOZ-bVi8Z%3DNLqti1%3DqyYrQDhu-5oDt6RJ4UBhA%40ma...

--
Thanks,
Nisha






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-24 05:40  shveta malik <shveta.malik@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  1 sibling, 2 replies; 196+ messages in thread

From: shveta malik @ 2026-08-24 05:40 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; vignesh C <vignesh21@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; shveta malik <shveta.malik@gmail.com>

On Fri, Aug 21, 2026 at 11:00 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
>
> Hi,
> After considering the discussion upthread, I think it is difficult to
> handle all combinations with a simple rule without making the code
> more complex. The main problematic cases seem to be when a
> partition/inherited child is in a different schema from its root.
>
> For example, s1.root has two partitions: s1.p1 and s2.p2.
> With the current patch v28/v29, if we do not allow:
>   CREATE PUBLICATION pub1 FOR TABLES IN SCHEMA s1 EXCEPT (s1.root), s2; (ERROR)
> then, we would also need to block several DDL operations to ensure the
> publication can never reach this state later. Say if s2.p2 does not
> exist yet and the creation of pub1 succeeds, then:
>
> 1. A partition of s1.root cannot later be created in another schema:
>    Block: CREATE TABLE s2.p2 PARTITION OF s1.root ...
>
> 2. A partition from a published schema cannot be attached to an excluded root:
>    Block: ALTER TABLE s1.root ATTACH PARTITION s2.p2 ...
>
> 3. A partition of the excluded root cannot be moved to another schema:
>    Block: ALTER TABLE s1.p1 SET SCHEMA s2;
>
> 4. Another schema s3 having s3.p3 (root's part) cannot later be added
> to the publication:
>    Block: ALTER PUBLICATION pub1 ADD TABLES IN SCHEMA s3;
>
> IMO, especially for cases 1 and 3, table DDL should not depend on
> publication metadata. So I don't think adding these DDL restrictions
> is a good approach.

I agree with the analysis.

>
> Another option is to simply allow FOR TABLES IN SCHEMA s1 EXCEPT
> (s1.root), s2; and exclude the full s1.root tree along with s2.p2. as
> suggested at [1]
> However, this conflicts with the other case where FOR TABLES IN SCHEMA
> s1 EXCEPT (s1.root), TABLE s2.p2; is rejected, as discussed earlier.
>
> So the question is whether we can simplify the rule further.
> On HEAD, I tested combinations where multiple publications in the same
> subscription have conflicting rules.
> For example:
> pub1: FOR ALL TABLES EXCEPT (s1.root);
> pub2: FOR TABLE s1.root;
>
> If the subscription includes both publications, s1.root is still
> replicated through pub2.
>
> Similarly:
> pub1: FOR ALL TABLES EXCEPT (s1.root);
> pub2: FOR TABLE s1.p1;
>
> and
>
> pub1: FOR ALL TABLES EXCEPT (s1.root);
> pub2: FOR TABLE s2.p2;
>
> In both cases, the subscriber receives s1.p1 / s2.p2 through pub2.

Okay. I see these cases but I don't think we can comapre these cases
with single publication case.

> This is because pgoutput makes the publication decision independently
> for each publication. So effectively, INCLUSION wins over EXCLUSION. I
> think we could apply the same rule to the publication definition
> itself.
>
> For example: (Partitions case)
>
> 1. FOR TABLES IN SCHEMA s1 EXCEPT (s1.root), s2;
>  -- Exclude s1.root and its children in s1, such as s1.p1.
>  -- Publish s2.p2 because s2 is explicitly included.
>
> The limitation is that there is still no way to exclude the complete
> s1.root tree when publishing both s1 and s2. This could potentially be
> addressed later by allowing partition children in the EXCEPT clause.
>
> 2. FOR TABLE s1.p1, FOR TABLES IN SCHEMA s1 EXCEPT (s1.root);
>  -- Allow s1.p1 to be published. The EXCEPT only excludes s1.root and
> other children in the same schema.
>
> 3. FOR TABLE s2.p2, FOR TABLES IN SCHEMA s1 EXCEPT (s1.root);
>  -- Same as case 1. Exclude s1.root and its children in s1, while
> s2.p2 is published.
>
> 4. FOR TABLE s1.root, FOR TABLES IN SCHEMA s1 EXCEPT (s1.root);
>  -- Allow s1.root to be published and ignore the EXCEPT entry, with a
> notice/warning.
>
> For partitions, we may need some changes in pgoutput and the relevant
> ancestor lookup code to ensure inclusion always wins over exclusion.
>
> I think the same rule can simplify inheritance trees as well:
>
> 5. FOR TABLES IN SCHEMA s1 EXCEPT (TABLE s1.parent), s2;
>  -- Exclude s1.parent and its children in s1, but publish s2.child.
>
> 6. FOR TABLE s1.parent, TABLES IN SCHEMA s2 EXCEPT (TABLE s2.child);
>  -- Publish the full s1.parent tree. The explicit inclusion of
> s1.parent tree overrides the exclusion of s2.child, with a
> notice/warning.
>
> 7. FOR TABLE s2.child, TABLES IN SCHEMA s1 EXCEPT (TABLE s1.parent);
>  -- Same as case 5: publish s2.child, while excluding s1.parent and
> its children in s1.
>
> 8. FOR TABLES IN SCHEMA s1, TABLES IN SCHEMA s2 EXCEPT (TABLE s2.child);
>  -- Same as case 6: publish the full s1.parent tree, since s1 is
> included, so s2.child is published. The inclusion overrides the
> EXCEPT, with a notice/warning.
>
> With this approach, I don't think we need additional DDL restrictions.
> New tables/partitions added under an explicitly included schema would
> simply be included.
>
> I tried to cover the conflicting combinations including the ones
> discussed upthread. Please let me know if there are other cases that
> would still be ambiguous with this rule.
>
> Thoughts?
>

While the proposal to let inclusion win over conflicting rules avoids
adding complex alter-table restrictions, I think it has a significant
drawback: relying on a NOTICE/warning to override an explicit EXCEPT
clause feels risky.

An EXCEPT clause is an explicit data-filtering boundary. If a DBA/user
explicitly excludes a table or its child, for example, because it
contains sensitive data, I don't think we should silently override
that exclusion just because another inclusion rule happens to cover
the same relation indirectly.  A NOTICE or warning could easily be
missed, and we could end up publishing data that the user explicitly
intended to exclude. So, to me, the concern is not just that the
behavior could be surprising; we would actually be publishing
something that the user explicitly asked us not to publish.

An Alternative Solution could be 'Strict Schema-Bound Isolation'
(Peter also suggested something similar earlier if I am not wrong,
which did not reach to conclusion). To avoid both DDL-blocking and
unsafe Exclusion overrides, we could adopt a Strict Schema-Bound
Isolation model.

Core rule: Schema boundaries act as hard firewalls. An EXCEPT clause
defined for a specific schema applies only to objects physically
residing in that schema. Inclusion or exclusion through one schema
does not recursively "bleed over" into another schema or affect
partitions or inherited children that reside there.

How this resolves the cases from your email:

a). Clean Cross-Schema Separation (Cases 1, 3, 5, 7)
----------------------------------
Partitions:
 1. FOR TABLES IN SCHEMA s1 EXCEPT (s1.root), s2;
 --s1.root excluded, everything under s2 even if it is parition of
s1.root is published

 3. FOR TABLE s2.p2, FOR TABLES IN SCHEMA s1 EXCEPT (s1.root);
 --s1.root excluded, s2.p2 published

Inheritance:
 5. FOR TABLES IN SCHEMA s1 EXCEPT (TABLE s1.parent), s2;
 --s1.parent excluded, everything under s2 even if it is child of
s1.parent is published.

 7. FOR TABLE s2.child, TABLES IN SCHEMA s1 EXCEPT (TABLE s1.parent);
  --s1.parent excluded, s2.child is published as it is explcilty mentioned.


b. Local Exceptions are Respected (Cases 6 & 8)
----------------------------------
6.  FOR TABLE s1.parent, TABLES IN SCHEMA s2 EXCEPT (TABLE s2.child);
    --s1.parent published with all its children present in s1,
s2.child is excluded.

8.  FOR TABLES IN SCHEMA s1, TABLES IN SCHEMA s2 EXCEPT (TABLE
s2.child);
    --s1.parent published with all its children present in s1,
s2.child is excluded.


c. Local Table Precedence within the Same Schema (Cases 2 & 4)
----------------------------------
2. FOR TABLE s1.p1, FOR TABLES IN SCHEMA s1 EXCEPT (s1.root);
 -- parition s1.p1 is published. s1.root and other paritions in the
same schema are excluded. The same rule applies to inherited tables
too.

4. FOR TABLE s1.root, FOR TABLES IN SCHEMA s1 EXCEPT (s1.root);
--This is clearly an ERROR scenario as user is giving exact same
inclusion and exclusion for the same schema.


NOTE:
The case where parition is included while ROOT is excluded and
publish_via_partition_root is TRUE (e.g., case a.1), we may not even
publish parition itself. Check this once please. But this case will
not be any different from existing case on HEAD where partition alone
is included in publication with publish_via_partition_root=true.
Example:

create publication pub1 for table s2.part with
(publish_via_partition_root = true);

~~


Benefits I see:
1) We avoid any other issues requiring DDL blocking. Let me know if
you see any.
b) We follow what the user explicitly asked to EXCLUDE without any
notice/warning to override their choice.
c) We can clearly document it: 'Inclusion/exclusion rules do not bleed
over to other schema.

Nisha, can you please review this in detail? I might have overlooked something.

thanks
Shveta





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-24 06:13  Peter Smith <smithpb2250@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  1 sibling, 0 replies; 196+ messages in thread

From: Peter Smith @ 2026-08-24 06:13 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; vignesh C <vignesh21@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Sat, Aug 22, 2026 at 3:30 AM Nisha Moond <nisha.moond412@gmail.com> wrote:
>
> Hi,
> After considering the discussion upthread, I think it is difficult to
> handle all combinations with a simple rule without making the code
> more complex. The main problematic cases seem to be when a
> partition/inherited child is in a different schema from its root.
>
> For example, s1.root has two partitions: s1.p1 and s2.p2.
> With the current patch v28/v29, if we do not allow:
>   CREATE PUBLICATION pub1 FOR TABLES IN SCHEMA s1 EXCEPT (s1.root), s2; (ERROR)
> then, we would also need to block several DDL operations to ensure the
> publication can never reach this state later. Say if s2.p2 does not
> exist yet and the creation of pub1 succeeds, then:
>
> 1. A partition of s1.root cannot later be created in another schema:
>    Block: CREATE TABLE s2.p2 PARTITION OF s1.root ...
>
> 2. A partition from a published schema cannot be attached to an excluded root:
>    Block: ALTER TABLE s1.root ATTACH PARTITION s2.p2 ...
>
> 3. A partition of the excluded root cannot be moved to another schema:
>    Block: ALTER TABLE s1.p1 SET SCHEMA s2;
>
> 4. Another schema s3 having s3.p3 (root's part) cannot later be added
> to the publication:
>    Block: ALTER PUBLICATION pub1 ADD TABLES IN SCHEMA s3;
>
> IMO, especially for cases 1 and 3, table DDL should not depend on
> publication metadata. So I don't think adding these DDL restrictions
> is a good approach.
>
> Another option is to simply allow FOR TABLES IN SCHEMA s1 EXCEPT
> (s1.root), s2; and exclude the full s1.root tree along with s2.p2. as
> suggested at [1]
> However, this conflicts with the other case where FOR TABLES IN SCHEMA
> s1 EXCEPT (s1.root), TABLE s2.p2; is rejected, as discussed earlier.
>
> So the question is whether we can simplify the rule further.
> On HEAD, I tested combinations where multiple publications in the same
> subscription have conflicting rules.
> For example:
> pub1: FOR ALL TABLES EXCEPT (s1.root);
> pub2: FOR TABLE s1.root;
>
> If the subscription includes both publications, s1.root is still
> replicated through pub2.
>
> Similarly:
> pub1: FOR ALL TABLES EXCEPT (s1.root);
> pub2: FOR TABLE s1.p1;
>
> and
>
> pub1: FOR ALL TABLES EXCEPT (s1.root);
> pub2: FOR TABLE s2.p2;
>
> In both cases, the subscriber receives s1.p1 / s2.p2 through pub2.
>
> This is because pgoutput makes the publication decision independently
> for each publication. So effectively, INCLUSION wins over EXCLUSION. I
> think we could apply the same rule to the publication definition
> itself.
>
> For example: (Partitions case)
>
> 1. FOR TABLES IN SCHEMA s1 EXCEPT (s1.root), s2;
>  -- Exclude s1.root and its children in s1, such as s1.p1.
>  -- Publish s2.p2 because s2 is explicitly included.
>
> The limitation is that there is still no way to exclude the complete
> s1.root tree when publishing both s1 and s2. This could potentially be
> addressed later by allowing partition children in the EXCEPT clause.
>
> 2. FOR TABLE s1.p1, FOR TABLES IN SCHEMA s1 EXCEPT (s1.root);
>  -- Allow s1.p1 to be published. The EXCEPT only excludes s1.root and
> other children in the same schema.
>
> 3. FOR TABLE s2.p2, FOR TABLES IN SCHEMA s1 EXCEPT (s1.root);
>  -- Same as case 1. Exclude s1.root and its children in s1, while
> s2.p2 is published.
>
> 4. FOR TABLE s1.root, FOR TABLES IN SCHEMA s1 EXCEPT (s1.root);
>  -- Allow s1.root to be published and ignore the EXCEPT entry, with a
> notice/warning.
>
> For partitions, we may need some changes in pgoutput and the relevant
> ancestor lookup code to ensure inclusion always wins over exclusion.
>
> I think the same rule can simplify inheritance trees as well:
>
> 5. FOR TABLES IN SCHEMA s1 EXCEPT (TABLE s1.parent), s2;
>  -- Exclude s1.parent and its children in s1, but publish s2.child.
>
> 6. FOR TABLE s1.parent, TABLES IN SCHEMA s2 EXCEPT (TABLE s2.child);
>  -- Publish the full s1.parent tree. The explicit inclusion of
> s1.parent tree overrides the exclusion of s2.child, with a
> notice/warning.
>
> 7. FOR TABLE s2.child, TABLES IN SCHEMA s1 EXCEPT (TABLE s1.parent);
>  -- Same as case 5: publish s2.child, while excluding s1.parent and
> its children in s1.

Any combination of clauses used to describe behaviour also needs to
show what happens for table inheritance using the "ONLY" keyword. I
think you've omitted that combination.

>
> 8. FOR TABLES IN SCHEMA s1, TABLES IN SCHEMA s2 EXCEPT (TABLE s2.child);
>  -- Same as case 6: publish the full s1.parent tree, since s1 is
> included, so s2.child is published. The inclusion overrides the
> EXCEPT, with a notice/warning.

No. You wrote “publish the full s1.parent tree, since s1 is included,
so s2.child is published “, but that is incorrect AFAIK.

Cross-schema inclusion behaves differently for inheritance and for
partitioning. For “TABLES IN SCHEMA s1” the s1.parent will *not* reach
out to include descendants from other schemas. (I demonstrated this
already with my SQL CASE 2 example [1])

======
[1] https://www.postgresql.org/message-id/CAHut%2BPvpFR0%3D-AT_0QfjtWFov5ZT4yrfJgbAd-N7w%3DCzSm708g%40ma...

Kind Regards,
Peter Smith.
Fujitsu Australia





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-24 06:27  shveta malik <shveta.malik@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  1 sibling, 0 replies; 196+ messages in thread

From: shveta malik @ 2026-08-24 06:27 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; vignesh C <vignesh21@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; shveta malik <shveta.malik@gmail.com>

On Mon, Aug 24, 2026 at 11:10 AM shveta malik <shveta.malik@gmail.com> wrote:
>
> On Fri, Aug 21, 2026 at 11:00 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
> >
> > Hi,
> > After considering the discussion upthread, I think it is difficult to
> > handle all combinations with a simple rule without making the code
> > more complex. The main problematic cases seem to be when a
> > partition/inherited child is in a different schema from its root.
> >
> > For example, s1.root has two partitions: s1.p1 and s2.p2.
> > With the current patch v28/v29, if we do not allow:
> >   CREATE PUBLICATION pub1 FOR TABLES IN SCHEMA s1 EXCEPT (s1.root), s2; (ERROR)
> > then, we would also need to block several DDL operations to ensure the
> > publication can never reach this state later. Say if s2.p2 does not
> > exist yet and the creation of pub1 succeeds, then:
> >
> > 1. A partition of s1.root cannot later be created in another schema:
> >    Block: CREATE TABLE s2.p2 PARTITION OF s1.root ...
> >
> > 2. A partition from a published schema cannot be attached to an excluded root:
> >    Block: ALTER TABLE s1.root ATTACH PARTITION s2.p2 ...
> >
> > 3. A partition of the excluded root cannot be moved to another schema:
> >    Block: ALTER TABLE s1.p1 SET SCHEMA s2;
> >
> > 4. Another schema s3 having s3.p3 (root's part) cannot later be added
> > to the publication:
> >    Block: ALTER PUBLICATION pub1 ADD TABLES IN SCHEMA s3;
> >
> > IMO, especially for cases 1 and 3, table DDL should not depend on
> > publication metadata. So I don't think adding these DDL restrictions
> > is a good approach.
>
> I agree with the analysis.
>
> >
> > Another option is to simply allow FOR TABLES IN SCHEMA s1 EXCEPT
> > (s1.root), s2; and exclude the full s1.root tree along with s2.p2. as
> > suggested at [1]
> > However, this conflicts with the other case where FOR TABLES IN SCHEMA
> > s1 EXCEPT (s1.root), TABLE s2.p2; is rejected, as discussed earlier.
> >
> > So the question is whether we can simplify the rule further.
> > On HEAD, I tested combinations where multiple publications in the same
> > subscription have conflicting rules.
> > For example:
> > pub1: FOR ALL TABLES EXCEPT (s1.root);
> > pub2: FOR TABLE s1.root;
> >
> > If the subscription includes both publications, s1.root is still
> > replicated through pub2.
> >
> > Similarly:
> > pub1: FOR ALL TABLES EXCEPT (s1.root);
> > pub2: FOR TABLE s1.p1;
> >
> > and
> >
> > pub1: FOR ALL TABLES EXCEPT (s1.root);
> > pub2: FOR TABLE s2.p2;
> >
> > In both cases, the subscriber receives s1.p1 / s2.p2 through pub2.
>
> Okay. I see these cases but I don't think we can comapre these cases
> with single publication case.
>
> > This is because pgoutput makes the publication decision independently
> > for each publication. So effectively, INCLUSION wins over EXCLUSION. I
> > think we could apply the same rule to the publication definition
> > itself.
> >
> > For example: (Partitions case)
> >
> > 1. FOR TABLES IN SCHEMA s1 EXCEPT (s1.root), s2;
> >  -- Exclude s1.root and its children in s1, such as s1.p1.
> >  -- Publish s2.p2 because s2 is explicitly included.
> >
> > The limitation is that there is still no way to exclude the complete
> > s1.root tree when publishing both s1 and s2. This could potentially be
> > addressed later by allowing partition children in the EXCEPT clause.
> >
> > 2. FOR TABLE s1.p1, FOR TABLES IN SCHEMA s1 EXCEPT (s1.root);
> >  -- Allow s1.p1 to be published. The EXCEPT only excludes s1.root and
> > other children in the same schema.
> >
> > 3. FOR TABLE s2.p2, FOR TABLES IN SCHEMA s1 EXCEPT (s1.root);
> >  -- Same as case 1. Exclude s1.root and its children in s1, while
> > s2.p2 is published.
> >
> > 4. FOR TABLE s1.root, FOR TABLES IN SCHEMA s1 EXCEPT (s1.root);
> >  -- Allow s1.root to be published and ignore the EXCEPT entry, with a
> > notice/warning.
> >
> > For partitions, we may need some changes in pgoutput and the relevant
> > ancestor lookup code to ensure inclusion always wins over exclusion.
> >
> > I think the same rule can simplify inheritance trees as well:
> >
> > 5. FOR TABLES IN SCHEMA s1 EXCEPT (TABLE s1.parent), s2;
> >  -- Exclude s1.parent and its children in s1, but publish s2.child.
> >
> > 6. FOR TABLE s1.parent, TABLES IN SCHEMA s2 EXCEPT (TABLE s2.child);
> >  -- Publish the full s1.parent tree. The explicit inclusion of
> > s1.parent tree overrides the exclusion of s2.child, with a
> > notice/warning.
> >
> > 7. FOR TABLE s2.child, TABLES IN SCHEMA s1 EXCEPT (TABLE s1.parent);
> >  -- Same as case 5: publish s2.child, while excluding s1.parent and
> > its children in s1.
> >
> > 8. FOR TABLES IN SCHEMA s1, TABLES IN SCHEMA s2 EXCEPT (TABLE s2.child);
> >  -- Same as case 6: publish the full s1.parent tree, since s1 is
> > included, so s2.child is published. The inclusion overrides the
> > EXCEPT, with a notice/warning.
> >
> > With this approach, I don't think we need additional DDL restrictions.
> > New tables/partitions added under an explicitly included schema would
> > simply be included.
> >
> > I tried to cover the conflicting combinations including the ones
> > discussed upthread. Please let me know if there are other cases that
> > would still be ambiguous with this rule.
> >
> > Thoughts?
> >
>
> While the proposal to let inclusion win over conflicting rules avoids
> adding complex alter-table restrictions, I think it has a significant
> drawback: relying on a NOTICE/warning to override an explicit EXCEPT
> clause feels risky.
>
> An EXCEPT clause is an explicit data-filtering boundary. If a DBA/user
> explicitly excludes a table or its child, for example, because it
> contains sensitive data, I don't think we should silently override
> that exclusion just because another inclusion rule happens to cover
> the same relation indirectly.  A NOTICE or warning could easily be
> missed, and we could end up publishing data that the user explicitly
> intended to exclude. So, to me, the concern is not just that the
> behavior could be surprising; we would actually be publishing
> something that the user explicitly asked us not to publish.
>
> An Alternative Solution could be 'Strict Schema-Bound Isolation'
> (Peter also suggested something similar earlier if I am not wrong,
> which did not reach to conclusion). To avoid both DDL-blocking and
> unsafe Exclusion overrides, we could adopt a Strict Schema-Bound
> Isolation model.
>
> Core rule: Schema boundaries act as hard firewalls. An EXCEPT clause
> defined for a specific schema applies only to objects physically
> residing in that schema. Inclusion or exclusion through one schema
> does not recursively "bleed over" into another schema or affect
> partitions or inherited children that reside there.
>
> How this resolves the cases from your email:
>
> a). Clean Cross-Schema Separation (Cases 1, 3, 5, 7)
> ----------------------------------
> Partitions:
>  1. FOR TABLES IN SCHEMA s1 EXCEPT (s1.root), s2;
>  --s1.root excluded, everything under s2 even if it is parition of
> s1.root is published
>
>  3. FOR TABLE s2.p2, FOR TABLES IN SCHEMA s1 EXCEPT (s1.root);
>  --s1.root excluded, s2.p2 published
>
> Inheritance:
>  5. FOR TABLES IN SCHEMA s1 EXCEPT (TABLE s1.parent), s2;
>  --s1.parent excluded, everything under s2 even if it is child of
> s1.parent is published.
>
>  7. FOR TABLE s2.child, TABLES IN SCHEMA s1 EXCEPT (TABLE s1.parent);
>   --s1.parent excluded, s2.child is published as it is explcilty mentioned.
>
>
> b. Local Exceptions are Respected (Cases 6 & 8)
> ----------------------------------
> 6.  FOR TABLE s1.parent, TABLES IN SCHEMA s2 EXCEPT (TABLE s2.child);
>     --s1.parent published with all its children present in s1,
> s2.child is excluded.

Based on experiments done by Peter in [1], I would like to revise this
behavious. In this case:

--s1.parent and all its children belonging to any schema should be
published because inclusion of s1.parent is not schema-bound. But
s2.child should be excluded as explicitly given by the user.

>
> 8.  FOR TABLES IN SCHEMA s1, TABLES IN SCHEMA s2 EXCEPT (TABLE
> s2.child);
>     --s1.parent published with all its children present in s1,
> s2.child is excluded.

Here s1.s1.parent is schema-bound as it is included by schema s1, and
thus the behaviour I stated above remains the same.

[1] https://www.postgresql.org/message-id/CAHut%2BPvpFR0%3D-AT_0QfjtWFov5ZT4yrfJgbAd-N7w%3DCzSm708g%40ma...

>
> c. Local Table Precedence within the Same Schema (Cases 2 & 4)
> ----------------------------------
> 2. FOR TABLE s1.p1, FOR TABLES IN SCHEMA s1 EXCEPT (s1.root);
>  -- parition s1.p1 is published. s1.root and other paritions in the
> same schema are excluded. The same rule applies to inherited tables
> too.
>
> 4. FOR TABLE s1.root, FOR TABLES IN SCHEMA s1 EXCEPT (s1.root);
> --This is clearly an ERROR scenario as user is giving exact same
> inclusion and exclusion for the same schema.
>
>
> NOTE:
> The case where parition is included while ROOT is excluded and
> publish_via_partition_root is TRUE (e.g., case a.1), we may not even
> publish parition itself. Check this once please. But this case will
> not be any different from existing case on HEAD where partition alone
> is included in publication with publish_via_partition_root=true.
> Example:
>
> create publication pub1 for table s2.part with
> (publish_via_partition_root = true);
>
> ~~
>
>
> Benefits I see:
> 1) We avoid any other issues requiring DDL blocking. Let me know if
> you see any.
> b) We follow what the user explicitly asked to EXCLUDE without any
> notice/warning to override their choice.
> c) We can clearly document it: 'Inclusion/exclusion rules do not bleed
> over to other schema.
>
> Nisha, can you please review this in detail? I might have overlooked something.
>
> thanks
> Shveta





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-24 07:24  Peter Smith <smithpb2250@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  1 sibling, 1 reply; 196+ messages in thread

From: Peter Smith @ 2026-08-24 07:24 UTC (permalink / raw)
  To: shveta malik <shveta.malik@gmail.com>; +Cc: Nisha Moond <nisha.moond412@gmail.com>; vignesh C <vignesh21@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Mon, Aug 24, 2026 at 3:40 PM shveta malik <shveta.malik@gmail.com> wrote:
>
> On Fri, Aug 21, 2026 at 11:00 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
> >
> > Hi,
> > After considering the discussion upthread, I think it is difficult to
> > handle all combinations with a simple rule without making the code
> > more complex. The main problematic cases seem to be when a
> > partition/inherited child is in a different schema from its root.
> >
> > For example, s1.root has two partitions: s1.p1 and s2.p2.
> > With the current patch v28/v29, if we do not allow:
> >   CREATE PUBLICATION pub1 FOR TABLES IN SCHEMA s1 EXCEPT (s1.root), s2; (ERROR)
> > then, we would also need to block several DDL operations to ensure the
> > publication can never reach this state later. Say if s2.p2 does not
> > exist yet and the creation of pub1 succeeds, then:
> >
> > 1. A partition of s1.root cannot later be created in another schema:
> >    Block: CREATE TABLE s2.p2 PARTITION OF s1.root ...
> >
> > 2. A partition from a published schema cannot be attached to an excluded root:
> >    Block: ALTER TABLE s1.root ATTACH PARTITION s2.p2 ...
> >
> > 3. A partition of the excluded root cannot be moved to another schema:
> >    Block: ALTER TABLE s1.p1 SET SCHEMA s2;
> >
> > 4. Another schema s3 having s3.p3 (root's part) cannot later be added
> > to the publication:
> >    Block: ALTER PUBLICATION pub1 ADD TABLES IN SCHEMA s3;
> >
> > IMO, especially for cases 1 and 3, table DDL should not depend on
> > publication metadata. So I don't think adding these DDL restrictions
> > is a good approach.
>
> I agree with the analysis.
>
> >
> > Another option is to simply allow FOR TABLES IN SCHEMA s1 EXCEPT
> > (s1.root), s2; and exclude the full s1.root tree along with s2.p2. as
> > suggested at [1]
> > However, this conflicts with the other case where FOR TABLES IN SCHEMA
> > s1 EXCEPT (s1.root), TABLE s2.p2; is rejected, as discussed earlier.
> >
> > So the question is whether we can simplify the rule further.
> > On HEAD, I tested combinations where multiple publications in the same
> > subscription have conflicting rules.
> > For example:
> > pub1: FOR ALL TABLES EXCEPT (s1.root);
> > pub2: FOR TABLE s1.root;
> >
> > If the subscription includes both publications, s1.root is still
> > replicated through pub2.
> >
> > Similarly:
> > pub1: FOR ALL TABLES EXCEPT (s1.root);
> > pub2: FOR TABLE s1.p1;
> >
> > and
> >
> > pub1: FOR ALL TABLES EXCEPT (s1.root);
> > pub2: FOR TABLE s2.p2;
> >
> > In both cases, the subscriber receives s1.p1 / s2.p2 through pub2.
>
> Okay. I see these cases but I don't think we can comapre these cases
> with single publication case.
>
> > This is because pgoutput makes the publication decision independently
> > for each publication. So effectively, INCLUSION wins over EXCLUSION. I
> > think we could apply the same rule to the publication definition
> > itself.
> >
> > For example: (Partitions case)
> >
> > 1. FOR TABLES IN SCHEMA s1 EXCEPT (s1.root), s2;
> >  -- Exclude s1.root and its children in s1, such as s1.p1.
> >  -- Publish s2.p2 because s2 is explicitly included.
> >
> > The limitation is that there is still no way to exclude the complete
> > s1.root tree when publishing both s1 and s2. This could potentially be
> > addressed later by allowing partition children in the EXCEPT clause.
> >
> > 2. FOR TABLE s1.p1, FOR TABLES IN SCHEMA s1 EXCEPT (s1.root);
> >  -- Allow s1.p1 to be published. The EXCEPT only excludes s1.root and
> > other children in the same schema.
> >
> > 3. FOR TABLE s2.p2, FOR TABLES IN SCHEMA s1 EXCEPT (s1.root);
> >  -- Same as case 1. Exclude s1.root and its children in s1, while
> > s2.p2 is published.
> >
> > 4. FOR TABLE s1.root, FOR TABLES IN SCHEMA s1 EXCEPT (s1.root);
> >  -- Allow s1.root to be published and ignore the EXCEPT entry, with a
> > notice/warning.
> >
> > For partitions, we may need some changes in pgoutput and the relevant
> > ancestor lookup code to ensure inclusion always wins over exclusion.
> >
> > I think the same rule can simplify inheritance trees as well:
> >
> > 5. FOR TABLES IN SCHEMA s1 EXCEPT (TABLE s1.parent), s2;
> >  -- Exclude s1.parent and its children in s1, but publish s2.child.
> >
> > 6. FOR TABLE s1.parent, TABLES IN SCHEMA s2 EXCEPT (TABLE s2.child);
> >  -- Publish the full s1.parent tree. The explicit inclusion of
> > s1.parent tree overrides the exclusion of s2.child, with a
> > notice/warning.
> >
> > 7. FOR TABLE s2.child, TABLES IN SCHEMA s1 EXCEPT (TABLE s1.parent);
> >  -- Same as case 5: publish s2.child, while excluding s1.parent and
> > its children in s1.
> >
> > 8. FOR TABLES IN SCHEMA s1, TABLES IN SCHEMA s2 EXCEPT (TABLE s2.child);
> >  -- Same as case 6: publish the full s1.parent tree, since s1 is
> > included, so s2.child is published. The inclusion overrides the
> > EXCEPT, with a notice/warning.
> >
> > With this approach, I don't think we need additional DDL restrictions.
> > New tables/partitions added under an explicitly included schema would
> > simply be included.
> >
> > I tried to cover the conflicting combinations including the ones
> > discussed upthread. Please let me know if there are other cases that
> > would still be ambiguous with this rule.
> >
> > Thoughts?
> >
>
> While the proposal to let inclusion win over conflicting rules avoids
> adding complex alter-table restrictions, I think it has a significant
> drawback: relying on a NOTICE/warning to override an explicit EXCEPT
> clause feels risky.
>
> An EXCEPT clause is an explicit data-filtering boundary. If a DBA/user
> explicitly excludes a table or its child, for example, because it
> contains sensitive data, I don't think we should silently override
> that exclusion just because another inclusion rule happens to cover
> the same relation indirectly.  A NOTICE or warning could easily be
> missed, and we could end up publishing data that the user explicitly
> intended to exclude. So, to me, the concern is not just that the
> behavior could be surprising; we would actually be publishing
> something that the user explicitly asked us not to publish.

+1 If the user says EXCEPT then the only safe thing to do is what the
user asked for. To do otherwise is effectively saying: “We see you
wanted to exclude this table but we are going to publish it anyway
because we figure you just made a mistake”.

>
> An Alternative Solution could be 'Strict Schema-Bound Isolation'
> (Peter also suggested something similar earlier if I am not wrong,
> which did not reach to conclusion). To avoid both DDL-blocking and
> unsafe Exclusion overrides, we could adopt a Strict Schema-Bound
> Isolation model.
>
> Core rule: Schema boundaries act as hard firewalls. An EXCEPT clause
> defined for a specific schema applies only to objects physically
> residing in that schema. Inclusion or exclusion through one schema
> does not recursively "bleed over" into another schema or affect
> partitions or inherited children that reside there.

Something seems off here. The inclusion rules are already
well-established. Partitioning really *does* bleed already into other
unpublished schemas currently on HEAD.

e.g.
CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1;

Inheritance:
s1.parent INCLUDED
s1.child INCLUDED
s2.child NOT INCLUDED

Partitioning:
s1.root INCLUDED
s1.part INCLUDED
s2.part INCLUDED (it cascades to other schemas)

~~~

So you can't make this a "Core Rule" without changing the existing
HEAD behaviour for partition inclusion. I doubt that will be
acceptable.Perhaps you meant the "Strict Schema-Bound Isolation" rule
is only for exclusions. Maybe that is ok. OTOH making the
inclusion/exclusion cross-schema rules different might not be good
either.

======
Kind Regards,
Peter Smith.
Fujitsu Australia





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-24 09:55  shveta malik <shveta.malik@gmail.com>
  parent: Peter Smith <smithpb2250@gmail.com>
  0 siblings, 3 replies; 196+ messages in thread

From: shveta malik @ 2026-08-24 09:55 UTC (permalink / raw)
  To: Peter Smith <smithpb2250@gmail.com>; +Cc: Nisha Moond <nisha.moond412@gmail.com>; vignesh C <vignesh21@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; shveta malik <shveta.malik@gmail.com>

On Mon, Aug 24, 2026 at 12:55 PM Peter Smith <smithpb2250@gmail.com> wrote:
>
> On Mon, Aug 24, 2026 at 3:40 PM shveta malik <shveta.malik@gmail.com> wrote:
> >
> > On Fri, Aug 21, 2026 at 11:00 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
> > >
> > > Hi,
> > > After considering the discussion upthread, I think it is difficult to
> > > handle all combinations with a simple rule without making the code
> > > more complex. The main problematic cases seem to be when a
> > > partition/inherited child is in a different schema from its root.
> > >
> > > For example, s1.root has two partitions: s1.p1 and s2.p2.
> > > With the current patch v28/v29, if we do not allow:
> > >   CREATE PUBLICATION pub1 FOR TABLES IN SCHEMA s1 EXCEPT (s1.root), s2; (ERROR)
> > > then, we would also need to block several DDL operations to ensure the
> > > publication can never reach this state later. Say if s2.p2 does not
> > > exist yet and the creation of pub1 succeeds, then:
> > >
> > > 1. A partition of s1.root cannot later be created in another schema:
> > >    Block: CREATE TABLE s2.p2 PARTITION OF s1.root ...
> > >
> > > 2. A partition from a published schema cannot be attached to an excluded root:
> > >    Block: ALTER TABLE s1.root ATTACH PARTITION s2.p2 ...
> > >
> > > 3. A partition of the excluded root cannot be moved to another schema:
> > >    Block: ALTER TABLE s1.p1 SET SCHEMA s2;
> > >
> > > 4. Another schema s3 having s3.p3 (root's part) cannot later be added
> > > to the publication:
> > >    Block: ALTER PUBLICATION pub1 ADD TABLES IN SCHEMA s3;
> > >
> > > IMO, especially for cases 1 and 3, table DDL should not depend on
> > > publication metadata. So I don't think adding these DDL restrictions
> > > is a good approach.
> >
> > I agree with the analysis.
> >
> > >
> > > Another option is to simply allow FOR TABLES IN SCHEMA s1 EXCEPT
> > > (s1.root), s2; and exclude the full s1.root tree along with s2.p2. as
> > > suggested at [1]
> > > However, this conflicts with the other case where FOR TABLES IN SCHEMA
> > > s1 EXCEPT (s1.root), TABLE s2.p2; is rejected, as discussed earlier.
> > >
> > > So the question is whether we can simplify the rule further.
> > > On HEAD, I tested combinations where multiple publications in the same
> > > subscription have conflicting rules.
> > > For example:
> > > pub1: FOR ALL TABLES EXCEPT (s1.root);
> > > pub2: FOR TABLE s1.root;
> > >
> > > If the subscription includes both publications, s1.root is still
> > > replicated through pub2.
> > >
> > > Similarly:
> > > pub1: FOR ALL TABLES EXCEPT (s1.root);
> > > pub2: FOR TABLE s1.p1;
> > >
> > > and
> > >
> > > pub1: FOR ALL TABLES EXCEPT (s1.root);
> > > pub2: FOR TABLE s2.p2;
> > >
> > > In both cases, the subscriber receives s1.p1 / s2.p2 through pub2.
> >
> > Okay. I see these cases but I don't think we can comapre these cases
> > with single publication case.
> >
> > > This is because pgoutput makes the publication decision independently
> > > for each publication. So effectively, INCLUSION wins over EXCLUSION. I
> > > think we could apply the same rule to the publication definition
> > > itself.
> > >
> > > For example: (Partitions case)
> > >
> > > 1. FOR TABLES IN SCHEMA s1 EXCEPT (s1.root), s2;
> > >  -- Exclude s1.root and its children in s1, such as s1.p1.
> > >  -- Publish s2.p2 because s2 is explicitly included.
> > >
> > > The limitation is that there is still no way to exclude the complete
> > > s1.root tree when publishing both s1 and s2. This could potentially be
> > > addressed later by allowing partition children in the EXCEPT clause.
> > >
> > > 2. FOR TABLE s1.p1, FOR TABLES IN SCHEMA s1 EXCEPT (s1.root);
> > >  -- Allow s1.p1 to be published. The EXCEPT only excludes s1.root and
> > > other children in the same schema.
> > >
> > > 3. FOR TABLE s2.p2, FOR TABLES IN SCHEMA s1 EXCEPT (s1.root);
> > >  -- Same as case 1. Exclude s1.root and its children in s1, while
> > > s2.p2 is published.
> > >
> > > 4. FOR TABLE s1.root, FOR TABLES IN SCHEMA s1 EXCEPT (s1.root);
> > >  -- Allow s1.root to be published and ignore the EXCEPT entry, with a
> > > notice/warning.
> > >
> > > For partitions, we may need some changes in pgoutput and the relevant
> > > ancestor lookup code to ensure inclusion always wins over exclusion.
> > >
> > > I think the same rule can simplify inheritance trees as well:
> > >
> > > 5. FOR TABLES IN SCHEMA s1 EXCEPT (TABLE s1.parent), s2;
> > >  -- Exclude s1.parent and its children in s1, but publish s2.child.
> > >
> > > 6. FOR TABLE s1.parent, TABLES IN SCHEMA s2 EXCEPT (TABLE s2.child);
> > >  -- Publish the full s1.parent tree. The explicit inclusion of
> > > s1.parent tree overrides the exclusion of s2.child, with a
> > > notice/warning.
> > >
> > > 7. FOR TABLE s2.child, TABLES IN SCHEMA s1 EXCEPT (TABLE s1.parent);
> > >  -- Same as case 5: publish s2.child, while excluding s1.parent and
> > > its children in s1.
> > >
> > > 8. FOR TABLES IN SCHEMA s1, TABLES IN SCHEMA s2 EXCEPT (TABLE s2.child);
> > >  -- Same as case 6: publish the full s1.parent tree, since s1 is
> > > included, so s2.child is published. The inclusion overrides the
> > > EXCEPT, with a notice/warning.
> > >
> > > With this approach, I don't think we need additional DDL restrictions.
> > > New tables/partitions added under an explicitly included schema would
> > > simply be included.
> > >
> > > I tried to cover the conflicting combinations including the ones
> > > discussed upthread. Please let me know if there are other cases that
> > > would still be ambiguous with this rule.
> > >
> > > Thoughts?
> > >
> >
> > While the proposal to let inclusion win over conflicting rules avoids
> > adding complex alter-table restrictions, I think it has a significant
> > drawback: relying on a NOTICE/warning to override an explicit EXCEPT
> > clause feels risky.
> >
> > An EXCEPT clause is an explicit data-filtering boundary. If a DBA/user
> > explicitly excludes a table or its child, for example, because it
> > contains sensitive data, I don't think we should silently override
> > that exclusion just because another inclusion rule happens to cover
> > the same relation indirectly.  A NOTICE or warning could easily be
> > missed, and we could end up publishing data that the user explicitly
> > intended to exclude. So, to me, the concern is not just that the
> > behavior could be surprising; we would actually be publishing
> > something that the user explicitly asked us not to publish.
>
> +1 If the user says EXCEPT then the only safe thing to do is what the
> user asked for. To do otherwise is effectively saying: “We see you
> wanted to exclude this table but we are going to publish it anyway
> because we figure you just made a mistake”.
>
> >
> > An Alternative Solution could be 'Strict Schema-Bound Isolation'
> > (Peter also suggested something similar earlier if I am not wrong,
> > which did not reach to conclusion). To avoid both DDL-blocking and
> > unsafe Exclusion overrides, we could adopt a Strict Schema-Bound
> > Isolation model.
> >
> > Core rule: Schema boundaries act as hard firewalls. An EXCEPT clause
> > defined for a specific schema applies only to objects physically
> > residing in that schema. Inclusion or exclusion through one schema
> > does not recursively "bleed over" into another schema or affect
> > partitions or inherited children that reside there.
>
> Something seems off here. The inclusion rules are already
> well-established. Partitioning really *does* bleed already into other
> unpublished schemas currently on HEAD.
>
> e.g.
> CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1;
>
> Inheritance:
> s1.parent INCLUDED
> s1.child INCLUDED
> s2.child NOT INCLUDED
>
> Partitioning:
> s1.root INCLUDED
> s1.part INCLUDED
> s2.part INCLUDED (it cascades to other schemas)
>

Right I found this case specially documented also in [1]: See:
"When a partitioned table is published via a schema-level publication,
all of its existing and future partitions are implicitly considered to
be part of the publication, regardless of whether they are from the
publication schema or not."

Thus, on re-thinking, we can apply a similar EXCLUSION rule to
partitions: excluding a partition root excludes all of its partitions,
even if their schemas are included separately. The only addition I
would make is that if a partition is explicitly included by name, then
it remains included.


Partition Case Rules:
-----------------------------------
a) By default, mentioning a 'partition root 'means that its entire
partition tree is included/excluded, irrespective of schema
boundaries, consistent with HEAD.
b) An explicitly mentioned partition is allowed and takes precedence
over the partition-tree exclusion.

Going through the cases again:
1. FOR TABLES IN SCHEMA s1 EXCEPT (s1.root), TABLES IN SCHEMA s2;
Excludes root: By default all its parition gets excluded, even the
ones present in s2.

2. FOR TABLES IN SCHEMA s1 EXCEPT (s1.root), FOR TABLE s1.p1;
Excludes s1.root: By default all its partitions get excluded except
s1.p1.  s1.p1 is still published as the user has explicitly mentioned
it.

3. FOR TABLES IN SCHEMA s1 EXCEPT (s1.root), FOR TABLE s2.p2;
Excludes s1.root: By default all its partitions get excluded except
s2.p2.   s2.p2 is still published as the user has explicitly mentioned
it.

4. FOR TABLE s1.root, FOR TABLES IN SCHEMA s1 EXCEPT (s1.root);
ERROR scenario: We cannot have the exact same table (root in this
case) included and excluded.


Inheritance Case Rules:
-----------------------------------
a) An EXCEPT clause associated with a schema does not follow the
inheritance hierarchy across schema boundaries. It only excludes the
parent and its descendants selected through that schema.
b) An explicitly mentioned child is allowed and takes precedence over
an exclusion inherited through the parent.

Going through the cases again:
5. FOR TABLES IN SCHEMA s1 EXCEPT (TABLE s1.parent), TABLES IN SCHEMA s2;

  --s1.parent and its children in s1 are excluded; while s2.child is
published.
  --if 'ONLY' is mentioned in EXCEPT, only s1.parent is excluded; all
its children in s1 and s2 are published.

6. FOR TABLE s1.parent, TABLES IN SCHEMA s2 EXCEPT (TABLE s2.child);

--s1.parent and all its children belonging to any schema should be
published because inclusion of s1.parent is not schema-bound. This
would mean, any child present in s3 would also be published, similar
to HEAD (see [2]).   s2.child will be excluded, as explicitly given by
the user.
--if 'ONLY' s1.parent is mentioned, only s1.parent is published.
s2.child is excluded by EXCEPT rule of s2.

7. FOR TABLE s2.child, TABLES IN SCHEMA s1 EXCEPT (TABLE s1.parent);

  -- s1.parent and all its children in s1 are excluded; s2.child is published.
  -- if 'ONLY' is mentioned in EXCEPT, only s1.parent is excluded; all
its children in s1 are published along with s2.child.

8. FOR TABLES IN SCHEMA s1, TABLES IN SCHEMA s2 EXCEPT (TABLE s2.child);
   --s1.parent is published with all its children present in s1 alone;
s2.child is excluded. This would mean unlike case 6, if any child is
present in s3, that will not be published. Taking the behaviour of
HEAD as the base (see [2]).

9. A new case: FOR TABLES IN SCHEMA s1 EXCEPT (TABLE s1.parent), TABLE s1.child;
   --s1.parent and its children in s1 are excluded; while s1.child is
still published.


[1]: https://www.postgresql.org/docs/19/sql-createpublication.html
[2]: https://www.postgresql.org/message-id/CAHut%2BPvpFR0%3D-AT_0QfjtWFov5ZT4yrfJgbAd-N7w%3DCzSm708g%40ma...

~~

Please reveiw this and let me know.

thanks
Shveta





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-24 11:38  Nisha Moond <nisha.moond412@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  2 siblings, 1 reply; 196+ messages in thread

From: Nisha Moond @ 2026-08-24 11:38 UTC (permalink / raw)
  To: shveta malik <shveta.malik@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; vignesh C <vignesh21@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Mon, Aug 24, 2026 at 3:25 PM shveta malik <shveta.malik@gmail.com> wrote:
>
> On Mon, Aug 24, 2026 at 12:55 PM Peter Smith <smithpb2250@gmail.com> wrote:
> >
> > On Mon, Aug 24, 2026 at 3:40 PM shveta malik <shveta.malik@gmail.com> wrote:
> > >
> > > While the proposal to let inclusion win over conflicting rules avoids
> > > adding complex alter-table restrictions, I think it has a significant
> > > drawback: relying on a NOTICE/warning to override an explicit EXCEPT
> > > clause feels risky.
> > >
> > > An EXCEPT clause is an explicit data-filtering boundary. If a DBA/user
> > > explicitly excludes a table or its child, for example, because it
> > > contains sensitive data, I don't think we should silently override
> > > that exclusion just because another inclusion rule happens to cover
> > > the same relation indirectly.  A NOTICE or warning could easily be
> > > missed, and we could end up publishing data that the user explicitly
> > > intended to exclude. So, to me, the concern is not just that the
> > > behavior could be surprising; we would actually be publishing
> > > something that the user explicitly asked us not to publish.
> >
> > +1 If the user says EXCEPT then the only safe thing to do is what the
> > user asked for. To do otherwise is effectively saying: “We see you
> > wanted to exclude this table but we are going to publish it anyway
> > because we figure you just made a mistake”.
> >
> > >
> > > An Alternative Solution could be 'Strict Schema-Bound Isolation'
> > > (Peter also suggested something similar earlier if I am not wrong,
> > > which did not reach to conclusion). To avoid both DDL-blocking and
> > > unsafe Exclusion overrides, we could adopt a Strict Schema-Bound
> > > Isolation model.
> > >
> > > Core rule: Schema boundaries act as hard firewalls. An EXCEPT clause
> > > defined for a specific schema applies only to objects physically
> > > residing in that schema. Inclusion or exclusion through one schema
> > > does not recursively "bleed over" into another schema or affect
> > > partitions or inherited children that reside there.
> >
> > Something seems off here. The inclusion rules are already
> > well-established. Partitioning really *does* bleed already into other
> > unpublished schemas currently on HEAD.
> >
> > e.g.
> > CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1;
> >
> > Inheritance:
> > s1.parent INCLUDED
> > s1.child INCLUDED
> > s2.child NOT INCLUDED
> >
> > Partitioning:
> > s1.root INCLUDED
> > s1.part INCLUDED
> > s2.part INCLUDED (it cascades to other schemas)
> >
>
> Right I found this case specially documented also in [1]: See:
> "When a partitioned table is published via a schema-level publication,
> all of its existing and future partitions are implicitly considered to
> be part of the publication, regardless of whether they are from the
> publication schema or not."
>
> Thus, on re-thinking, we can apply a similar EXCLUSION rule to
> partitions: excluding a partition root excludes all of its partitions,
> even if their schemas are included separately. The only addition I
> would make is that if a partition is explicitly included by name, then
> it remains included.
>

To me, keeping the PARTITION and INHERITANCE behavior different for
EXCEPT also seems reasonable, since their behavior is already
different on HEAD.

>
> Partition Case Rules:
> -----------------------------------
> a) By default, mentioning a 'partition root 'means that its entire
> partition tree is included/excluded, irrespective of schema
> boundaries, consistent with HEAD.
> b) An explicitly mentioned partition is allowed and takes precedence
> over the partition-tree exclusion.
>
> Going through the cases again:
> 1. FOR TABLES IN SCHEMA s1 EXCEPT (s1.root), TABLES IN SCHEMA s2;
> Excludes root: By default all its parition gets excluded, even the
> ones present in s2.
>

I’m okay with the proposed behavior. It will avoid the required DDL
blocking mentioned at [1]

> 2. FOR TABLES IN SCHEMA s1 EXCEPT (s1.root), FOR TABLE s1.p1;
> Excludes s1.root: By default all its partitions get excluded except
> s1.p1.  s1.p1 is still published as the user has explicitly mentioned
> it.
>
> 3. FOR TABLES IN SCHEMA s1 EXCEPT (s1.root), FOR TABLE s2.p2;
> Excludes s1.root: By default all its partitions get excluded except
> s2.p2.   s2.p2 is still published as the user has explicitly mentioned
> it.
>
> 4. FOR TABLE s1.root, FOR TABLES IN SCHEMA s1 EXCEPT (s1.root);
> ERROR scenario: We cannot have the exact same table (root in this
> case) included and excluded.
>

Agree.

>
> Inheritance Case Rules:
> -----------------------------------
> a) An EXCEPT clause associated with a schema does not follow the
> inheritance hierarchy across schema boundaries. It only excludes the
> parent and its descendants selected through that schema.
> b) An explicitly mentioned child is allowed and takes precedence over
> an exclusion inherited through the parent.
>
> Going through the cases again:
> 5. FOR TABLES IN SCHEMA s1 EXCEPT (TABLE s1.parent), TABLES IN SCHEMA s2;
>
>   --s1.parent and its children in s1 are excluded; while s2.child is
> published.
>   --if 'ONLY' is mentioned in EXCEPT, only s1.parent is excluded; all
> its children in s1 and s2 are published.
>
> 6. FOR TABLE s1.parent, TABLES IN SCHEMA s2 EXCEPT (TABLE s2.child);
>
> --s1.parent and all its children belonging to any schema should be
> published because inclusion of s1.parent is not schema-bound. This
> would mean, any child present in s3 would also be published, similar
> to HEAD (see [2]).   s2.child will be excluded, as explicitly given by
> the user.
> --if 'ONLY' s1.parent is mentioned, only s1.parent is published.
> s2.child is excluded by EXCEPT rule of s2.
>
> 7. FOR TABLE s2.child, TABLES IN SCHEMA s1 EXCEPT (TABLE s1.parent);
>
>   -- s1.parent and all its children in s1 are excluded; s2.child is published.
>   -- if 'ONLY' is mentioned in EXCEPT, only s1.parent is excluded; all
> its children in s1 are published along with s2.child.
>
> 8. FOR TABLES IN SCHEMA s1, TABLES IN SCHEMA s2 EXCEPT (TABLE s2.child);
>    --s1.parent is published with all its children present in s1 alone;
> s2.child is excluded. This would mean unlike case 6, if any child is
> present in s3, that will not be published. Taking the behaviour of
> HEAD as the base (see [2]).
>
> 9. A new case: FOR TABLES IN SCHEMA s1 EXCEPT (TABLE s1.parent), TABLE s1.child;
>    --s1.parent and its children in s1 are excluded; while s1.child is
> still published.
>

As for the TABLES IN SCHEMA, inclusion of an inherited parent is
schema-scoped. I re-analyzed the cases under these rules where the two
clauses in the same command conflict, i.e., one includes and the other
excludes the same table or tree within their respective scopes.

I think cases 5, 7, and 8 are not really conflicting, since s1 and s2
do not cross each other’s schema boundaries. So, no additional
handling should be needed for these cases.

The only conflicting cases I see are 6, 9, and the following new case:
10) FOR TABLE s1.parent, TABLES IN SCHEMA s1 EXCEPT (s1.child1)
  -- s1.parent and all its children are published, except s1.child1,
as explicitly given by the user.

The remaining possible conflicts seem to be clear ERROR cases:
 - FOR TABLE s1.parent, TABLES IN SCHEMA s1 EXCEPT (s1.parent)
 - FOR TABLE s1.parent, TABLES IN SCHEMA s1 EXCEPT (ONLY s1.parent)
 - FOR TABLE s1.child,  TABLES IN SCHEMA s1 EXCEPT (s1.child)
 - FOR TABLE s2.child,  TABLES IN SCHEMA s2 EXCEPT (s2.child)

>
> [1]: https://www.postgresql.org/docs/19/sql-createpublication.html
> [2]: https://www.postgresql.org/message-id/CAHut%2BPvpFR0%3D-AT_0QfjtWFov5ZT4yrfJgbAd-N7w%3DCzSm708g%40ma...
>
> ~~
>
> Please reveiw this and let me know.
>

With these rules, I think we can reduce code complexity and avoid the
need for any additional table DDL blocking.

I’ll think about this a bit more and get back.

--
Thanks,
Nisha






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-25 06:38  Amit Kapila <amit.kapila16@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  2 siblings, 1 reply; 196+ messages in thread

From: Amit Kapila @ 2026-08-25 06:38 UTC (permalink / raw)
  To: shveta malik <shveta.malik@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; Nisha Moond <nisha.moond412@gmail.com>; vignesh C <vignesh21@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Mon, Aug 24, 2026 at 3:25 PM shveta malik <shveta.malik@gmail.com> wrote:
>
> Partition Case Rules:
> -----------------------------------
> a) By default, mentioning a 'partition root 'means that its entire
> partition tree is included/excluded, irrespective of schema
> boundaries, consistent with HEAD.
> b) An explicitly mentioned partition is allowed and takes precedence
> over the partition-tree exclusion.
>
> Going through the cases again:
> 1. FOR TABLES IN SCHEMA s1 EXCEPT (s1.root), TABLES IN SCHEMA s2;
> Excludes root: By default all its parition gets excluded, even the
> ones present in s2.
>
> 2. FOR TABLES IN SCHEMA s1 EXCEPT (s1.root), FOR TABLE s1.p1;
> Excludes s1.root: By default all its partitions get excluded except
> s1.p1.  s1.p1 is still published as the user has explicitly mentioned
> it.
>

Both the above cases seem to fall in the same category though for the
first one the table is not explicitly mentioned but TABLES IN SCHEMA
does mean all tables in that schema. The another point I see in making
both above cases behave similar (follow what you mentioned in 2) is
that we will follow the same behavior when two different publications
(pub1 FOR TABLES IN SCHEMA s1 EXCEPT (s1.root) and pub2  FOR TABLES IN
SCHEMA s2;) that specify the two clauses separately are combined by
SUBSCRIPTION.

-- 
With Regards,
Amit Kapila.





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-25 07:35  Peter Smith <smithpb2250@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  2 siblings, 1 reply; 196+ messages in thread

From: Peter Smith @ 2026-08-25 07:35 UTC (permalink / raw)
  To: shveta malik <shveta.malik@gmail.com>; +Cc: Nisha Moond <nisha.moond412@gmail.com>; vignesh C <vignesh21@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Mon, Aug 24, 2026 at 7:55 PM shveta malik <shveta.malik@gmail.com> wrote:
>
...
>
>
> Partition Case Rules:
> -----------------------------------
> a) By default, mentioning a 'partition root 'means that its entire
> partition tree is included/excluded, irrespective of schema
> boundaries, consistent with HEAD.
> b) An explicitly mentioned partition is allowed and takes precedence
> over the partition-tree exclusion.

OK.
Also (c). A partition cannot be mentioned as an explicit *exclusion*
because we only allow partition roots in EXCEPT.
Also (d). "EXCEPT (TABLE ONLY root)" -- the ONLY is completely ignored
for partitions so that is identical to "EXCEPT (TABLE root)", right?

>
> Going through the cases again:
> 1. FOR TABLES IN SCHEMA s1 EXCEPT (s1.root), TABLES IN SCHEMA s2;
> Excludes root: By default all its parition gets excluded, even the
> ones present in s2.
>
> 2. FOR TABLES IN SCHEMA s1 EXCEPT (s1.root), FOR TABLE s1.p1;
> Excludes s1.root: By default all its partitions get excluded except
> s1.p1.  s1.p1 is still published as the user has explicitly mentioned
> it.
>
> 3. FOR TABLES IN SCHEMA s1 EXCEPT (s1.root), FOR TABLE s2.p2;
> Excludes s1.root: By default all its partitions get excluded except
> s2.p2.   s2.p2 is still published as the user has explicitly mentioned
> it.
>
> 4. FOR TABLE s1.root, FOR TABLES IN SCHEMA s1 EXCEPT (s1.root);
> ERROR scenario: We cannot have the exact same table (root in this
> case) included and excluded.
>
>
> Inheritance Case Rules:
> -----------------------------------
> a) An EXCEPT clause associated with a schema does not follow the
> inheritance hierarchy across schema boundaries. It only excludes the
> parent and its descendants selected through that schema.
> b) An explicitly mentioned child is allowed and takes precedence over
> an exclusion inherited through the parent.

OK.
For (b) you said explicit child takes precedence over exclusion
inherited by parent.
I think example is: TABLE IN SCHEMA s1 (EXCEPT s1.parent), TABLE
s1.child; --- child stays

But your rules don't say anything what happens for explicit child
taking precedence inherited **inclusion**
e.g. TABLE s1.parent, TABLES IN SCHEMA s1 EXCEPT (TABLE s1.child); --
I think child excluded, right?

>
> Please reveiw this and let me know.
>

AFAICT all your example SQL results LGTM, but, IMO there are many
dozens more combinations (I have itemized over 100 variations so
far...). Sure, all these might all fall into just a few same-behaviour
categories, but OTOH there could be some unaccounted edge-cases. I am
currently trying to make a giant matrix of them all, but it is taking
much longer than expected.

The suggested rules might still be OK -- I just don't know yet.

~~~

Finally, there is another nasty hand-grenade to be lobbed into this
thread, otherwise it might get overlooked...

AFAIK, it is possible to have diamond-shaped inheritance:

e.g.
CREATE TABLE vehicle ( name text );
CREATE TABLE boat () INHERITS (vehicle);
CREATE TABLE car () INHERITS (vehicle);
CREATE TABLE boatcar () INHERITS (boat,car);
INSERT INTO boatcar (name) VALUES ('amphibious car');

       vehicle
          /\
         /  \
        /    \
     boat    car
        \    /
         \  /
          \/
        boatcar

I have no idea what problems that's going to cause for SCHEMA EXCEPT,
but it can't be good, and it needs to be handled somehow.

======
Kind Regards,
Peter Smith.
Fujitsu Australia






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-25 08:27  shveta malik <shveta.malik@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  0 siblings, 0 replies; 196+ messages in thread

From: shveta malik @ 2026-08-25 08:27 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; vignesh C <vignesh21@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; shveta malik <shveta.malik@gmail.com>

On Mon, Aug 24, 2026 at 5:08 PM Nisha Moond <nisha.moond412@gmail.com> wrote:
>
> On Mon, Aug 24, 2026 at 3:25 PM shveta malik <shveta.malik@gmail.com> wrote:
> >
> > On Mon, Aug 24, 2026 at 12:55 PM Peter Smith <smithpb2250@gmail.com> wrote:
> > >
> > > On Mon, Aug 24, 2026 at 3:40 PM shveta malik <shveta.malik@gmail.com> wrote:
> > > >
> > > > While the proposal to let inclusion win over conflicting rules avoids
> > > > adding complex alter-table restrictions, I think it has a significant
> > > > drawback: relying on a NOTICE/warning to override an explicit EXCEPT
> > > > clause feels risky.
> > > >
> > > > An EXCEPT clause is an explicit data-filtering boundary. If a DBA/user
> > > > explicitly excludes a table or its child, for example, because it
> > > > contains sensitive data, I don't think we should silently override
> > > > that exclusion just because another inclusion rule happens to cover
> > > > the same relation indirectly.  A NOTICE or warning could easily be
> > > > missed, and we could end up publishing data that the user explicitly
> > > > intended to exclude. So, to me, the concern is not just that the
> > > > behavior could be surprising; we would actually be publishing
> > > > something that the user explicitly asked us not to publish.
> > >
> > > +1 If the user says EXCEPT then the only safe thing to do is what the
> > > user asked for. To do otherwise is effectively saying: “We see you
> > > wanted to exclude this table but we are going to publish it anyway
> > > because we figure you just made a mistake”.
> > >
> > > >
> > > > An Alternative Solution could be 'Strict Schema-Bound Isolation'
> > > > (Peter also suggested something similar earlier if I am not wrong,
> > > > which did not reach to conclusion). To avoid both DDL-blocking and
> > > > unsafe Exclusion overrides, we could adopt a Strict Schema-Bound
> > > > Isolation model.
> > > >
> > > > Core rule: Schema boundaries act as hard firewalls. An EXCEPT clause
> > > > defined for a specific schema applies only to objects physically
> > > > residing in that schema. Inclusion or exclusion through one schema
> > > > does not recursively "bleed over" into another schema or affect
> > > > partitions or inherited children that reside there.
> > >
> > > Something seems off here. The inclusion rules are already
> > > well-established. Partitioning really *does* bleed already into other
> > > unpublished schemas currently on HEAD.
> > >
> > > e.g.
> > > CREATE PUBLICATION pub FOR TABLES IN SCHEMA s1;
> > >
> > > Inheritance:
> > > s1.parent INCLUDED
> > > s1.child INCLUDED
> > > s2.child NOT INCLUDED
> > >
> > > Partitioning:
> > > s1.root INCLUDED
> > > s1.part INCLUDED
> > > s2.part INCLUDED (it cascades to other schemas)
> > >
> >
> > Right I found this case specially documented also in [1]: See:
> > "When a partitioned table is published via a schema-level publication,
> > all of its existing and future partitions are implicitly considered to
> > be part of the publication, regardless of whether they are from the
> > publication schema or not."
> >
> > Thus, on re-thinking, we can apply a similar EXCLUSION rule to
> > partitions: excluding a partition root excludes all of its partitions,
> > even if their schemas are included separately. The only addition I
> > would make is that if a partition is explicitly included by name, then
> > it remains included.
> >
>
> To me, keeping the PARTITION and INHERITANCE behavior different for
> EXCEPT also seems reasonable, since their behavior is already
> different on HEAD.
>
> >
> > Partition Case Rules:
> > -----------------------------------
> > a) By default, mentioning a 'partition root 'means that its entire
> > partition tree is included/excluded, irrespective of schema
> > boundaries, consistent with HEAD.
> > b) An explicitly mentioned partition is allowed and takes precedence
> > over the partition-tree exclusion.
> >
> > Going through the cases again:
> > 1. FOR TABLES IN SCHEMA s1 EXCEPT (s1.root), TABLES IN SCHEMA s2;
> > Excludes root: By default all its parition gets excluded, even the
> > ones present in s2.
> >
>
> I’m okay with the proposed behavior. It will avoid the required DDL
> blocking mentioned at [1]
>
> > 2. FOR TABLES IN SCHEMA s1 EXCEPT (s1.root), FOR TABLE s1.p1;
> > Excludes s1.root: By default all its partitions get excluded except
> > s1.p1.  s1.p1 is still published as the user has explicitly mentioned
> > it.
> >
> > 3. FOR TABLES IN SCHEMA s1 EXCEPT (s1.root), FOR TABLE s2.p2;
> > Excludes s1.root: By default all its partitions get excluded except
> > s2.p2.   s2.p2 is still published as the user has explicitly mentioned
> > it.
> >
> > 4. FOR TABLE s1.root, FOR TABLES IN SCHEMA s1 EXCEPT (s1.root);
> > ERROR scenario: We cannot have the exact same table (root in this
> > case) included and excluded.
> >
>
> Agree.
>
> >
> > Inheritance Case Rules:
> > -----------------------------------
> > a) An EXCEPT clause associated with a schema does not follow the
> > inheritance hierarchy across schema boundaries. It only excludes the
> > parent and its descendants selected through that schema.
> > b) An explicitly mentioned child is allowed and takes precedence over
> > an exclusion inherited through the parent.
> >
> > Going through the cases again:
> > 5. FOR TABLES IN SCHEMA s1 EXCEPT (TABLE s1.parent), TABLES IN SCHEMA s2;
> >
> >   --s1.parent and its children in s1 are excluded; while s2.child is
> > published.
> >   --if 'ONLY' is mentioned in EXCEPT, only s1.parent is excluded; all
> > its children in s1 and s2 are published.
> >
> > 6. FOR TABLE s1.parent, TABLES IN SCHEMA s2 EXCEPT (TABLE s2.child);
> >
> > --s1.parent and all its children belonging to any schema should be
> > published because inclusion of s1.parent is not schema-bound. This
> > would mean, any child present in s3 would also be published, similar
> > to HEAD (see [2]).   s2.child will be excluded, as explicitly given by
> > the user.
> > --if 'ONLY' s1.parent is mentioned, only s1.parent is published.
> > s2.child is excluded by EXCEPT rule of s2.
> >
> > 7. FOR TABLE s2.child, TABLES IN SCHEMA s1 EXCEPT (TABLE s1.parent);
> >
> >   -- s1.parent and all its children in s1 are excluded; s2.child is published.
> >   -- if 'ONLY' is mentioned in EXCEPT, only s1.parent is excluded; all
> > its children in s1 are published along with s2.child.
> >
> > 8. FOR TABLES IN SCHEMA s1, TABLES IN SCHEMA s2 EXCEPT (TABLE s2.child);
> >    --s1.parent is published with all its children present in s1 alone;
> > s2.child is excluded. This would mean unlike case 6, if any child is
> > present in s3, that will not be published. Taking the behaviour of
> > HEAD as the base (see [2]).
> >
> > 9. A new case: FOR TABLES IN SCHEMA s1 EXCEPT (TABLE s1.parent), TABLE s1.child;
> >    --s1.parent and its children in s1 are excluded; while s1.child is
> > still published.
> >
>
> As for the TABLES IN SCHEMA, inclusion of an inherited parent is
> schema-scoped. I re-analyzed the cases under these rules where the two
> clauses in the same command conflict, i.e., one includes and the other
> excludes the same table or tree within their respective scopes.
>
> I think cases 5, 7, and 8 are not really conflicting, since s1 and s2
> do not cross each other’s schema boundaries.

Right.

>  So, no additional
> handling should be needed for these cases.

I hope so. We need to verify though on your new patch.

> The only conflicting cases I see are 6, 9, and the following new case:
> 10) FOR TABLE s1.parent, TABLES IN SCHEMA s1 EXCEPT (s1.child1)
>   -- s1.parent and all its children are published, except s1.child1,
> as explicitly given by the user.

Right.

> The remaining possible conflicts seem to be clear ERROR cases:
>  - FOR TABLE s1.parent, TABLES IN SCHEMA s1 EXCEPT (s1.parent)
>  - FOR TABLE s1.parent, TABLES IN SCHEMA s1 EXCEPT (ONLY s1.parent)
>  - FOR TABLE s1.child,  TABLES IN SCHEMA s1 EXCEPT (s1.child)
>  - FOR TABLE s2.child,  TABLES IN SCHEMA s2 EXCEPT (s2.child)

Agree.

> >
> > [1]: https://www.postgresql.org/docs/19/sql-createpublication.html
> > [2]: https://www.postgresql.org/message-id/CAHut%2BPvpFR0%3D-AT_0QfjtWFov5ZT4yrfJgbAd-N7w%3DCzSm708g%40ma...
> >
> > ~~
> >
> > Please reveiw this and let me know.
> >
>
> With these rules, I think we can reduce code complexity and avoid the
> need for any additional table DDL blocking.
>
> I’ll think about this a bit more and get back.

Okay.

thanks
Shveta





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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-25 08:49  shveta malik <shveta.malik@gmail.com>
  parent: Peter Smith <smithpb2250@gmail.com>
  0 siblings, 1 reply; 196+ messages in thread

From: shveta malik @ 2026-08-25 08:49 UTC (permalink / raw)
  To: Peter Smith <smithpb2250@gmail.com>; +Cc: Nisha Moond <nisha.moond412@gmail.com>; vignesh C <vignesh21@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; shveta malik <shveta.malik@gmail.com>

On Tue, Aug 25, 2026 at 1:05 PM Peter Smith <smithpb2250@gmail.com> wrote:
>
> On Mon, Aug 24, 2026 at 7:55 PM shveta malik <shveta.malik@gmail.com> wrote:
> >
> ...
> >
> >
> > Partition Case Rules:
> > -----------------------------------
> > a) By default, mentioning a 'partition root 'means that its entire
> > partition tree is included/excluded, irrespective of schema
> > boundaries, consistent with HEAD.
> > b) An explicitly mentioned partition is allowed and takes precedence
> > over the partition-tree exclusion.
>
> OK.
> Also (c). A partition cannot be mentioned as an explicit *exclusion*
> because we only allow partition roots in EXCEPT.
> Also (d). "EXCEPT (TABLE ONLY root)" -- the ONLY is completely ignored
> for partitions so that is identical to "EXCEPT (TABLE root)", right?

Right.

> >
> > Going through the cases again:
> > 1. FOR TABLES IN SCHEMA s1 EXCEPT (s1.root), TABLES IN SCHEMA s2;
> > Excludes root: By default all its parition gets excluded, even the
> > ones present in s2.
> >
> > 2. FOR TABLES IN SCHEMA s1 EXCEPT (s1.root), FOR TABLE s1.p1;
> > Excludes s1.root: By default all its partitions get excluded except
> > s1.p1.  s1.p1 is still published as the user has explicitly mentioned
> > it.
> >
> > 3. FOR TABLES IN SCHEMA s1 EXCEPT (s1.root), FOR TABLE s2.p2;
> > Excludes s1.root: By default all its partitions get excluded except
> > s2.p2.   s2.p2 is still published as the user has explicitly mentioned
> > it.
> >
> > 4. FOR TABLE s1.root, FOR TABLES IN SCHEMA s1 EXCEPT (s1.root);
> > ERROR scenario: We cannot have the exact same table (root in this
> > case) included and excluded.
> >
> >
> > Inheritance Case Rules:
> > -----------------------------------
> > a) An EXCEPT clause associated with a schema does not follow the
> > inheritance hierarchy across schema boundaries. It only excludes the
> > parent and its descendants selected through that schema.
> > b) An explicitly mentioned child is allowed and takes precedence over
> > an exclusion inherited through the parent.
>
> OK.
> For (b) you said explicit child takes precedence over exclusion
> inherited by parent.
> I think example is: TABLE IN SCHEMA s1 (EXCEPT s1.parent), TABLE
> s1.child; --- child stays

yes. Right.

> But your rules don't say anything what happens for explicit child
> taking precedence inherited **inclusion**
> e.g. TABLE s1.parent, TABLES IN SCHEMA s1 EXCEPT (TABLE s1.child); --
> I think child excluded, right?

Yes. The child is excluded because the user explicitly mentioned it.

> >
> > Please reveiw this and let me know.
> >
>
> AFAICT all your example SQL results LGTM, but, IMO there are many
> dozens more combinations (I have itemized over 100 variations so
> far...). Sure, all these might all fall into just a few same-behaviour
> categories, but OTOH there could be some unaccounted edge-cases. I am
> currently trying to make a giant matrix of them all, but it is taking
> much longer than expected.

yes, the matrix will help; otherwise, we may end up missing some scenarios.

> The suggested rules might still be OK -- I just don't know yet.
>
> ~~~
>
> Finally, there is another nasty hand-grenade to be lobbed into this
> thread, otherwise it might get overlooked...

Yes, I think we completely missed it in our earlier analysis. Thanks
for pointing it out.

> AFAIK, it is possible to have diamond-shaped inheritance:
>
> e.g.
> CREATE TABLE vehicle ( name text );
> CREATE TABLE boat () INHERITS (vehicle);
> CREATE TABLE car () INHERITS (vehicle);
> CREATE TABLE boatcar () INHERITS (boat,car);
> INSERT INTO boatcar (name) VALUES ('amphibious car');
>
>        vehicle
>           /\
>          /  \
>         /    \
>      boat    car
>         \    /
>          \  /
>           \/
>         boatcar

The one tricky scenario I see here is when 'boat' is included while
'car' is excluded: what happens to boatcar? Does it stay or is it
excluded? We need to establish a rule here. I will think more about
this.

thanks
Shveta






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-08-25 10:06  shveta malik <shveta.malik@gmail.com>
  parent: Amit Kapila <amit.kapila16@gmail.com>
  0 siblings, 0 replies; 196+ messages in thread

From: shveta malik @ 2026-08-25 10:06 UTC (permalink / raw)
  To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: Peter Smith <smithpb2250@gmail.com>; Nisha Moond <nisha.moond412@gmail.com>; vignesh C <vignesh21@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; shveta malik <shveta.malik@gmail.com>

On Tue, Aug 25, 2026 at 12:08 PM Amit Kapila <amit.kapila16@gmail.com> wrote:
>
> On Mon, Aug 24, 2026 at 3:25 PM shveta malik <shveta.malik@gmail.com> wrote:
> >
> > Partition Case Rules:
> > -----------------------------------
> > a) By default, mentioning a 'partition root 'means that its entire
> > partition tree is included/excluded, irrespective of schema
> > boundaries, consistent with HEAD.
> > b) An explicitly mentioned partition is allowed and takes precedence
> > over the partition-tree exclusion.
> >
> > Going through the cases again:
> > 1. FOR TABLES IN SCHEMA s1 EXCEPT (s1.root), TABLES IN SCHEMA s2;
> > Excludes root: By default all its parition gets excluded, even the
> > ones present in s2.
> >
> > 2. FOR TABLES IN SCHEMA s1 EXCEPT (s1.root), FOR TABLE s1.p1;
> > Excludes s1.root: By default all its partitions get excluded except
> > s1.p1.  s1.p1 is still published as the user has explicitly mentioned
> > it.
> >
>
> Both the above cases seem to fall in the same category though for the
> first one the table is not explicitly mentioned but TABLES IN SCHEMA
> does mean all tables in that schema. The another point I see in making
> both above cases behave similar (follow what you mentioned in 2) is
> that we will follow the same behavior when two different publications
> (pub1 FOR TABLES IN SCHEMA s1 EXCEPT (s1.root) and pub2  FOR TABLES IN
> SCHEMA s2;) that specify the two clauses separately are combined by
> SUBSCRIPTION.

The drawback I see with this approach is that it leaves the user with
no way to exclude an entire root tree (including s2.p2) while still
including everything else in schema s2. If we are relying on a future
EXCEPT (leaf_partition) implementation to address this, that does not
seem practical to me. The 'exclusion on partition' approach already
had numerous issues even for a simple ALL TABLES publication, and with
the additional cross-schema complexities here, I don't see it being
addressed anytime soon.

Additionally, if we adopt the analogy that a single publication with
mixed rules should behave exactly like multiple independent
publications combined on a subscription, then we need to apply that
principle consistently across all cases.  Example, for inheritance
case:
 FOR TABLE s1.parent, TABLES IN SCHEMA s2 EXCEPT (TABLE s2.child);

Currently, this explicitly excludes s2.child. But if we treat this as
equivalent to two independent publications combined together: pub1:
FOR TABLE s1.parent;  pub2: TABLES IN SCHEMA s2 EXCEPT (TABLE
s2.child) ; then, under the "inclusion wins" rule, s2.child would be
published. The "inclusion wins" (see [1]) approach had a basic
problem: to achieve it, we had to ignore EXCEPTs in many cases, which
didn't seem acceptable to me. But let me know what do you think.

[1]: https://www.postgresql.org/message-id/CABdArM7javjNBWoS0d8qgESaMqdja-0JG3wr%2BWVn6%3DbRg92m4A%40mail...

thanks
Shveta






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-09-02 11:19  Nisha Moond <nisha.moond412@gmail.com>
  parent: Peter Smith <smithpb2250@gmail.com>
  1 sibling, 0 replies; 196+ messages in thread

From: Nisha Moond @ 2026-09-02 11:19 UTC (permalink / raw)
  To: Peter Smith <smithpb2250@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; vignesh C <vignesh21@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

On Tue, Sep 1, 2026 at 12:13 PM Peter Smith <smithpb2250@gmail.com> wrote:
>
> Each time new EXCEPT rules are proposed in this thread, they come with
> a worked examples, but I felt there was still a risk that other
> combinations could be broken and go unnoticed. Then, when a
> problematic combination is later encountered, we're back to square one
> again.
>
> To help avoid that, I made a matrix of *many* combinations (~300),
> covering both inheritance and partitioning.
>
> Also, TBH I was getting lost keeping track of what "case 1", "case 2",
> etc. meant. In this matrix, every case can instead be referred to like
> "11x23" — a combo of clauses "11" and "23" (the first digit being the
> schema). This makes it easy to refer to any of the 300 combinations
> unambiguously. Furthermore, the same combination numbers (e.g. 11x23)
> mean the same thing in both the INHERITANCE and PARTITIONING matrices,
> so the two can be directly compared.
>
> PSA the doc containing the matrices, rules, results, diagrams, and a
> key for interpreting them.
>
> My conclusion is that the rules proposed by Shveta ([1] and also
> included in the document) are sound; they can be applied to all these
> combinations to give unambiguous results. FWIW, my AI checking
> confirms the matrix results are consistent.
>
> Of course, there are more possible variations (e.g. diamond
> inheritance shapes), but IMO these 300 test cases give a much more
> solid starting point.
>

Thanks, Peter, for putting in such a huge effort to work through these
cases. I’ll go through them carefully and get back to you.

--
Nisha






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-09-03 04:57  shveta malik <shveta.malik@gmail.com>
  parent: Peter Smith <smithpb2250@gmail.com>
  1 sibling, 0 replies; 196+ messages in thread

From: shveta malik @ 2026-09-03 04:57 UTC (permalink / raw)
  To: Peter Smith <smithpb2250@gmail.com>; +Cc: Nisha Moond <nisha.moond412@gmail.com>; vignesh C <vignesh21@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org; shveta malik <shveta.malik@gmail.com>

On Tue, Sep 1, 2026 at 12:13 PM Peter Smith <smithpb2250@gmail.com> wrote:
>
> On Tue, Aug 25, 2026 at 6:49 PM shveta malik <shveta.malik@gmail.com> wrote:
> >
> > On Tue, Aug 25, 2026 at 1:05 PM Peter Smith <smithpb2250@gmail.com> wrote:
> > >
> > > On Mon, Aug 24, 2026 at 7:55 PM shveta malik <shveta.malik@gmail.com> wrote:
> > > >
> > > ...
> > > >
> > > >
> > > > Partition Case Rules:
> > > > -----------------------------------
> > > > a) By default, mentioning a 'partition root 'means that its entire
> > > > partition tree is included/excluded, irrespective of schema
> > > > boundaries, consistent with HEAD.
> > > > b) An explicitly mentioned partition is allowed and takes precedence
> > > > over the partition-tree exclusion.
> > >
> > > OK.
> > > Also (c). A partition cannot be mentioned as an explicit *exclusion*
> > > because we only allow partition roots in EXCEPT.
> > > Also (d). "EXCEPT (TABLE ONLY root)" -- the ONLY is completely ignored
> > > for partitions so that is identical to "EXCEPT (TABLE root)", right?
> >
> > Right.
> >
> > > >
> > > > Going through the cases again:
> > > > 1. FOR TABLES IN SCHEMA s1 EXCEPT (s1.root), TABLES IN SCHEMA s2;
> > > > Excludes root: By default all its parition gets excluded, even the
> > > > ones present in s2.
> > > >
> > > > 2. FOR TABLES IN SCHEMA s1 EXCEPT (s1.root), FOR TABLE s1.p1;
> > > > Excludes s1.root: By default all its partitions get excluded except
> > > > s1.p1.  s1.p1 is still published as the user has explicitly mentioned
> > > > it.
> > > >
> > > > 3. FOR TABLES IN SCHEMA s1 EXCEPT (s1.root), FOR TABLE s2.p2;
> > > > Excludes s1.root: By default all its partitions get excluded except
> > > > s2.p2.   s2.p2 is still published as the user has explicitly mentioned
> > > > it.
> > > >
> > > > 4. FOR TABLE s1.root, FOR TABLES IN SCHEMA s1 EXCEPT (s1.root);
> > > > ERROR scenario: We cannot have the exact same table (root in this
> > > > case) included and excluded.
> > > >
> > > >
> > > > Inheritance Case Rules:
> > > > -----------------------------------
> > > > a) An EXCEPT clause associated with a schema does not follow the
> > > > inheritance hierarchy across schema boundaries. It only excludes the
> > > > parent and its descendants selected through that schema.
> > > > b) An explicitly mentioned child is allowed and takes precedence over
> > > > an exclusion inherited through the parent.
> > >
> > > OK.
> > > For (b) you said explicit child takes precedence over exclusion
> > > inherited by parent.
> > > I think example is: TABLE IN SCHEMA s1 (EXCEPT s1.parent), TABLE
> > > s1.child; --- child stays
> >
> > yes. Right.
> >
> > > But your rules don't say anything what happens for explicit child
> > > taking precedence inherited **inclusion**
> > > e.g. TABLE s1.parent, TABLES IN SCHEMA s1 EXCEPT (TABLE s1.child); --
> > > I think child excluded, right?
> >
> > Yes. The child is excluded because the user explicitly mentioned it.
> >
> > > >
> > > > Please reveiw this and let me know.
> > > >
> > >
> > > AFAICT all your example SQL results LGTM, but, IMO there are many
> > > dozens more combinations (I have itemized over 100 variations so
> > > far...). Sure, all these might all fall into just a few same-behaviour
> > > categories, but OTOH there could be some unaccounted edge-cases. I am
> > > currently trying to make a giant matrix of them all, but it is taking
> > > much longer than expected.
> >
> > yes, the matrix will help; otherwise, we may end up missing some scenarios.
> >
> > > The suggested rules might still be OK -- I just don't know yet.
> > >
> > > ~~~
>
>
> Each time new EXCEPT rules are proposed in this thread, they come with
> a worked examples, but I felt there was still a risk that other
> combinations could be broken and go unnoticed. Then, when a
> problematic combination is later encountered, we're back to square one
> again.
>
> To help avoid that, I made a matrix of *many* combinations (~300),
> covering both inheritance and partitioning.

Thanks Peter. I think that if we come up with a new proposal, we
should refer to this matrix to see that all the cases resolve
correctly.

I have gone through the matrix and it looks good to me. It should
serve as a starting point to finalize any proposal.

> Also, TBH I was getting lost keeping track of what "case 1", "case 2",
> etc. meant. In this matrix, every case can instead be referred to like
> "11x23" — a combo of clauses "11" and "23" (the first digit being the
> schema). This makes it easy to refer to any of the 300 combinations
> unambiguously. Furthermore, the same combination numbers (e.g. 11x23)
> mean the same thing in both the INHERITANCE and PARTITIONING matrices,
> so the two can be directly compared.
>
> PSA the doc containing the matrices, rules, results, diagrams, and a
> key for interpreting them.
>
> My conclusion is that the rules proposed by Shveta ([1] and also
> included in the document) are sound; they can be applied to all these
> combinations to give unambiguous results. FWIW, my AI checking
> confirms the matrix results are consistent.
>
> Of course, there are more possible variations (e.g. diamond
> inheritance shapes), but IMO these 300 test cases give a much more
> solid starting point.
>
> ======
> [1] https://www.postgresql.org/message-id/CAJpy0uAoRpAoWHWBrGmkCXeEEeMa9R0GXPmKmCrrwLHvgmzOfQ%40mail.gma...
>
> Kind Regards,
> Peter Smith.
> Fujitsu Australia






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

* Re: Support EXCEPT for TABLES IN SCHEMA publications
@ 2026-09-27 14:28  Mihail Nikalayeu <mihailnikalayeu@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  0 siblings, 0 replies; 196+ messages in thread

From: Mihail Nikalayeu @ 2026-09-27 14:28 UTC (permalink / raw)
  To: shveta malik <shveta.malik@gmail.com>; +Cc: Nisha Moond <nisha.moond412@gmail.com>; Peter Smith <smithpb2250@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org

Hello!

On Thu, Jul 16, 2026, shveta malik wrote:
> Okay thanks. I am able to reproduce the crash on HEAD now. We can
> pursue this in separate thread.

For the archives: that separate thread is [1] and its entry [2].

[1]: https://www.postgresql.org/message-id/flat/CADzfLwWoFPT%2Ba73%3DA%3DbsNWRMZQ98NpBEMgE%3Dt1FS4O4_%3DQ...
[2]: https://commitfest.postgresql.org/patch/7351/

Best regards,
Mikhail.






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

1 further message in this thread omitted from this page (render size limit).
Use the per-message pages, or the t.mbox.gz byte stream, for the complete thread.


end of thread, other threads:[~2026-09-27 14:28 UTC | newest]

Thread overview: 196+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2026-04-14 06:30 Support EXCEPT for TABLES IN SCHEMA publications Nisha Moond <nisha.moond412@gmail.com>
2026-04-14 07:32 ` Peter Smith <smithpb2250@gmail.com>
2026-04-14 07:51   ` Amit Kapila <amit.kapila16@gmail.com>
2026-04-14 08:09     ` Peter Smith <smithpb2250@gmail.com>
2026-04-14 08:34   ` shveta malik <shveta.malik@gmail.com>
2026-04-14 09:36     ` Amit Kapila <amit.kapila16@gmail.com>
2026-04-15 02:05       ` Peter Smith <smithpb2250@gmail.com>
2026-04-16 10:54         ` Nisha Moond <nisha.moond412@gmail.com>
2026-04-24 04:46           ` shveta malik <shveta.malik@gmail.com>
2026-04-24 05:59             ` shveta malik <shveta.malik@gmail.com>
2026-04-27 03:32               ` Nisha Moond <nisha.moond412@gmail.com>
2026-04-27 03:36                 ` shveta malik <shveta.malik@gmail.com>
2026-04-27 09:02                   ` Nisha Moond <nisha.moond412@gmail.com>
2026-04-29 05:45                     ` Peter Smith <smithpb2250@gmail.com>
2026-05-04 12:05                       ` Nisha Moond <nisha.moond412@gmail.com>
2026-04-29 06:32                     ` Peter Smith <smithpb2250@gmail.com>
2026-05-04 12:05                       ` Nisha Moond <nisha.moond412@gmail.com>
2026-05-15 07:19                         ` Peter Smith <smithpb2250@gmail.com>
2026-05-15 13:32                           ` Nisha Moond <nisha.moond412@gmail.com>
2026-05-17 01:32                             ` Peter Smith <smithpb2250@gmail.com>
2026-05-19 11:14                           ` Nisha Moond <nisha.moond412@gmail.com>
2026-05-22 02:26                             ` Peter Smith <smithpb2250@gmail.com>
2026-05-28 11:26                               ` Nisha Moond <nisha.moond412@gmail.com>
2026-05-29 05:31                                 ` Peter Smith <smithpb2250@gmail.com>
2026-05-30 04:32                                   ` Nisha Moond <nisha.moond412@gmail.com>
2026-06-01 07:24                                     ` Peter Smith <smithpb2250@gmail.com>
2026-06-02 08:56                                       ` Nisha Moond <nisha.moond412@gmail.com>
2026-06-01 07:28                                     ` Peter Smith <smithpb2250@gmail.com>
2026-06-02 08:57                                       ` Nisha Moond <nisha.moond412@gmail.com>
2026-06-02 21:21                                         ` Zsolt Parragi <zsolt.parragi@percona.com>
2026-06-05 11:41                                           ` Nisha Moond <nisha.moond412@gmail.com>
2026-06-06 20:39                                             ` Zsolt Parragi <zsolt.parragi@percona.com>
2026-06-09 16:21                                               ` Nisha Moond <nisha.moond412@gmail.com>
2026-06-09 21:36                                                 ` Zsolt Parragi <zsolt.parragi@percona.com>
2026-06-10 09:03                                                   ` Nisha Moond <nisha.moond412@gmail.com>
2026-06-10 20:54                                                     ` Zsolt Parragi <zsolt.parragi@percona.com>
2026-06-15 06:08                                                       ` Amit Kapila <amit.kapila16@gmail.com>
2026-06-15 11:30                                                         ` Nisha Moond <nisha.moond412@gmail.com>
2026-06-10 04:36                                                 ` Peter Smith <smithpb2250@gmail.com>
2026-06-10 10:26                                                   ` Nisha Moond <nisha.moond412@gmail.com>
2026-06-11 06:47                                                     ` Peter Smith <smithpb2250@gmail.com>
2026-06-15 06:19                                                       ` Amit Kapila <amit.kapila16@gmail.com>
2026-06-15 11:30                                                         ` Nisha Moond <nisha.moond412@gmail.com>
2026-06-15 21:45                                                           ` Zsolt Parragi <zsolt.parragi@percona.com>
2026-06-16 01:21                                                           ` Peter Smith <smithpb2250@gmail.com>
2026-06-16 04:35                                                             ` Amit Kapila <amit.kapila16@gmail.com>
2026-06-16 06:36                                                               ` Peter Smith <smithpb2250@gmail.com>
2026-06-16 11:08                                                                 ` Amit Kapila <amit.kapila16@gmail.com>
2026-06-17 03:38                                                                   ` Peter Smith <smithpb2250@gmail.com>
2026-06-16 08:23                                                           ` Peter Smith <smithpb2250@gmail.com>
2026-06-16 10:44                                                             ` Nisha Moond <nisha.moond412@gmail.com>
2026-06-17 01:53                                                               ` Peter Smith <smithpb2250@gmail.com>
2026-06-18 06:35                                                                 ` Nisha Moond <nisha.moond412@gmail.com>
2026-06-22 02:16                                                                   ` Peter Smith <smithpb2250@gmail.com>
2026-06-22 12:49                                                                     ` Nisha Moond <nisha.moond412@gmail.com>
2026-06-22 23:40                                                                       ` Peter Smith <smithpb2250@gmail.com>
2026-06-30 10:16                                                                       ` shveta malik <shveta.malik@gmail.com>
2026-07-01 10:07                                                                         ` Nisha Moond <nisha.moond412@gmail.com>
2026-07-01 10:12                                                                           ` Nisha Moond <nisha.moond412@gmail.com>
2026-07-01 10:24                                                                             ` shveta malik <shveta.malik@gmail.com>
2026-07-02 09:03                                                                               ` Amit Kapila <amit.kapila16@gmail.com>
2026-07-03 16:45                                                                                 ` Nisha Moond <nisha.moond412@gmail.com>
2026-07-01 10:16                                                                           ` shveta malik <shveta.malik@gmail.com>
2026-07-02 04:51                                                                             ` Nisha Moond <nisha.moond412@gmail.com>
2026-07-02 08:49                                                                               ` shveta malik <shveta.malik@gmail.com>
2026-07-03 16:45                                                                                 ` Nisha Moond <nisha.moond412@gmail.com>
2026-07-06 03:11                                                                                   ` shveta malik <shveta.malik@gmail.com>
2026-07-06 07:55                                                                                   ` Peter Smith <smithpb2250@gmail.com>
2026-07-08 15:22                                                                                     ` Nisha Moond <nisha.moond412@gmail.com>
2026-07-06 23:01                                                                                   ` Peter Smith <smithpb2250@gmail.com>
2026-07-07 03:09                                                                                     ` shveta malik <shveta.malik@gmail.com>
2026-07-08 15:20                                                                                       ` Nisha Moond <nisha.moond412@gmail.com>
2026-07-09 09:23                                                                                         ` shveta malik <shveta.malik@gmail.com>
2026-07-10 11:37                                                                                           ` Nisha Moond <nisha.moond412@gmail.com>
2026-07-13 10:01                                                                                             ` shveta malik <shveta.malik@gmail.com>
2026-07-14 09:34                                                                                               ` shveta malik <shveta.malik@gmail.com>
2026-07-15 16:46                                                                                               ` Nisha Moond <nisha.moond412@gmail.com>
2026-07-16 04:45                                                                                                 ` shveta malik <shveta.malik@gmail.com>
2026-07-16 05:44                                                                                                   ` Nisha Moond <nisha.moond412@gmail.com>
2026-07-16 06:15                                                                                                     ` shveta malik <shveta.malik@gmail.com>
2026-09-27 14:28                                                                                                       ` Mihail Nikalayeu <mihailnikalayeu@gmail.com>
2026-07-16 08:34                                                                                                 ` Peter Smith <smithpb2250@gmail.com>
2026-07-16 10:32                                                                                                   ` shveta malik <shveta.malik@gmail.com>
2026-07-17 06:56                                                                                                     ` Peter Smith <smithpb2250@gmail.com>
2026-07-20 08:22                                                                                                   ` Nisha Moond <nisha.moond412@gmail.com>
2026-07-21 05:52                                                                                                     ` Peter Smith <smithpb2250@gmail.com>
2026-07-23 11:56                                                                                                       ` Nisha Moond <nisha.moond412@gmail.com>
2026-07-17 04:19                                                                                                 ` Peter Smith <smithpb2250@gmail.com>
2026-07-20 07:21                                                                                                   ` Nisha Moond <nisha.moond412@gmail.com>
2026-07-30 03:45                                                                                                   ` shveta malik <shveta.malik@gmail.com>
2026-07-30 04:23                                                                                                     ` Peter Smith <smithpb2250@gmail.com>
2026-07-17 08:07                                                                                                 ` Peter Smith <smithpb2250@gmail.com>
2026-07-20 02:20                                                                                                   ` Peter Smith <smithpb2250@gmail.com>
2026-07-20 08:22                                                                                                   ` Nisha Moond <nisha.moond412@gmail.com>
2026-07-20 10:17                                                                                                     ` shveta malik <shveta.malik@gmail.com>
2026-07-21 05:42                                                                                                       ` shveta malik <shveta.malik@gmail.com>
2026-07-23 11:56                                                                                                         ` Nisha Moond <nisha.moond412@gmail.com>
2026-07-23 11:55                                                                                                       ` Nisha Moond <nisha.moond412@gmail.com>
2026-07-24 06:24                                                                                                         ` Peter Smith <smithpb2250@gmail.com>
2026-07-30 06:03                                                                                                           ` Nisha Moond <nisha.moond412@gmail.com>
2026-07-28 08:48                                                                                                         ` shveta malik <shveta.malik@gmail.com>
2026-07-28 09:08                                                                                                           ` shveta malik <shveta.malik@gmail.com>
2026-07-30 06:03                                                                                                             ` Nisha Moond <nisha.moond412@gmail.com>
2026-07-30 06:19                                                                                                               ` Nisha Moond <nisha.moond412@gmail.com>
2026-07-31 06:10                                                                                                                 ` shveta malik <shveta.malik@gmail.com>
2026-08-04 08:41                                                                                                                   ` Nisha Moond <nisha.moond412@gmail.com>
2026-08-04 10:13                                                                                                                     ` shveta malik <shveta.malik@gmail.com>
2026-08-05 01:18                                                                                                                     ` Peter Smith <smithpb2250@gmail.com>
2026-08-05 09:00                                                                                                                       ` shveta malik <shveta.malik@gmail.com>
2026-08-06 04:55                                                                                                                         ` shveta malik <shveta.malik@gmail.com>
2026-08-11 08:57                                                                                                                         ` vignesh C <vignesh21@gmail.com>
2026-08-12 09:10                                                                                                                           ` shveta malik <shveta.malik@gmail.com>
2026-08-14 14:22                                                                                                                             ` vignesh C <vignesh21@gmail.com>
2026-08-17 04:02                                                                                                                               ` shveta malik <shveta.malik@gmail.com>
2026-08-17 07:06                                                                                                                                 ` vignesh C <vignesh21@gmail.com>
2026-08-13 07:22                                                                                                                           ` Peter Smith <smithpb2250@gmail.com>
2026-08-14 05:58                                                                                                                             ` shveta malik <shveta.malik@gmail.com>
2026-08-14 06:55                                                                                                                               ` Peter Smith <smithpb2250@gmail.com>
2026-08-14 10:22                                                                                                                                 ` shveta malik <shveta.malik@gmail.com>
2026-08-19 03:26                                                                                                                                 ` Nisha Moond <nisha.moond412@gmail.com>
2026-08-19 03:26                                                                                                                               ` Nisha Moond <nisha.moond412@gmail.com>
2026-08-07 11:56                                                                                                                     ` vignesh C <vignesh21@gmail.com>
2026-08-11 14:41                                                                                                                       ` vignesh C <vignesh21@gmail.com>
2026-08-12 04:01                                                                                                                         ` shveta malik <shveta.malik@gmail.com>
2026-08-12 06:11                                                                                                                           ` shveta malik <shveta.malik@gmail.com>
2026-08-13 09:41                                                                                                                             ` Amit Kapila <amit.kapila16@gmail.com>
2026-08-13 09:53                                                                                                                               ` shveta malik <shveta.malik@gmail.com>
2026-08-14 14:15                                                                                                                             ` vignesh C <vignesh21@gmail.com>
2026-08-18 03:58                                                                                                                               ` Peter Smith <smithpb2250@gmail.com>
2026-08-19 03:36                                                                                                                                 ` Nisha Moond <nisha.moond412@gmail.com>
2026-08-18 04:54                                                                                                                             ` vignesh C <vignesh21@gmail.com>
2026-08-18 08:04                                                                                                                               ` Peter Smith <smithpb2250@gmail.com>
2026-08-19 03:44                                                                                                                                 ` shveta malik <shveta.malik@gmail.com>
2026-08-19 10:17                                                                                                                                 ` vignesh C <vignesh21@gmail.com>
2026-08-19 22:47                                                                                                                                   ` Peter Smith <smithpb2250@gmail.com>
2026-08-19 23:35                                                                                                                                     ` Peter Smith <smithpb2250@gmail.com>
2026-08-20 09:03                                                                                                                                       ` shveta malik <shveta.malik@gmail.com>
2026-08-21 04:30                                                                                                                                         ` Peter Smith <smithpb2250@gmail.com>
2026-08-20 08:39                                                                                                                                   ` shveta malik <shveta.malik@gmail.com>
2026-08-21 04:54                                                                                                                                     ` shveta malik <shveta.malik@gmail.com>
2026-08-21 06:53                                                                                                                                       ` Peter Smith <smithpb2250@gmail.com>
2026-08-21 17:30                                                                                                                                         ` Nisha Moond <nisha.moond412@gmail.com>
2026-08-24 05:40                                                                                                                                           ` shveta malik <shveta.malik@gmail.com>
2026-08-24 06:27                                                                                                                                             ` shveta malik <shveta.malik@gmail.com>
2026-08-24 07:24                                                                                                                                             ` Peter Smith <smithpb2250@gmail.com>
2026-08-24 09:55                                                                                                                                               ` shveta malik <shveta.malik@gmail.com>
2026-08-24 11:38                                                                                                                                                 ` Nisha Moond <nisha.moond412@gmail.com>
2026-08-25 08:27                                                                                                                                                   ` shveta malik <shveta.malik@gmail.com>
2026-08-25 06:38                                                                                                                                                 ` Amit Kapila <amit.kapila16@gmail.com>
2026-08-25 10:06                                                                                                                                                   ` shveta malik <shveta.malik@gmail.com>
2026-08-25 07:35                                                                                                                                                 ` Peter Smith <smithpb2250@gmail.com>
2026-08-25 08:49                                                                                                                                                   ` shveta malik <shveta.malik@gmail.com>
2026-09-01 06:43                                                                                                                                                     ` Peter Smith <smithpb2250@gmail.com>
2026-09-02 11:19                                                                                                                                                       ` Nisha Moond <nisha.moond412@gmail.com>
2026-09-03 04:57                                                                                                                                                       ` shveta malik <shveta.malik@gmail.com>
2026-08-24 06:13                                                                                                                                           ` Peter Smith <smithpb2250@gmail.com>
2026-08-18 13:27                                                                                                                               ` vignesh C <vignesh21@gmail.com>
2026-08-07 14:21                                                                                                                     ` vignesh C <vignesh21@gmail.com>
2026-08-14 14:29                                                                                                                       ` vignesh C <vignesh21@gmail.com>
2026-07-31 07:47                                                                                                               ` Shlok Kyal <shlok.kyal.oss@gmail.com>
2026-08-04 08:41                                                                                                                 ` Nisha Moond <nisha.moond412@gmail.com>
2026-07-31 08:44                                                                                                               ` Peter Smith <smithpb2250@gmail.com>
2026-08-04 08:42                                                                                                                 ` Nisha Moond <nisha.moond412@gmail.com>
2026-07-30 06:04                                                                                                           ` Nisha Moond <nisha.moond412@gmail.com>
2026-07-07 09:01                                                                                   ` shveta malik <shveta.malik@gmail.com>
2026-07-07 10:43                                                                                     ` shveta malik <shveta.malik@gmail.com>
2026-07-08 06:28                                                                                       ` Amit Kapila <amit.kapila16@gmail.com>
2026-07-08 08:52                                                                                         ` shveta malik <shveta.malik@gmail.com>
2026-07-08 09:28                                                                                           ` shveta malik <shveta.malik@gmail.com>
2026-07-10 11:33                                                                                             ` Nisha Moond <nisha.moond412@gmail.com>
2026-07-15 04:48                                                                                               ` Peter Smith <smithpb2250@gmail.com>
2026-07-15 16:48                                                                                                 ` Nisha Moond <nisha.moond412@gmail.com>
2026-07-15 08:42                                                                                               ` Peter Smith <smithpb2250@gmail.com>
2026-07-15 16:48                                                                                                 ` Nisha Moond <nisha.moond412@gmail.com>
2026-07-08 15:22                                                                                         ` Nisha Moond <nisha.moond412@gmail.com>
2026-05-22 05:30                             ` Peter Smith <smithpb2250@gmail.com>
2026-05-28 11:28                               ` Nisha Moond <nisha.moond412@gmail.com>
2026-05-26 05:56                             ` Peter Smith <smithpb2250@gmail.com>
2026-05-28 11:28                               ` Nisha Moond <nisha.moond412@gmail.com>
2026-05-29 08:24                                 ` Peter Smith <smithpb2250@gmail.com>
2026-05-30 04:32                                   ` Nisha Moond <nisha.moond412@gmail.com>
2026-06-01 07:26                                     ` Peter Smith <smithpb2250@gmail.com>
2026-06-02 08:56                                       ` Nisha Moond <nisha.moond412@gmail.com>
2026-04-14 09:45   ` Nisha Moond <nisha.moond412@gmail.com>
2026-04-14 09:52     ` shveta malik <shveta.malik@gmail.com>
2026-04-15 08:52       ` Nisha Moond <nisha.moond412@gmail.com>
2026-04-15 10:15         ` shveta malik <shveta.malik@gmail.com>
2026-04-16 00:13           ` Peter Smith <smithpb2250@gmail.com>
2026-04-16 10:30             ` Nisha Moond <nisha.moond412@gmail.com>
2026-04-14 11:31 ` vignesh C <vignesh21@gmail.com>
2026-04-15 14:07   ` Nisha Moond <nisha.moond412@gmail.com>
2026-04-14 15:16 ` vignesh C <vignesh21@gmail.com>
2026-04-15 08:52   ` Nisha Moond <nisha.moond412@gmail.com>
2026-04-15 13:08     ` vignesh C <vignesh21@gmail.com>
2026-04-15 05:48 ` vignesh C <vignesh21@gmail.com>
2026-04-15 14:17   ` Nisha Moond <nisha.moond412@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