From a773b0ef3912ced47d22920cb63c7e92b136575d Mon Sep 17 00:00:00 2001 From: Nikhil Sontakke Date: Thu, 3 Dec 2026 18:20:33 +0530 Subject: [PATCH 2/2] Check that each replayed DDL command leaves the catalogs as the original did With execute_deparsed_ddl, a wrong deparse result was only noticed if it changed the regression test output. Most catalog properties are never printed, and most objects are dropped again before a test ends, so a lost CLUSTER ON or REPLICA IDENTITY, a different storage or sequence type, or a changed constraint went unnoticed. Fingerprint each relation the captured command created, altered or dropped, together with its inheritance children, at the end of the trial run: its kind, access method and options, its columns, constraints, indexes, inheritance, triggers, rules and owned sequences, as canonical text keyed by name. After the deparsed command has run, fingerprint the relations again and report any difference at the level given by the new test_ddl_deparse.check_catalog (warning by default, log, or off). 001_deparse_regress.pl sets it to log and fails if any relation other than a known one is reported. The only known one in the core tests is a CHECK expression on nulltest that ruleutils prints in a form that parses back to an equivalent but different tree. In the module's own tests, CREATE TABLE ... (LIKE ... INCLUDING IDENTITY) now reports that the replayed identity sequence is integer where the original's is bigint: core makes the copied sequence bigint, and the deparser doesn't emit the sequence type. --- .../expected/deparse_create_table.out | 5 + .../test_ddl_deparse/t/001_deparse_regress.pl | 22 ++ .../test_ddl_deparse/test_ddl_deparse.c | 296 +++++++++++++++++- 3 files changed, 322 insertions(+), 1 deletion(-) diff --git a/src/test/modules/test_ddl_deparse/expected/deparse_create_table.out b/src/test/modules/test_ddl_deparse/expected/deparse_create_table.out index ac365c9eda0..ee0b820aa99 100644 --- a/src/test/modules/test_ddl_deparse/expected/deparse_create_table.out +++ b/src/test/modules/test_ddl_deparse/expected/deparse_create_table.out @@ -198,6 +198,11 @@ NOTICE: deparsed DDL: CREATE TABLE deparse_tests.t_like_ident (a pg_catalog.int NOTICE: DDL test: type simple, tag CREATE SEQUENCE NOTICE: DDL test: type simple, tag CREATE TABLE NOTICE: DDL test: type simple, tag ALTER SEQUENCE +WARNING: test_ddl_deparse: deparsed DDL left relation deparse_tests.t_like_ident different from the original +DETAIL: original: ownedseq deparse_tests.t_like_ident_a_seq type=bigint start=10 increment=5 min=1 max=2147483647 cache=1 cycle=f +deparsed: ownedseq deparse_tests.t_like_ident_a_seq type=integer start=10 increment=5 min=1 max=2147483647 cache=1 cycle=f +HINT: Original DDL "CREATE TABLE deparse_tests.t_like_ident + (LIKE deparse_tests.t_like_idsrc INCLUDING IDENTITY);", deparsed DDL "CREATE TABLE deparse_tests.t_like_ident (a pg_catalog.int4 CONSTRAINT t_like_idsrc_a_not_null NOT NULL GENERATED BY DEFAULT AS IDENTITY (CACHE 1 NO CYCLE INCREMENT BY 5 MAXVALUE 2147483647 MINVALUE 1 START WITH 10))". -- LIKE options that copy a separate object are declined CREATE INDEX ON deparse_tests.t_like_src (a); NOTICE: DDL test: type simple, tag CREATE INDEX diff --git a/src/test/modules/test_ddl_deparse/t/001_deparse_regress.pl b/src/test/modules/test_ddl_deparse/t/001_deparse_regress.pl index 306898b6032..efe82a721f6 100644 --- a/src/test/modules/test_ddl_deparse/t/001_deparse_regress.pl +++ b/src/test/modules/test_ddl_deparse/t/001_deparse_regress.pl @@ -33,6 +33,7 @@ $node->append_conf('postgresql.conf', <start; @@ -120,6 +121,27 @@ else note("the deparser declined no command during this run"); } +# Each replayed command must leave the catalogs as the original did; see +# test_ddl_deparse.check_catalog. Known differences are listed here with the +# reason, keyed by relation. +my %known_mismatches = ( + # ruleutils prints the ANY array of the CHECK constraint so that it + # parses back to an equivalent but different expression tree. + 'public.nulltest' => 'CHECK expression does not round-trip exactly',); + +my @mismatches; +for my $line (split /\n/, slurp_file($node->logfile)) +{ + next + unless $line =~ + /test_ddl_deparse: deparsed DDL left relation (\S+) different from the original/; + push @mismatches, $1 unless exists $known_mismatches{$1}; +} +is(scalar(@mismatches), 0, + 'replayed commands leave the catalogs as the originals did') + or diag("relations left different (see the server log for details):\n " + . join("\n ", @mismatches)); + # Report results is($rc, 0, 'regression tests pass'); diff --git a/src/test/modules/test_ddl_deparse/test_ddl_deparse.c b/src/test/modules/test_ddl_deparse/test_ddl_deparse.c index 57727f8d3b6..60b0fec6180 100644 --- a/src/test/modules/test_ddl_deparse/test_ddl_deparse.c +++ b/src/test/modules/test_ddl_deparse/test_ddl_deparse.c @@ -11,6 +11,12 @@ #include "postgres.h" #include "access/xact.h" +#include "catalog/index.h" +#include "catalog/namespace.h" +#include "catalog/pg_class.h" +#include "catalog/pg_inherits.h" +#include "catalog/pg_type.h" +#include "executor/spi.h" #include "commands/ddl_deparse.h" #include "commands/event_trigger.h" #include "funcapi.h" @@ -20,7 +26,9 @@ #include "tcop/utility.h" #include "utils/builtins.h" #include "utils/guc.h" +#include "utils/lsyscache.h" #include "utils/memutils.h" +#include "utils/regproc.h" #include "utils/resowner.h" #include "utils/tuplestore.h" @@ -53,8 +61,16 @@ static const struct config_enum_entry print_deparsed_ddl_options[] = { {NULL, 0, false} }; +static const struct config_enum_entry check_catalog_options[] = { + {"off", -1, false}, + {"warning", WARNING, false}, + {"log", LOG, false}, + {NULL, 0, false} +}; + /* GUCs */ static bool execute_deparsed_ddl = false; +static int check_catalog = WARNING; static int print_deparsed_ddl = PRINT_DEPARSED_OFF; static bool log_declined_commands = false; @@ -85,6 +101,16 @@ static int capture_depth = 0; /* Are we re-executing a deparsed command ourselves? */ static bool in_roundtrip = false; +/* + * Catalog fingerprints of the relations the captured statement affected, as + * they were at the end of the trial run, keyed by qualified name since the + * replay creates objects with different OIDs. In TopTransactionContext, like + * captured_json. The replay must leave each relation with the same + * fingerprint; see check_fingerprints(). + */ +static List *fp_names = NIL; +static List *fp_texts = NIL; + static void test_ddl_deparse_utility_command(PlannedStmt *pstmt, const char *queryString, bool readOnlyTree, @@ -119,6 +145,16 @@ _PG_init(void) 0, NULL, NULL, NULL); + DefineCustomEnumVariable("test_ddl_deparse.check_catalog", + "Compare the catalog state left by each deparsed DDL command with the original's, reporting differences at this level.", + NULL, + &check_catalog, + WARNING, + check_catalog_options, + PGC_USERSET, + 0, + NULL, NULL, NULL); + DefineCustomBoolVariable("test_ddl_deparse.log_declined_commands", "Log DDL commands the deparser declined to reproduce.", NULL, @@ -134,6 +170,253 @@ _PG_init(void) ProcessUtility_hook = test_ddl_deparse_utility_command; } +/* + * Everything about a relation that DDL can change and the catalogs record, + * as canonical text. Names rather than OIDs are used throughout, since the + * original and the replay create objects with different OIDs. Internal + * triggers are left out, as their names contain OIDs. + */ +static const char *fingerprint_query = +"SELECT pg_catalog.concat_ws(E'\\n'," +" (SELECT pg_catalog.format('rel kind=%s am=%s persistence=%s replident=%s" +" rls=%s/%s owner=%s options=%s partkey=%s bound=%s oftype=%s'," +" c.relkind, am.amname, c.relpersistence, c.relreplident," +" c.relrowsecurity, c.relforcerowsecurity," +" pg_catalog.pg_get_userbyid(c.relowner), c.reloptions," +" pg_catalog.pg_get_partkeydef(c.oid)," +" pg_catalog.pg_get_expr(c.relpartbound, c.oid)," +" c.reloftype::pg_catalog.regtype)" +" FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_am am ON am.oid = c.relam" +" WHERE c.oid = $1)," +" (SELECT pg_catalog.string_agg(pg_catalog.format('att %s type=%s notnull=%s" +" storage=%s compression=%s collation=%s generated=%s identity=%s" +" default=%s stattarget=%s options=%s local=%s inhcount=%s'," +" a.attname, pg_catalog.format_type(a.atttypid, a.atttypmod)," +" a.attnotnull, a.attstorage, a.attcompression, co.collname," +" a.attgenerated, a.attidentity, pg_catalog.pg_get_expr(d.adbin, d.adrelid)," +" a.attstattarget, a.attoptions, a.attislocal, a.attinhcount)," +" E'\\n' ORDER BY a.attnum)" +" FROM pg_catalog.pg_attribute a" +" LEFT JOIN pg_catalog.pg_attrdef d" +" ON d.adrelid = a.attrelid AND d.adnum = a.attnum" +" LEFT JOIN pg_catalog.pg_collation co ON co.oid = a.attcollation" +" WHERE a.attrelid = $1 AND a.attnum > 0 AND NOT a.attisdropped)," +" (SELECT pg_catalog.string_agg(t.l, E'\\n' ORDER BY t.l) FROM" +" (SELECT pg_catalog.format('con %s type=%s def=%s local=%s inhcount=%s" +" noinherit=%s', conname, contype," +" pg_catalog.pg_get_constraintdef(oid), conislocal, coninhcount," +" connoinherit) AS l" +" FROM pg_catalog.pg_constraint WHERE conrelid = $1) t)," +" (SELECT pg_catalog.string_agg(t.l, E'\\n' ORDER BY t.l) FROM" +" (SELECT pg_catalog.format('idx %s clustered=%s replident=%s valid=%s'," +" pg_catalog.pg_get_indexdef(indexrelid), indisclustered," +" indisreplident, indisvalid) AS l" +" FROM pg_catalog.pg_index WHERE indrelid = $1) t)," +" (SELECT pg_catalog.string_agg(pg_catalog.format('inh %s'," +" inhparent::pg_catalog.regclass), E'\\n' ORDER BY inhseqno)" +" FROM pg_catalog.pg_inherits WHERE inhrelid = $1)," +" (SELECT pg_catalog.string_agg(pg_catalog.format('trigger %s enabled=%s'," +" tgname, tgenabled), E'\\n' ORDER BY tgname)" +" FROM pg_catalog.pg_trigger WHERE tgrelid = $1 AND NOT tgisinternal)," +" (SELECT pg_catalog.string_agg(pg_catalog.format('rule %s enabled=%s'," +" rulename, ev_enabled), E'\\n' ORDER BY rulename)" +" FROM pg_catalog.pg_rewrite WHERE ev_class = $1 AND rulename <> '_RETURN')," +" (SELECT pg_catalog.string_agg(pg_catalog.format('ownedseq %s type=%s" +" start=%s increment=%s min=%s max=%s cache=%s cycle=%s'," +" s.seqrelid::pg_catalog.regclass, s.seqtypid::pg_catalog.regtype," +" s.seqstart, s.seqincrement, s.seqmin, s.seqmax, s.seqcache, s.seqcycle)," +" E'\\n' ORDER BY s.seqrelid::pg_catalog.regclass::pg_catalog.text)" +" FROM pg_catalog.pg_depend dep" +" JOIN pg_catalog.pg_sequence s ON s.seqrelid = dep.objid" +" WHERE dep.classid = 'pg_catalog.pg_class'::pg_catalog.regclass" +" AND dep.refclassid = 'pg_catalog.pg_class'::pg_catalog.regclass" +" AND dep.refobjid = $1 AND dep.deptype IN ('a', 'i')))"; + +/* + * Return the fingerprint of a relation, or "(absent)" for InvalidOid, in + * the current memory context. Runs under a restricted search_path, so that + * the names in it don't depend on the session's. + */ +static char * +relation_fingerprint(Oid relid) +{ + MemoryContext oldcxt = CurrentMemoryContext; + Datum arg = ObjectIdGetDatum(relid); + Oid argtype = OIDOID; + bool isnull; + Datum d; + char *result; + int save_nestlevel; + + if (!OidIsValid(relid)) + return pstrdup("(absent)"); + + save_nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); + + if (SPI_connect() != SPI_OK_CONNECT) + elog(ERROR, "SPI_connect failed"); + + /* + * Not read-only: that would reuse the statement's snapshot, which was + * taken before the command ran and so doesn't see its effects. + */ + if (SPI_execute_with_args(fingerprint_query, 1, &argtype, &arg, NULL, + false, 1) != SPI_OK_SELECT || + SPI_processed != 1) + elog(ERROR, "could not fingerprint relation %u", relid); + d = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, + &isnull); + MemoryContextSwitchTo(oldcxt); + result = isnull ? pstrdup("(absent)") : TextDatumGetCString(d); + SPI_finish(); + + AtEOXact_GUC(true, save_nestlevel); + return result; +} + +/* Add a relation, and for a table its inheritance children, to a list */ +static List * +add_affected_relation(List *relids, Oid relid) +{ + char relkind = get_rel_relkind(relid); + + if (relkind == '\0') + return relids; /* gone */ + + /* An index stands for its table */ + if (relkind == RELKIND_INDEX || relkind == RELKIND_PARTITIONED_INDEX) + { + relid = IndexGetRelation(relid, true); + if (!OidIsValid(relid)) + return relids; + relkind = get_rel_relkind(relid); + } + + if (relkind == RELKIND_RELATION || relkind == RELKIND_PARTITIONED_TABLE || + relkind == RELKIND_FOREIGN_TABLE) + return list_concat_unique_oid(relids, + find_all_inheritors(relid, NoLock, NULL)); + + return list_append_unique_oid(relids, relid); +} + +/* + * Record the fingerprints of the relations the captured statement created, + * altered or dropped, as the trial run left them. + */ +static void +record_fingerprints(List *cmds, List *dropped) +{ + List *relids = NIL; + ListCell *lc; + MemoryContext oldcxt; + + foreach(lc, cmds) + { + CollectedCommand *cmd = lfirst(lc); + + if (cmd->type == SCT_Simple) + { + if (cmd->d.simple.address.classId == RelationRelationId) + relids = add_affected_relation(relids, + cmd->d.simple.address.objectId); + if (cmd->d.simple.secondaryObject.classId == RelationRelationId) + relids = add_affected_relation(relids, + cmd->d.simple.secondaryObject.objectId); + } + else if (cmd->type == SCT_AlterTable && + cmd->d.alterTable.classId == RelationRelationId) + { + ListCell *lc2; + + relids = add_affected_relation(relids, cmd->d.alterTable.objectId); + foreach(lc2, cmd->d.alterTable.subcmds) + { + CollectedATSubcmd *sub = lfirst(lc2); + + if (sub->address.classId == RelationRelationId) + relids = add_affected_relation(relids, + sub->address.objectId); + } + } + } + + oldcxt = MemoryContextSwitchTo(TopTransactionContext); + fp_names = NIL; + fp_texts = NIL; + + foreach_oid(relid, relids) + { + fp_names = lappend(fp_names, + quote_qualified_identifier(get_namespace_name(get_rel_namespace(relid)), + get_rel_name(relid))); + fp_texts = lappend(fp_texts, relation_fingerprint(relid)); + } + + /* A dropped relation must be gone after the replay too */ + foreach(lc, dropped) + { + SQLDropObject *obj = lfirst(lc); + + if (obj->address.classId == RelationRelationId && + obj->address.objectSubId == 0 && obj->original) + { + fp_names = lappend(fp_names, + quote_qualified_identifier(obj->schemaname, + obj->objname)); + fp_texts = lappend(fp_texts, pstrdup("(absent)")); + } + } + MemoryContextSwitchTo(oldcxt); +} + +/* + * After the replay, each relation recorded by record_fingerprints() must have + * the same fingerprint. Report the first differing line of each that doesn't. + */ +static void +check_fingerprints(const char *orig_ddl, const char *deparsed_ddl) +{ + ListCell *ln, + *lt; + + forboth(ln, fp_names, lt, fp_texts) + { + const char *name = lfirst(ln); + const char *orig = lfirst(lt); + RangeVar *rv; + Oid relid; + char *now; + + rv = makeRangeVarFromNameList(stringToQualifiedNameList(name, NULL)); + relid = RangeVarGetRelid(rv, NoLock, true); + now = relation_fingerprint(relid); + + if (strcmp(orig, now) != 0) + { + const char *o = orig, + *n = now; + + /* find the first differing line */ + while (*o && *o == *n) + o++, n++; + while (o > orig && o[-1] != '\n') + o--, n--; + + ereport(check_catalog, + (errmsg("test_ddl_deparse: deparsed DDL left relation %s different from the original", name), + errdetail("original: %.*s\ndeparsed: %.*s", + (int) strcspn(o, "\n"), o, + (int) strcspn(n, "\n"), n), + errhint("Original DDL \"%s\", deparsed DDL \"%s\".", + orig_ddl, deparsed_ddl), + errhidestmt(true), + errhidecontext(true))); + } + } +} + /* * ddl_command_end event trigger: deparse the statement being captured and keep * the result for replay. The result is copied into TopTransactionContext, @@ -185,6 +468,11 @@ capture_deparsed_ddl(PG_FUNCTION_ARGS) captured_json = MemoryContextStrdup(TopTransactionContext, json); + /* Remember what the original did, to compare with the replay */ + if (execute_deparsed_ddl && check_catalog >= 0) + record_fingerprints(EventTriggerGetCollectedCommands(), + EventTriggerGetDroppedObjects()); + PG_RETURN_NULL(); } @@ -364,6 +652,8 @@ test_ddl_deparse_utility_command(PlannedStmt *pstmt, } captured_json = NULL; + fp_names = NIL; + fp_texts = NIL; capturing = true; capture_depth = utility_depth + 1; @@ -462,14 +752,18 @@ test_ddl_deparse_utility_command(PlannedStmt *pstmt, PG_END_TRY(2); error_context_stack = errcallback.previous; + + check_fingerprints(queryString, sql); } } } PG_FINALLY(); { capturing = false; - /* don't leave a dangling pointer into transaction-lifetime memory */ + /* don't leave dangling pointers into transaction-lifetime memory */ captured_json = NULL; + fp_names = NIL; + fp_texts = NIL; } PG_END_TRY(); }