pg.ddx.io  pgsql-hackers@postgresql.org mailing list archive  
help / color / mirror / Atom feed
pg_get_*_ddl() needs a redesign
32+ messages / 10 participants
[nested] [flat]

Commits from this thread:
  2026-09-14 4664929e5a  Fix Makefile build
  2026-09-13 db169985c1  Revert pg_get_role_ddl(), pg_get_tablespace_ddl(), and pg_get_database_ddl().
* pg_get_*_ddl() needs a redesign
@ 2026-08-27 01:52 Noah Misch <noah@leadboat.com>
  2026-09-09 15:47 ` Re: pg_get_*_ddl() needs a redesign Melanie Plageman <melanieplageman@gmail.com>
  0 siblings, 1 reply; 32+ messages in thread

From: Noah Misch @ 2026-08-27 01:52 UTC (permalink / raw)
  To: andrew@dunslane.net; gonzalemario@gmail.com; dbryan.green@gmail.com; euler@eulerto.com; +Cc: pgsql-hackers

commit 76e514e wrote:
> Author:     Andrew Dunstan <>
> AuthorDate: Thu Mar 19 09:52:25 2026 -0400
> Commit:     Andrew Dunstan <andrew@dunslane.net>
> CommitDate: Sun Apr 5 10:54:54 2026 -0400
> 
>     Add pg_get_role_ddl() function

I reviewed this commit.

>     Author: Mario Gonzalez <gonzalemario@gmail.com>
>     Author: Bryan Green <dbryan.green@gmail.com>
>     Co-authored-by: Andrew Dunstan <andrew@dunslane.net>
>     Co-authored-by: Euler Taveira <euler@eulerto.com>
>     Reviewed-by: Japin Li <japinli@hotmail.com>
>     Reviewed-by: Quan Zongliang <quanzongliang@yeah.net>
>     Reviewed-by: jian he <jian.universality@gmail.com>
>     Discussion: https://postgr.es/m/4c5f895e-3281-48f8-b943-9228b7da6471@gmail.com
>     Discussion: https://postgr.es/m/e247c261-e3fb-4810-81e0-a65893170e94@dunslane.net

> +	/*
> +	 * We intentionally omit PASSWORD.  There's no way to retrieve the
> +	 * original password text from the stored hash, and even if we could,
> +	 * exposing passwords through a SQL function would be a security issue.
> +	 * Users must set passwords separately after recreating roles.
> +	 */

pg_dumpall recreates password hashes without needing the original plaintext.
The first thread message said the use case is "dumping role definitions for
migration or backup purposes without needing pg_dumpall."  Users expect their
passwords to be accepted after migration or restore from backup.

I also don't see a security distinction arising merely because SQL is the
conduit.

> + * pg_get_role_ddl_internal
> + *		Generate DDL statements to recreate a role

> +			/* Build a fresh ALTER ROLE statement for this setting */
> +			resetStringInfo(&buf);
> +			appendStringInfo(&buf, "ALTER ROLE %s", quote_identifier(rolname));
> +
> +			if (datname != NULL)
> +				appendStringInfo(&buf, " IN DATABASE %s",
> +								 quote_identifier(datname));

This doesn't deal with dependencies.  To migrate, you need to dump roles
first, then databases (potentially owned by roles), then IN DATABASE ... SET
statements (which depend on both).  By putting IN DATABASE in the same payload
as CREATE ROLE, it's not conducive to restoring from an empty cluster.  The
caller would need to break apart the payload and do its own dependency
analysis, which substantially defeats the point of having $SUBJECT.

The word "depend" appears nowhere on the threads or in this commit.  For a
feature aiming for an outcome like pg_dump, I think dependency handling needs
to be foundational in the design.

> +	/*
> +	 * Scan pg_auth_members for role memberships.  We look for rows where
> +	 * member = roleid, meaning this role has been granted membership in other
> +	 * roles.

The corresponding step in pg_dumpall is much more complicated; see this
comment in dumpRoleMembership():

	/*
	 * We can't dump these GRANT commands in arbitrary order, because a role
	 * that is named as a grantor must already have ADMIN OPTION on the role
	 * for which it is granting permissions, except for the bootstrap
	 * superuser, who can always be named as the grantor.
	 *
	 * We handle this by considering these grants role by role. For each role,
	 * we initially consider the only allowable grantor to be the bootstrap
	 * superuser. Every time we grant ADMIN OPTION on the role to some user,
	 * that user also becomes an allowable grantor. We make repeated passes
	 * over the grants for the role, each time dumping those whose grantors
	 * are allowable and which we haven't done yet. Eventually this should let
	 * us dump all the grants.
	 */

If the backend version achieves the right outcomes without that complexity, it
should have a comment about how it achieves that.


>  src/backend/utils/adt/ddlutils.c       | 361 +++++++++++++++++++++++++++++++++

Separate from the above correctness problems, I object to having two
independent implementations in the tree for translating catalog state into SQL
that recreates that state.  pg_dump support is already a key friction source
for implementing most new catalog-stored features.  I don't want such features
to face updating both a src/bin/pg_dump implementation and an independent
backend implementation, each with its own bugs.

Wrapping pg_dump and pg_dumpall is already a reasonable implementation of
these use cases, so I think the bar for introducing another implementation is
high.  A shared implementation used by both could potentially clear that bar;
this commit doesn't start in that direction.  PostgreSQL should not carry two
independent implementations of this logic.


I also ran an Opus 4.8 review.  It found some minor issues that aren't worth
addressing before the above.  I'm attaching it for completeness.

Attachments:

ddlutils-defect-tests-v0.patch (text/plain, 18.9K) download commit 9ba82a3 (HEAD -> ddlutils-defect-tests) Author: Noah Misch <nm@cqla.c.codeql-202606a.internal> AuthorDate: Sat Jul 11 16:30:54 2026 +0000 Commit: Noah Misch <nm@cqla.c.codeql-202606a.internal> CommitDate: Sat Jul 11 18:22:19 2026 +0000 Add TAP test documenting known pg_get_*_ddl defects The new test test_misc/t/015_ddlutils_defects.pl demonstrates two confirmed, still-unfixed defects in the DDL generation functions. Each defect is asserted as its correct expected behavior inside a TODO block, so the assertions currently fail as TAP expected failures and the suite stays green; once a defect is fixed, the corresponding assertion passes and the TODO wrapper should be removed. 1. pg_get_database_ddl() omits the TABLESPACE clause for a database in a user tablespace named "PG_DEFAULT". The clause is suppressed with pg_strcasecmp(spcname, "pg_default"), but tablespace names are case-sensitive and the reserved-name check only rejects lowercase "pg_" prefixes, so such a tablespace is legal and distinct from the built-in pg_default. Expected: the emitted CREATE DATABASE carries TABLESPACE = "PG_DEFAULT" (pg_dump compares with case-sensitive strcmp() and emits it). Actual: no TABLESPACE clause; replaying the output succeeds but silently places the database in the built-in pg_default tablespace -- a lossy round trip. 2. Misleading permission-denied errors. pg_get_role_ddl() requires SELECT on pg_authid and pg_get_tablespace_ddl() requires SELECT on pg_tablespace, but on failure they report "permission denied for role <target>" (even for the caller's own role, which any unprivileged user hits on a stock install) and "permission denied for tablespace <target>". Expected: an error naming the catalog whose SELECT privilege is missing, as a direct SELECT from that catalog reports. Actual: only the irrelevant target object is named, with nothing pointing at the real remedy. The test is registered in the test_misc meson.build test list; the Makefile picks it up automatically via TAP_TESTS. The hunt confirmed three further user-visible defects that are not encoded in the test because they are documentation gaps (the function behavior is intentional, but doc/src/sgml/func/func-info.sgml does not describe it): the reference omits the functions' privilege requirements, omits that they refuse reserved/system targets (pg_default/pg_global, pg_-prefixed roles, template0/template1), and omits ALLOW_CONNECTIONS from pg_get_database_ddl()'s list of emitted ALTER DATABASE statements. These are written up, with reproductions, in the companion 015_ddlutils_defects_uncovered.md. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Bhit3mWtVg5qYPW8F78h5J --- src/test/modules/test_misc/meson.build | 1 + .../modules/test_misc/t/015_ddlutils_defects.pl | 186 +++++++++++++++++++++ .../test_misc/t/015_ddlutils_defects_uncovered.md | 171 +++++++++++++++++++ 3 files changed, 358 insertions(+) diff --git a/src/test/modules/test_misc/meson.build b/src/test/modules/test_misc/meson.build index ee29069..3348350 100644 --- a/src/test/modules/test_misc/meson.build +++ b/src/test/modules/test_misc/meson.build @@ -23,6 +23,7 @@ tests += { 't/012_ddlutils.pl', 't/013_temp_obj_multisession.pl', 't/014_log_statement_max_length.pl', + 't/015_ddlutils_defects.pl', ], # The injection points are cluster-wide, so disable installcheck 'runningcheck': false, diff --git a/src/test/modules/test_misc/t/015_ddlutils_defects.pl b/src/test/modules/test_misc/t/015_ddlutils_defects.pl new file mode 100644 index 0000000..f96a79d --- /dev/null +++ b/src/test/modules/test_misc/t/015_ddlutils_defects.pl @@ -0,0 +1,186 @@ + +# Copyright (c) 2026, PostgreSQL Global Development Group + +# Tests demonstrating known, still-unfixed defects in the DDL generation +# functions pg_get_database_ddl(), pg_get_role_ddl(), and +# pg_get_tablespace_ddl(). Companion to 012_ddlutils.pl, which covers the +# intended behavior of these functions. +# +# Each defect is encoded by asserting the CORRECT (expected) behavior and +# wrapping that assertion in a TODO block, so that: +# - while the defect exists, the assertion fails but is reported as an +# expected failure ("not ok ... # TODO"), keeping the suite green; +# - once the defect is fixed, the assertion passes, at which point the +# TODO wrapper should be removed. +# Assertions outside the TODO blocks hold both before and after a fix. + +use strict; +use warnings FATAL => 'all'; +use PostgreSQL::Test::Cluster; +use PostgreSQL::Test::Utils; +use Test::More; + +# Package variable consulted by Test::More inside the TODO blocks below. +our $TODO; + +my $node = PostgreSQL::Test::Cluster->new('main'); +$node->init; +# Force UTC so that any timestamptz values render the same way regardless +# of the host's local timezone. +$node->append_conf('postgresql.conf', "timezone = 'UTC'\n"); +$node->start; + + +######################################################################## +# Defect 1: pg_get_database_ddl() omits the TABLESPACE clause for a +# database whose tablespace is a user tablespace named "PG_DEFAULT" +# (a silently lossy round trip). +# +# pg_get_database_ddl_internal() decides whether to emit the TABLESPACE +# clause with pg_strcasecmp(spcname, "pg_default"). But tablespace names +# are case-sensitive identifiers, and the reserved-name check only rejects +# lowercase "pg_"-prefixed names, so CREATE TABLESPACE "PG_DEFAULT" is +# perfectly legal and is a distinct tablespace from the built-in +# pg_default. pg_dump makes the same "is it the default?" decision with a +# case-sensitive strcmp() and therefore emits TABLESPACE "PG_DEFAULT" +# correctly. +# +# Expected: the emitted CREATE DATABASE carries TABLESPACE = "PG_DEFAULT", +# and replaying the DDL recreates the database in that tablespace. +# Actual (currently broken): no TABLESPACE clause is emitted; the replay +# succeeds without error but silently places the database in the built-in +# pg_default tablespace instead. +######################################################################## + +# The reserved-name check is case-sensitive, so this name is allowed. +# (It intentionally lacks the regress_ prefix: the defect requires the +# exact spelling "PG_DEFAULT".) +$node->safe_psql( + 'postgres', q{ + SET allow_in_place_tablespaces = true; + CREATE TABLESPACE "PG_DEFAULT" LOCATION ''}); +$node->safe_psql( + 'postgres', q{ + CREATE DATABASE regress_getddl_pgdef + TABLESPACE "PG_DEFAULT" TEMPLATE template0}); + +# owner => false keeps the output free of the (installation-dependent) +# bootstrap superuser name, so the DDL can be replayed verbatim below. +my $ddl = $node->safe_psql( + 'postgres', + q{SELECT * FROM pg_get_database_ddl('regress_getddl_pgdef', + owner => false)}); +like( + $ddl, + qr/CREATE DATABASE regress_getddl_pgdef/, + 'database DDL for tablespace "PG_DEFAULT" includes CREATE DATABASE'); + +{ + local $TODO = 'pg_get_database_ddl: TABLESPACE clause suppressed by ' + . 'case-insensitive comparison against pg_default'; + + like( + $ddl, + qr/TABLESPACE = "PG_DEFAULT"/, + 'database DDL includes TABLESPACE = "PG_DEFAULT"'); +} + +# Round trip: drop the database and replay the captured DDL. The replay +# itself succeeds both before and after a fix; only the resulting +# database's tablespace differs. +$node->safe_psql('postgres', 'DROP DATABASE regress_getddl_pgdef'); +$node->safe_psql('postgres', $ddl); +my $spc = $node->safe_psql( + 'postgres', q{ + SELECT t.spcname + FROM pg_database d JOIN pg_tablespace t ON t.oid = d.dattablespace + WHERE d.datname = 'regress_getddl_pgdef'}); + +{ + local $TODO = 'pg_get_database_ddl: replayed DDL silently lands the ' + . 'database in pg_default instead of "PG_DEFAULT"'; + + is($spc, 'PG_DEFAULT', + 'replayed database DDL preserves tablespace "PG_DEFAULT"'); +} + +$node->safe_psql('postgres', 'DROP DATABASE regress_getddl_pgdef'); +$node->safe_psql('postgres', 'DROP TABLESPACE "PG_DEFAULT"'); + + +######################################################################## +# Defect 2: misleading "permission denied" errors when the caller lacks +# SELECT on the system catalog that the function actually reads. +# +# pg_get_role_ddl() requires SELECT on pg_authid, and +# pg_get_tablespace_ddl() requires SELECT on pg_tablespace. When that +# check fails, however, the error names the *target* object ("permission +# denied for role ...", "permission denied for tablespace ..."), which by +# PostgreSQL convention means the caller lacks a privilege on that named +# object. Nothing points at the actual remedy (GRANT SELECT ON pg_authid +# / pg_tablespace); the role message even blames the caller's own role +# when it introspects itself. (pg_get_database_ddl() is not affected: it +# genuinely checks CONNECT on the named database.) +# +# Expected: the error identifies the catalog whose SELECT privilege is +# missing -- e.g. "permission denied for table pg_authid", exactly as a +# direct SELECT FROM pg_authid reports. +# Actual (currently broken): "permission denied for role <target>" / +# "permission denied for tablespace <target>", naming neither catalog. +######################################################################## + +$node->safe_psql( + 'postgres', q{ + CREATE ROLE regress_getddl_unpriv LOGIN; + SET allow_in_place_tablespaces = true; + CREATE TABLESPACE regress_getddl_ts LOCATION ''; + REVOKE SELECT ON pg_tablespace FROM PUBLIC}); + +# pg_authid is never PUBLIC-readable, so on a stock install any +# unprivileged role hits this even when introspecting its own role. +my ($ret, $stdout, $stderr) = $node->psql( + 'postgres', q{ + SET ROLE regress_getddl_unpriv; + SELECT * FROM pg_get_role_ddl(current_user::regrole)}); +isnt($ret, 0, 'role DDL denied without SELECT on pg_authid'); +like( + $stderr, + qr/permission denied/, + 'role DDL permission failure reports "permission denied"'); + +{ + local $TODO = 'pg_get_role_ddl: error blames the target role instead ' + . 'of naming the missing SELECT privilege on pg_authid'; + + like( + $stderr, + qr/pg_authid/, + 'role DDL permission error identifies pg_authid'); +} + +($ret, $stdout, $stderr) = $node->psql( + 'postgres', q{ + SET ROLE regress_getddl_unpriv; + SELECT * FROM pg_get_tablespace_ddl('regress_getddl_ts')}); +isnt($ret, 0, 'tablespace DDL denied without SELECT on pg_tablespace'); +like( + $stderr, + qr/permission denied/, + 'tablespace DDL permission failure reports "permission denied"'); + +{ + local $TODO = 'pg_get_tablespace_ddl: error blames the target ' + . 'tablespace instead of naming the missing SELECT privilege on ' + . 'pg_tablespace'; + + like( + $stderr, + qr/pg_tablespace/, + 'tablespace DDL permission error identifies pg_tablespace'); +} + +$node->safe_psql('postgres', 'GRANT SELECT ON pg_tablespace TO PUBLIC'); + +$node->stop; + +done_testing(); diff --git a/src/test/modules/test_misc/t/015_ddlutils_defects_uncovered.md b/src/test/modules/test_misc/t/015_ddlutils_defects_uncovered.md new file mode 100644 index 0000000..7ff06c6 --- /dev/null +++ b/src/test/modules/test_misc/t/015_ddlutils_defects_uncovered.md @@ -0,0 +1,171 @@ +# pg_get_*_ddl defects not covered by 015_ddlutils_defects.pl + +A defect hunt over the `pg_get_role_ddl()`, `pg_get_tablespace_ddl()`, and +`pg_get_database_ddl()` feature (commits `76e514ebb4`, `b99fd9fd7f`, +`a4f774cf1c`) on `master` (`5f14f82`) confirmed five still-present, +user-visible defects. The companion TAP test +[`015_ddlutils_defects.pl`](015_ddlutils_defects.pl) encodes the two that +are defects in *function behavior*: + +1. `pg_get_database_ddl()` emits a lossy round trip for a database in a + user tablespace named `"PG_DEFAULT"` (a `TABLESPACE` clause is dropped). +2. The role/tablespace permission errors name the target object instead of + the catalog whose `SELECT` privilege is actually missing. + +The remaining **three** confirmed defects are **documentation** gaps: the +function behavior is intentional, but the SGML reference +(`doc/src/sgml/func/func-info.sgml`, the *Get Object DDL Functions* table) +does not describe it, so a user relying on the documented contract is +surprised. They are not encoded in the TAP test because a meaningful check +would assert on the rendered documentation, not on the functions' behavior; +they are recorded here instead. All three were reproduced from scratch on a +fresh `master` cluster. + +Unless noted, the reproductions assume a superuser `psql` session and, for +the in-place tablespace, `SET allow_in_place_tablespaces = on;`. + +--- + +## D1. Docs omit the privilege requirements of all three functions + +**Category:** doc_mismatch · **Severity:** low (documentation only) + +Each function is privilege-gated in code, but the documentation states no +privilege requirement at all: + +| Function | Required privilege | Enforced at | +| --- | --- | --- | +| `pg_get_role_ddl` | `SELECT` on `pg_authid` | `ddlutils.c:172` | +| `pg_get_tablespace_ddl` | `SELECT` on `pg_tablespace` | `ddlutils.c:502` | +| `pg_get_database_ddl` | `CONNECT` on the target database | `ddlutils.c:680` | + +The `pg_get_role_ddl` case is the sharpest: `pg_authid` is never +PUBLIC-readable, so on a stock install **any** non-superuser hits an +undocumented `permission denied` error — even when introspecting its own +role — although everything the function emits is otherwise visible through +`pg_roles` / `pg_db_role_setting` / `pg_auth_members` (the password is +omitted by design). It is also undocumented that `GRANT pg_read_all_data` +is enough to satisfy the role and tablespace functions. + +**Expected:** the reference lists each function's privilege requirement, as +PostgreSQL customarily documents for privilege-gated functions. + +**Actual:** the *Get Object DDL Functions* table contains no mention of +`privilege`, `permission`, `pg_authid`, or `superuser`. + +**Reproduction:** + +```sql +CREATE ROLE regress_unpriv LOGIN; +SET allow_in_place_tablespaces = on; +CREATE TABLESPACE regress_ts LOCATION ''; +CREATE DATABASE regress_ddb; +REVOKE SELECT ON pg_tablespace FROM PUBLIC; +REVOKE CONNECT ON DATABASE regress_ddb FROM PUBLIC; + +SET ROLE regress_unpriv; +SELECT * FROM pg_get_role_ddl(current_user::regrole); -- ERROR: permission denied for role regress_unpriv +SELECT * FROM pg_get_tablespace_ddl('regress_ts'); -- ERROR: permission denied for tablespace regress_ts +SELECT * FROM pg_get_database_ddl('regress_ddb'); -- ERROR: permission denied for database regress_ddb +RESET ROLE; + +GRANT pg_read_all_data TO regress_unpriv; +SET ROLE regress_unpriv; +SELECT count(*) FROM pg_get_role_ddl(current_user::regrole); -- now succeeds (undocumented) +``` + +**Suggested fix:** add a sentence per function to the reference stating the +required privilege (mirroring the code comments "User must have SELECT +privilege on pg_authid/pg_tablespace"). + +--- + +## D2. Docs omit that the functions refuse reserved / system targets + +**Category:** doc_mismatch · **Severity:** low (documentation only) + +Each function refuses a class of objects that exists in every cluster, with +`ERROR` code `42939` (reserved_name): + +| Call | Error | Raised at | +| --- | --- | --- | +| `pg_get_tablespace_ddl('pg_default')` / `('pg_global')` | `tablespace name "..." is reserved` | `ddlutils.c:512` | +| `pg_get_role_ddl('pg_monitor')` (any `pg_*` role) | `role name "pg_monitor" is reserved` | `ddlutils.c:184` | +| `pg_get_database_ddl('template0')` / `('template1')` | `database "..." is a system database` | `ddlutils.c:702` | + +The refusals themselves are intentional and consistent. But the reference +says each function "Reconstructs the CREATE … statement for the specified +…" with no stated exclusions and no documented error conditions, so a user +iterating over `pg_tablespace`, `pg_authid`, or `pg_database` (a natural way +to dump every object) hits unexpected errors. + +**Expected:** the reference notes that `pg_`-prefixed tablespaces/roles and +`template0`/`template1` are rejected (or, at least, that error conditions +exist). + +**Actual:** the table mentions none of `reserved`, `system`, `pg_default`, +`pg_global`, or `template0` (`template` appears only in "template status"). + +**Reproduction:** + +```sql +SELECT * FROM pg_get_tablespace_ddl('pg_default'); -- ERROR: tablespace name "pg_default" is reserved +SELECT * FROM pg_get_tablespace_ddl('pg_global'); -- ERROR: tablespace name "pg_global" is reserved +SELECT * FROM pg_get_role_ddl('pg_monitor'); -- ERROR: role name "pg_monitor" is reserved +SELECT * FROM pg_get_database_ddl('template1'); -- ERROR: database "template1" is a system database +SELECT * FROM pg_get_database_ddl('template0'); -- ERROR: database "template0" is a system database +``` + +**Suggested fix:** document the refused targets for each function. + +--- + +## D3. Docs omit `ALLOW_CONNECTIONS` from `pg_get_database_ddl`'s output list + +**Category:** doc_mismatch · **Severity:** low (documentation only) + +The reference enumerates the `ALTER DATABASE` statements the function emits +as being for "connection limit, template status, and configuration +settings" (`func-info.sgml:3896`). But the function also emits +`ALTER DATABASE … ALLOW_CONNECTIONS = false` when `datallowconn` is false +(`ddlutils.c:833`), which the enumeration does not cover. A reader would +wrongly conclude the allow-connections state is not captured. + +**Expected:** the enumeration includes the allow-connections state, e.g. +"… connection limit, template status, allow-connections status, and +configuration settings." + +**Actual:** `ALLOW_CONNECTIONS` is emitted but absent from the documented +list. + +**Reproduction:** + +```sql +CREATE DATABASE regress_db1 ALLOW_CONNECTIONS false; +SELECT * FROM pg_get_database_ddl('regress_db1'); +-- CREATE DATABASE regress_db1 WITH TEMPLATE = template0 ENCODING = ... ; +-- ALTER DATABASE regress_db1 OWNER TO ...; +-- ALTER DATABASE regress_db1 ALLOW_CONNECTIONS = false; <-- not in the docs' list +``` + +**Related nit (same paragraph):** the emitted `ALTER DATABASE … OWNER TO` +statement is likewise absent from the enumeration, though the `owner` +parameter description partially covers it. + +**Suggested fix:** extend the enumeration to mention allow-connections (and, +optionally, owner). + +--- + +## Verification notes + +- All reproductions above were run on a fresh `master` (`5f14f82`) assert + build and matched exactly (error text, SQLSTATE `42939`/`42501`, and the + `ddlutils.c` line numbers cited). +- None of these correspond to the already-committed follow-up fixes + (`d6ed87d`, `1f108fc`, `cda0c4c`, `5642a03`, `6c7bce2`). +- The feature is otherwise robust on the surfaces exercised during the hunt: + attribute/GUC/membership round trips, ICU/builtin/libc locale handling, + `GRANTED BY` membership replay, identifier and literal quoting (including + injection attempts), and the set-returning call paths all round-tripped or + behaved correctly.
^ permalink raw reply [nested|flat] 32+ messages in thread

* Re: pg_get_*_ddl() needs a redesign
  2026-08-27 01:52 pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
@ 2026-09-09 15:47 ` Melanie Plageman <melanieplageman@gmail.com>
  2026-09-09 16:24   ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  0 siblings, 1 reply; 32+ messages in thread

From: Melanie Plageman @ 2026-09-09 15:47 UTC (permalink / raw)
  To: Noah Misch <noah@leadboat.com>; +Cc: andrew@dunslane.net; gonzalemario@gmail.com; dbryan.green@gmail.com; euler@eulerto.com; pgsql-hackers

On Wed, Aug 26, 2026 at 9:52 PM Noah Misch <noah@leadboat.com> wrote:
>
> commit 76e514e wrote:
> > Author:     Andrew Dunstan <>
> > AuthorDate: Thu Mar 19 09:52:25 2026 -0400
> > Commit:     Andrew Dunstan <andrew@dunslane.net>
> > CommitDate: Sun Apr 5 10:54:54 2026 -0400
> >
> >     Add pg_get_role_ddl() function
>
> I reviewed this commit.
>
> >     Author: Mario Gonzalez <gonzalemario@gmail.com>
> >     Author: Bryan Green <dbryan.green@gmail.com>
> >     Co-authored-by: Andrew Dunstan <andrew@dunslane.net>
> >     Co-authored-by: Euler Taveira <euler@eulerto.com>
> >     Reviewed-by: Japin Li <japinli@hotmail.com>
> >     Reviewed-by: Quan Zongliang <quanzongliang@yeah.net>
> >     Reviewed-by: jian he <jian.universality@gmail.com>
> >     Discussion: https://postgr.es/m/4c5f895e-3281-48f8-b943-9228b7da6471@gmail.com
> >     Discussion: https://postgr.es/m/e247c261-e3fb-4810-81e0-a65893170e94@dunslane.net
>
> > +     /*
> > +      * We intentionally omit PASSWORD.  There's no way to retrieve the
> > +      * original password text from the stored hash, and even if we could,
> > +      * exposing passwords through a SQL function would be a security issue.
> > +      * Users must set passwords separately after recreating roles.
> > +      */
>
> pg_dumpall recreates password hashes without needing the original plaintext.
> The first thread message said the use case is "dumping role definitions for
> migration or backup purposes without needing pg_dumpall."  Users expect their
> passwords to be accepted after migration or restore from backup.
>
> I also don't see a security distinction arising merely because SQL is the
> conduit.
>
> > + * pg_get_role_ddl_internal
> > + *           Generate DDL statements to recreate a role
>
> > +                     /* Build a fresh ALTER ROLE statement for this setting */
> > +                     resetStringInfo(&buf);
> > +                     appendStringInfo(&buf, "ALTER ROLE %s", quote_identifier(rolname));
> > +
> > +                     if (datname != NULL)
> > +                             appendStringInfo(&buf, " IN DATABASE %s",
> > +                                                              quote_identifier(datname));
>
> This doesn't deal with dependencies.  To migrate, you need to dump roles
> first, then databases (potentially owned by roles), then IN DATABASE ... SET
> statements (which depend on both).  By putting IN DATABASE in the same payload
> as CREATE ROLE, it's not conducive to restoring from an empty cluster.  The
> caller would need to break apart the payload and do its own dependency
> analysis, which substantially defeats the point of having $SUBJECT.
>
> The word "depend" appears nowhere on the threads or in this commit.  For a
> feature aiming for an outcome like pg_dump, I think dependency handling needs
> to be foundational in the design.
>
> > +     /*
> > +      * Scan pg_auth_members for role memberships.  We look for rows where
> > +      * member = roleid, meaning this role has been granted membership in other
> > +      * roles.
>
> The corresponding step in pg_dumpall is much more complicated; see this
> comment in dumpRoleMembership():
>
>         /*
>          * We can't dump these GRANT commands in arbitrary order, because a role
>          * that is named as a grantor must already have ADMIN OPTION on the role
>          * for which it is granting permissions, except for the bootstrap
>          * superuser, who can always be named as the grantor.
>          *
>          * We handle this by considering these grants role by role. For each role,
>          * we initially consider the only allowable grantor to be the bootstrap
>          * superuser. Every time we grant ADMIN OPTION on the role to some user,
>          * that user also becomes an allowable grantor. We make repeated passes
>          * over the grants for the role, each time dumping those whose grantors
>          * are allowable and which we haven't done yet. Eventually this should let
>          * us dump all the grants.
>          */
>
> If the backend version achieves the right outcomes without that complexity, it
> should have a comment about how it achieves that.

[RMT hat]

We are concerned that there has been no reply addressing these
reported issues. We urge the feature authors to reply and determine
whether or not this feature needs to be fixed (or reverted).

- Melanie






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

* Re: pg_get_*_ddl() needs a redesign
  2026-08-27 01:52 pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 15:47 ` Re: pg_get_*_ddl() needs a redesign Melanie Plageman <melanieplageman@gmail.com>
@ 2026-09-09 16:24   ` Andrew Dunstan <andrew@dunslane.net>
  2026-09-09 17:21     ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  0 siblings, 1 reply; 32+ messages in thread

From: Andrew Dunstan @ 2026-09-09 16:24 UTC (permalink / raw)
  To: Melanie Plageman <melanieplageman@gmail.com>; Noah Misch <noah@leadboat.com>; +Cc: gonzalemario@gmail.com; dbryan.green@gmail.com; euler@eulerto.com; pgsql-hackers


On 2026-09-09 We 11:47 AM, Melanie Plageman wrote:
>
> [RMT hat]
>
> We are concerned that there has been no reply addressing these
> reported issues. We urge the feature authors to reply and determine
> whether or not this feature needs to be fixed (or reverted).


Sorry, my bad. Euler and I have been working on fixes, which I hope to 
publish today. There was a slight delay due to the issue addressed by my 
commit a12600b762c from an hour or so ago.


cheers


andrew


--
Andrew Dunstan
EDB: https://www.enterprisedb.com







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

* Re: pg_get_*_ddl() needs a redesign
  2026-08-27 01:52 pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 15:47 ` Re: pg_get_*_ddl() needs a redesign Melanie Plageman <melanieplageman@gmail.com>
  2026-09-09 16:24   ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
@ 2026-09-09 17:21     ` Noah Misch <noah@leadboat.com>
  2026-09-09 17:34       ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 1 reply; 32+ messages in thread

From: Noah Misch @ 2026-09-09 17:21 UTC (permalink / raw)
  To: Andrew Dunstan <andrew@dunslane.net>; +Cc: Melanie Plageman <melanieplageman@gmail.com>; gonzalemario@gmail.com; dbryan.green@gmail.com; euler@eulerto.com; pgsql-hackers

On Wed, Sep 09, 2026 at 12:24:32PM -0400, Andrew Dunstan wrote:
> On 2026-09-09 We 11:47 AM, Melanie Plageman wrote:
> > [RMT hat]
> > 
> > We are concerned that there has been no reply addressing these
> > reported issues. We urge the feature authors to reply and determine
> > whether or not this feature needs to be fixed (or reverted).
> 
> Sorry, my bad. Euler and I have been working on fixes, which I hope to
> publish today. There was a slight delay due to the issue addressed by my
> commit a12600b762c from an hour or so ago.

I want to clarify one thing before you spend much time on fixes.  I don't see
"fixes" addressing this thread as a whole, unless you plan to dispute the
premise that the feature needs a redesign.  In other words, I think the thread
outcome should be one of these:

- My review erred in determining that the feature needs a redesign.  The
  design is sound and should proceed, possibly with some fixes.

- Revert the feature.





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

* Re: pg_get_*_ddl() needs a redesign
  2026-08-27 01:52 pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 15:47 ` Re: pg_get_*_ddl() needs a redesign Melanie Plageman <melanieplageman@gmail.com>
  2026-09-09 16:24   ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-09 17:21     ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
@ 2026-09-09 17:34       ` Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-09 18:05         ` Re: pg_get_*_ddl() needs a redesign Nathan Bossart <nathandbossart@gmail.com>
  2026-09-09 19:12         ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  0 siblings, 2 replies; 32+ messages in thread

From: Tom Lane @ 2026-09-09 17:34 UTC (permalink / raw)
  To: Noah Misch <noah@leadboat.com>; +Cc: Andrew Dunstan <andrew@dunslane.net>; Melanie Plageman <melanieplageman@gmail.com>; gonzalemario@gmail.com; dbryan.green@gmail.com; euler@eulerto.com; pgsql-hackers

Noah Misch <noah@leadboat.com> writes:
> I want to clarify one thing before you spend much time on fixes.  I don't see
> "fixes" addressing this thread as a whole, unless you plan to dispute the
> premise that the feature needs a redesign.  In other words, I think the thread
> outcome should be one of these:

> - My review erred in determining that the feature needs a redesign.  The
>   design is sound and should proceed, possibly with some fixes.

> - Revert the feature.

FWIW, I agree with Noah's point that having two independent
implementations of SQL reverse compilation is not really a place
we want to be: it will be a major PITA for future development.

Unfortunately, I see no practical way to have pg_dump share code with
the backend for most of this stuff; not least because pg_dump has to
support dumping from old backends that won't have any such feature.
So we either swallow that duplication or decide that we're never
going to support this in the backend.  Neither choice is palatable,
but I don't think I want to be forced into the duplicative approach
when we've not explored other alternatives (such as refactoring
pg_dump to expose its internal logic in some way).

			regards, tom lane






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

* Re: pg_get_*_ddl() needs a redesign
  2026-08-27 01:52 pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 15:47 ` Re: pg_get_*_ddl() needs a redesign Melanie Plageman <melanieplageman@gmail.com>
  2026-09-09 16:24   ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-09 17:21     ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 17:34       ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
@ 2026-09-09 18:05         ` Nathan Bossart <nathandbossart@gmail.com>
  1 sibling, 0 replies; 32+ messages in thread

From: Nathan Bossart @ 2026-09-09 18:05 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Noah Misch <noah@leadboat.com>; Andrew Dunstan <andrew@dunslane.net>; Melanie Plageman <melanieplageman@gmail.com>; gonzalemario@gmail.com; dbryan.green@gmail.com; euler@eulerto.com; pgsql-hackers

On Wed, Sep 09, 2026 at 01:34:59PM -0400, Tom Lane wrote:
> [...] (such as refactoring pg_dump to expose its internal logic in some
> way).

Over the years, I've encountered a few cases where a pg_dump library
would be rather handy.  That's probably a huge and difficult project,
though.

-- 
nathan






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

* Re: pg_get_*_ddl() needs a redesign
  2026-08-27 01:52 pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 15:47 ` Re: pg_get_*_ddl() needs a redesign Melanie Plageman <melanieplageman@gmail.com>
  2026-09-09 16:24   ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-09 17:21     ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 17:34       ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
@ 2026-09-09 19:12         ` Andrew Dunstan <andrew@dunslane.net>
  2026-09-09 20:12           ` Re: pg_get_*_ddl() needs a redesign Andres Freund <andres@anarazel.de>
  2026-09-10 03:59           ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  1 sibling, 2 replies; 32+ messages in thread

From: Andrew Dunstan @ 2026-09-09 19:12 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; Noah Misch <noah@leadboat.com>; +Cc: Melanie Plageman <melanieplageman@gmail.com>; gonzalemario@gmail.com; dbryan.green@gmail.com; euler@eulerto.com; pgsql-hackers


On 2026-09-09 We 1:34 PM, Tom Lane wrote:
> Noah Misch<noah@leadboat.com> writes:
>> I want to clarify one thing before you spend much time on fixes.  I don't see
>> "fixes" addressing this thread as a whole, unless you plan to dispute the
>> premise that the feature needs a redesign.  In other words, I think the thread
>> outcome should be one of these:
>> - My review erred in determining that the feature needs a redesign.  The
>>    design is sound and should proceed, possibly with some fixes.
>> - Revert the feature.
> FWIW, I agree with Noah's point that having two independent
> implementations of SQL reverse compilation is not really a place
> we want to be: it will be a major PITA for future development.
>
> Unfortunately, I see no practical way to have pg_dump share code with
> the backend for most of this stuff; not least because pg_dump has to
> support dumping from old backends that won't have any such feature.
> So we either swallow that duplication or decide that we're never
> going to support this in the backend.  Neither choice is palatable,
> but I don't think I want to be forced into the duplicative approach
> when we've not explored other alternatives (such as refactoring
> pg_dump to expose its internal logic in some way).
>
> 			


I first raised the idea of these functions on the mailing list in July 
2025, although the idea was much older. [1] Among other things, you 
(Tom) said [2]:

    Insisting that this feature support pg_dump is a good way
    of making sure that nothing useful will emerge at all.

Concrete patches began to appear around October and November 2025. I don't recall anyone coming along and saying "No, we don't want to do that." After they were committed there were various comments on the way they were done, and I addressed them.  Now, months later, we are more or less told that this whole enterprise has been misguided from the start. Is it any wonder that people often find the process of contributing to Postgres discouraging? And that would include people who have been working on more important members of this set for release 20, particularly the one that most people want, namely pg_get_table_ddl() that Akshay has been working on. I don't feel badly for myself, but I do feel badly for the contributors.

I believe reverting now almost certainly means this proposal or anything like it is probably dead for the foreseeable future.

To me it is beyond stupid that a postgresql server doesn't have enough introspection to be able to produce the DDL for its own objects. Telling people that they have to call pg_dump/pg_dumpall to generate the DDL programmatically is awful. So, do I think this is worth the possible maintenance burden? Yes. I might take a suggestion of "needs redesign" more seriously if there had been a hint of what that might look like. But without that it looks to me like a way of saying "I don't like the feature or think we need it."

cheers

andrew


[1] https://postgr.es/m/945db7c5-be75-45bf-b55b-cb1e56f2e3e9@dunslane.net

[2] https://postgr.es/m/758258.1755354170@sss.pgh.pa.us


--
Andrew Dunstan
EDB:https://www.enterprisedb.com

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

* Re: pg_get_*_ddl() needs a redesign
  2026-08-27 01:52 pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 15:47 ` Re: pg_get_*_ddl() needs a redesign Melanie Plageman <melanieplageman@gmail.com>
  2026-09-09 16:24   ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-09 17:21     ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 17:34       ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-09 19:12         ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
@ 2026-09-09 20:12           ` Andres Freund <andres@anarazel.de>
  2026-09-09 22:25             ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  1 sibling, 1 reply; 32+ messages in thread

From: Andres Freund @ 2026-09-09 20:12 UTC (permalink / raw)
  To: Andrew Dunstan <andrew@dunslane.net>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Noah Misch <noah@leadboat.com>; Melanie Plageman <melanieplageman@gmail.com>; gonzalemario@gmail.com; dbryan.green@gmail.com; euler@eulerto.com; pgsql-hackers

Hi,

On 2026-09-09 15:12:26 -0400, Andrew Dunstan wrote:
> Concrete patches began to appear around October and November 2025. I don't
> recall anyone coming along and saying "No, we don't want to do that."

Given how busy the list is at times, I don't think we can really expect
everyone to make all objections known early enough, unfortunately. Otherwise
nobody will ever have time to actually do work on their own.


> To me it is beyond stupid that a postgresql server doesn't have enough
> introspection to be able to produce the DDL for its own objects. Telling
> people that they have to call pg_dump/pg_dumpall to generate the DDL
> programmatically is awful. So, do I think this is worth the possible
> maintenance burden? Yes. I might take a suggestion of "needs redesign" more
> seriously if there had been a hint of what that might look like. But without
> that it looks to me like a way of saying "I don't like the feature or think
> we need it."

I don't really have a clear opinion on this. I agree that not having a way to
get the DDL in a simple way is bad and that invoking pg_dump for it isn't an
actual answer.  But I also agree that having two codepaths for this is pretty
bad too.



I do have some concerns though:

- I don't understand the permission concept:

  	/* User must have connect privilege for target database. */
	aclresult = object_aclcheck(DatabaseRelationId, dbid, GetUserId(), ACL_CONNECT);
	if (aclresult != ACLCHECK_OK)
		aclcheck_error(aclresult, OBJECT_DATABASE,
					   get_database_name(dbid));

   Here the code seems to intend to check the permissions of the to-be-dumped
   object.

   But then there's stuff like:

	/* User must have SELECT privilege on pg_tablespace. */
	if (pg_class_aclcheck(TableSpaceRelationId, GetUserId(), ACL_SELECT) != ACLCHECK_OK)
	{
		ReleaseSysCache(tuple);
		aclcheck_error(ACLCHECK_NO_PRIV, OBJECT_TABLESPACE, spcname);
	}

   Which is a right everyone has, and that is not specific to the to-be-dumped
   object. Why are the permissions for pg_tablespace checked, but not e.g. the
   permissions for pg_database?


   There's also a permission check for pg_authid:
	/* User must have SELECT privilege on pg_authid. */
	if (pg_class_aclcheck(AuthIdRelationId, GetUserId(), ACL_SELECT) != ACLCHECK_OK)
	{
		ReleaseSysCache(tuple);
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
				 errmsg("permission denied for role %s", rolname)));
	}

   This afaict makes basically makes pg_get_role_ddl() unusable for
   non-superusers?

   And the error message indicates that the permission failure is on the user,
   but in fact the user's permissions were never checked.


- Has somebody thought about the locking semantics that are needed to make the
  ddl functions actually safe under concurrency?

  It's not yet too bad with the kinds of objects supported, but it'll be more
  important once tables etc are added.

  Even now I think these really ought to take appropriate locks?

  Once locking is done properly, I think this also ought to make sure to not
  lock objects that the user does not have permissions to.


- duplication between *_ddl_* functions:

  Why do pg_get_database_ddl(), pg_get_tablespace_ddl_srf(), pg_get_role_ddl()
  basically have the same contents? Why populate a list that then is returned
  via the SRF_PERCALL mechanism instead of just populating the tuplestore
  once?


- The code is quite verbose. With just roles, tablespaces and databases
  supported, we're already at ~1k lines. Once more is supported, we're talking
  a substantial amount of duplicated code that needs to be maintained
  indefinitely.

  I think this ought to undergo a fair bit refactoring to reduce the verbosity
  / repetition.  It e.g. really can't make sense that we have the ~same ~10
  lines for OWNER, CONNECTION LIMIT, IS_TEMPLATE, ALLOW_CONNECTIONS.

  There's also stuff like copies of timestamptz_out(), which seems ... not the
  right thing to have?


- There are no crosschecks that pg_get_*ddl actually produce the same result
  as the SQL generated by pg_dump. Without some automated crosschecking
  between them, I think it's pretty much guaranteed that we will have
  divergence.


- The tap test is pointlessly expensive, forking 10s of psqls for something
  that could - perhaps leaving some locale related filtering aside - as a
  single pg_regress style test isn't awesome.


Greetings,

Andres Freund






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

* Re: pg_get_*_ddl() needs a redesign
  2026-08-27 01:52 pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 15:47 ` Re: pg_get_*_ddl() needs a redesign Melanie Plageman <melanieplageman@gmail.com>
  2026-09-09 16:24   ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-09 17:21     ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 17:34       ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-09 19:12         ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-09 20:12           ` Re: pg_get_*_ddl() needs a redesign Andres Freund <andres@anarazel.de>
@ 2026-09-09 22:25             ` Andrew Dunstan <andrew@dunslane.net>
  2026-09-10 23:59               ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  0 siblings, 1 reply; 32+ messages in thread

From: Andrew Dunstan @ 2026-09-09 22:25 UTC (permalink / raw)
  To: Andres Freund <andres@anarazel.de>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Noah Misch <noah@leadboat.com>; Melanie Plageman <melanieplageman@gmail.com>; gonzalemario@gmail.com; dbryan.green@gmail.com; euler@eulerto.com; pgsql-hackers


On 2026-09-09 We 4:12 PM, Andres Freund wrote:
> Hi,
>
> On 2026-09-09 15:12:26 -0400, Andrew Dunstan wrote:
>> Concrete patches began to appear around October and November 2025. I don't
>> recall anyone coming along and saying "No, we don't want to do that."
> Given how busy the list is at times, I don't think we can really expect
> everyone to make all objections known early enough, unfortunately. Otherwise
> nobody will ever have time to actually do work on their own.


Quite so, but the time frame in this case was pretty large.


>
>
>> To me it is beyond stupid that a postgresql server doesn't have enough
>> introspection to be able to produce the DDL for its own objects. Telling
>> people that they have to call pg_dump/pg_dumpall to generate the DDL
>> programmatically is awful. So, do I think this is worth the possible
>> maintenance burden? Yes. I might take a suggestion of "needs redesign" more
>> seriously if there had been a hint of what that might look like. But without
>> that it looks to me like a way of saying "I don't like the feature or think
>> we need it."
> I don't really have a clear opinion on this. I agree that not having a way to
> get the DDL in a simple way is bad and that invoking pg_dump for it isn't an
> actual answer.  But I also agree that having two codepaths for this is pretty
> bad too.


Well, I have a proposal at least for that, namely that we test the 
equivalence with a TAP test. I don't know how comprehensive we can make 
it, but it seems like s atart at least.


>
>
>
> I do have some concerns though:
>
> - I don't understand the permission concept:
>
>    	/* User must have connect privilege for target database. */
> 	aclresult = object_aclcheck(DatabaseRelationId, dbid, GetUserId(), ACL_CONNECT);
> 	if (aclresult != ACLCHECK_OK)
> 		aclcheck_error(aclresult, OBJECT_DATABASE,
> 					   get_database_name(dbid));
>
>     Here the code seems to intend to check the permissions of the to-be-dumped
>     object.
>
>     But then there's stuff like:
>
> 	/* User must have SELECT privilege on pg_tablespace. */
> 	if (pg_class_aclcheck(TableSpaceRelationId, GetUserId(), ACL_SELECT) != ACLCHECK_OK)
> 	{
> 		ReleaseSysCache(tuple);
> 		aclcheck_error(ACLCHECK_NO_PRIV, OBJECT_TABLESPACE, spcname);
> 	}
>
>     Which is a right everyone has, and that is not specific to the to-be-dumped
>     object. Why are the permissions for pg_tablespace checked, but not e.g. the
>     permissions for pg_database?
>
>
>     There's also a permission check for pg_authid:
> 	/* User must have SELECT privilege on pg_authid. */
> 	if (pg_class_aclcheck(AuthIdRelationId, GetUserId(), ACL_SELECT) != ACLCHECK_OK)
> 	{
> 		ReleaseSysCache(tuple);
> 		ereport(ERROR,
> 				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
> 				 errmsg("permission denied for role %s", rolname)));
> 	}
>
>     This afaict makes basically makes pg_get_role_ddl() unusable for
>     non-superusers?
>
>     And the error message indicates that the permission failure is on the user,
>     but in fact the user's permissions were never checked.
>
>
> - Has somebody thought about the locking semantics that are needed to make the
>    ddl functions actually safe under concurrency?
>
>    It's not yet too bad with the kinds of objects supported, but it'll be more
>    important once tables etc are added.
>
>    Even now I think these really ought to take appropriate locks?
>
>    Once locking is done properly, I think this also ought to make sure to not
>    lock objects that the user does not have permissions to.
>
>
> - duplication between *_ddl_* functions:
>
>    Why do pg_get_database_ddl(), pg_get_tablespace_ddl_srf(), pg_get_role_ddl()
>    basically have the same contents? Why populate a list that then is returned
>    via the SRF_PERCALL mechanism instead of just populating the tuplestore
>    once?
>
>
> - The code is quite verbose. With just roles, tablespaces and databases
>    supported, we're already at ~1k lines. Once more is supported, we're talking
>    a substantial amount of duplicated code that needs to be maintained
>    indefinitely.
>
>    I think this ought to undergo a fair bit refactoring to reduce the verbosity
>    / repetition.  It e.g. really can't make sense that we have the ~same ~10
>    lines for OWNER, CONNECTION LIMIT, IS_TEMPLATE, ALLOW_CONNECTIONS.
>
>    There's also stuff like copies of timestamptz_out(), which seems ... not the
>    right thing to have?
>
>
> - There are no crosschecks that pg_get_*ddl actually produce the same result
>    as the SQL generated by pg_dump. Without some automated crosschecking
>    between them, I think it's pretty much guaranteed that we will have
>    divergence.
>
>
> - The tap test is pointlessly expensive, forking 10s of psqls for something
>    that could - perhaps leaving some locale related filtering aside - as a
>    single pg_regress style test isn't awesome.
>
>

Thanks for reviewing. I hope to have some proposals tomorrow for 
addressing these issues as well as those raised by Noah.


cheers


andrew


--
Andrew Dunstan
EDB: https://www.enterprisedb.com







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

* Re: pg_get_*_ddl() needs a redesign
  2026-08-27 01:52 pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 15:47 ` Re: pg_get_*_ddl() needs a redesign Melanie Plageman <melanieplageman@gmail.com>
  2026-09-09 16:24   ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-09 17:21     ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 17:34       ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-09 19:12         ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-09 20:12           ` Re: pg_get_*_ddl() needs a redesign Andres Freund <andres@anarazel.de>
  2026-09-09 22:25             ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
@ 2026-09-10 23:59               ` Andrew Dunstan <andrew@dunslane.net>
  2026-09-13 18:28                 ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  0 siblings, 1 reply; 32+ messages in thread

From: Andrew Dunstan @ 2026-09-10 23:59 UTC (permalink / raw)
  To: Andres Freund <andres@anarazel.de>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Noah Misch <noah@leadboat.com>; Melanie Plageman <melanieplageman@gmail.com>; gonzalemario@gmail.com; dbryan.green@gmail.com; euler@eulerto.com; pgsql-hackers


On 2026-09-09 We 6:25 PM, Andrew Dunstan wrote:
>
>
> Thanks for reviewing. I hope to have some proposals tomorrow for 
> addressing these issues as well as those raised by Noah.
>
>
>

I have run out of time, energy and brain cells. I have some working 
patches, but a) they need a little polish and b) I think they are too 
invasive for consideration now. The major difference in actual code (as 
opposed to testing) is in how we deal with permissions. I spent quite a 
lot of time yesterday and today on that, and came to the conclusion that 
it needs to be reworked along these lines: we should allow the user to 
see the information the functions provide if and only if they can see it 
by directly selecting from the catalog. Code changes to implement this 
by directly running ACL checks on  the relevant catalogs are 
straightforward but also substantial. My proposed changes to testing are 
also substantial, being both more efficient and providing better 
coverage, especially w.r.t pg_dump/all compatibility.

I therefore suggest that we revert for release 19, but not in master, 
and I will continue to polish the patches I mentioned and publish them 
in a few days.

I can make the revert happen in the next day or so.


cheers


andrew


--
Andrew Dunstan
EDB: https://www.enterprisedb.com







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

* Re: pg_get_*_ddl() needs a redesign
  2026-08-27 01:52 pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 15:47 ` Re: pg_get_*_ddl() needs a redesign Melanie Plageman <melanieplageman@gmail.com>
  2026-09-09 16:24   ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-09 17:21     ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 17:34       ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-09 19:12         ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-09 20:12           ` Re: pg_get_*_ddl() needs a redesign Andres Freund <andres@anarazel.de>
  2026-09-09 22:25             ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-10 23:59               ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
@ 2026-09-13 18:28                 ` Andrew Dunstan <andrew@dunslane.net>
  2026-09-14 02:21                   ` Re: pg_get_*_ddl() needs a redesign Michael Paquier <michael@paquier.xyz>
  0 siblings, 1 reply; 32+ messages in thread

From: Andrew Dunstan @ 2026-09-13 18:28 UTC (permalink / raw)
  To: Andres Freund <andres@anarazel.de>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Noah Misch <noah@leadboat.com>; Melanie Plageman <melanieplageman@gmail.com>; gonzalemario@gmail.com; dbryan.green@gmail.com; euler@eulerto.com; pgsql-hackers


On 2026-09-10 Th 7:59 PM, Andrew Dunstan wrote:
>
> On 2026-09-09 We 6:25 PM, Andrew Dunstan wrote:
>>
>>
>> Thanks for reviewing. I hope to have some proposals tomorrow for 
>> addressing these issues as well as those raised by Noah.
>>
>>
>>
>
> I have run out of time, energy and brain cells. I have some working 
> patches, but a) they need a little polish and b) I think they are too 
> invasive for consideration now. The major difference in actual code 
> (as opposed to testing) is in how we deal with permissions. I spent 
> quite a lot of time yesterday and today on that, and came to the 
> conclusion that it needs to be reworked along these lines: we should 
> allow the user to see the information the functions provide if and 
> only if they can see it by directly selecting from the catalog. Code 
> changes to implement this by directly running ACL checks on  the 
> relevant catalogs are straightforward but also substantial. My 
> proposed changes to testing are also substantial, being both more 
> efficient and providing better coverage, especially w.r.t pg_dump/all 
> compatibility.
>
> I therefore suggest that we revert for release 19, but not in master, 
> and I will continue to polish the patches I mentioned and publish them 
> in a few days.
>
> I can make the revert happen in the next day or so.
>
>
>

OK, I have done that revert. Here are the patches Euler and I have in mind.


cheers


andrew



--
Andrew Dunstan
EDB: https://www.enterprisedb.com

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

v6-0001-pg_get_role_ddl-password-support-membership-grant.patch (text/x-patch, 9.7K) download From e3b65ce3bb90a5a84156c2108f6defc92e64eb3c Mon Sep 17 00:00:00 2001 From: Andrew Dunstan <andrew@dunslane.net> Date: Thu, 10 Sep 2026 11:07:16 -0400 Subject: [PATCH v6 1/5] pg_get_role_ddl: password support, membership grant ordering, and replay-safe attribute handling Emit the PASSWORD verifier from pg_authid, behind a new "password" argument (default true) and a privilege check that only fires when the verifier is actually emitted -- everything else the function emits is already public via pg_roles, pg_db_role_setting, and pg_auth_members, so requiring pg_authid access unconditionally made the function unusable by anyone but a superuser. Order membership GRANT statements so self-grants sort last: a role can only grant itself membership after gaining ADMIN OPTION from an earlier grant, and the catalog scan doesn't guarantee that order. Split role attributes into a separate ALTER ROLE ... WITH, matching pg_dumpall, so replaying the output over an existing role still applies them even though the CREATE fails. Author: Euler Taveira <euler@eulerto.com> Reviewed-by: Andrew Dunstan <andrew@dunslane.net> Discussion: https://postgr.es/m/20260827015242.54.noahmisch@microsoft.com --- src/backend/utils/adt/ddlutils.c | 84 +++++++++++++++++++++++--------- src/include/catalog/pg_proc.dat | 8 +-- 2 files changed, 66 insertions(+), 26 deletions(-) diff --git a/src/backend/utils/adt/ddlutils.c b/src/backend/utils/adt/ddlutils.c index a70f1c28655..913a35fb9d9 100644 --- a/src/backend/utils/adt/ddlutils.c +++ b/src/backend/utils/adt/ddlutils.c @@ -51,7 +51,7 @@ static void append_ddl_option(StringInfo buf, bool pretty, int indent, static void append_guc_value(StringInfo buf, const char *name, const char *value); static List *pg_get_role_ddl_internal(Oid roleid, bool pretty, - bool memberships); + bool memberships, bool password); static List *pg_get_tablespace_ddl_internal(Oid tsid, bool pretty, bool no_owner); static Datum pg_get_tablespace_ddl_srf(FunctionCallInfo fcinfo, Oid tsid); static List *pg_get_database_ddl_internal(Oid dbid, bool pretty, @@ -140,18 +140,22 @@ append_guc_value(StringInfo buf, const char *name, const char *value) * Generate DDL statements to recreate a role * * Returns a List of palloc'd strings, each being a complete SQL statement. - * The first list element is always the CREATE ROLE statement; subsequent - * elements are ALTER ROLE SET statements for any role-specific or - * role-in-database configuration settings. If memberships is true, - * GRANT statements for role memberships are appended. + * The first two list elements are always the CREATE ROLE statement and an + * ALTER ROLE statement carrying the role attributes; subsequent elements are + * ALTER ROLE SET statements for any role-specific or role-in-database + * configuration settings. If memberships is true, GRANT statements for + * role memberships are appended. If password is false, the PASSWORD + * clause is omitted. */ static List * -pg_get_role_ddl_internal(Oid roleid, bool pretty, bool memberships) +pg_get_role_ddl_internal(Oid roleid, bool pretty, bool memberships, + bool password) { HeapTuple tuple; Form_pg_authid roleform; StringInfoData buf; char *rolname; + Datum rolpassword; Datum rolevaliduntil; bool isnull; Relation rel; @@ -168,8 +172,13 @@ pg_get_role_ddl_internal(Oid roleid, bool pretty, bool memberships) roleform = (Form_pg_authid) GETSTRUCT(tuple); rolname = pstrdup(NameStr(roleform->rolname)); - /* User must have SELECT privilege on pg_authid. */ - if (pg_class_aclcheck(AuthIdRelationId, GetUserId(), ACL_SELECT) != ACLCHECK_OK) + /* + * rolpassword needs SELECT on pg_authid; nothing else here is + * sensitive, so only check it when the PASSWORD clause is wanted. + */ + if (password && + pg_class_aclcheck(AuthIdRelationId, GetUserId(), + ACL_SELECT) != ACLCHECK_OK) { ReleaseSysCache(tuple); ereport(ERROR, @@ -188,11 +197,20 @@ pg_get_role_ddl_internal(Oid roleid, bool pretty, bool memberships) errdetail("Role names starting with \"pg_\" are reserved for system roles."))); initStringInfo(&buf); - appendStringInfo(&buf, "CREATE ROLE %s", quote_identifier(rolname)); + + /* + * Attributes go in a separate ALTER ROLE, as pg_dumpall does, so they + * still apply when replayed over a role that already exists. + */ + appendStringInfo(&buf, "CREATE ROLE %s;", quote_identifier(rolname)); + statements = lappend(statements, pstrdup(buf.data)); + + resetStringInfo(&buf); + appendStringInfo(&buf, "ALTER ROLE %s WITH", quote_identifier(rolname)); /* * Append role attributes. The order here follows the same sequence as - * you'd typically write them in a CREATE ROLE command, though any order + * you'd typically write them in an ALTER ROLE command, though any order * is actually acceptable to the parser. */ append_ddl_option(&buf, pretty, 4, "%s", @@ -224,6 +242,19 @@ pg_get_role_ddl_internal(Oid roleid, bool pretty, bool memberships) append_ddl_option(&buf, pretty, 4, "CONNECTION LIMIT %d", roleform->rolconnlimit); + /* PASSWORD is the stored verifier; the plaintext isn't recoverable. */ + rolpassword = SysCacheGetAttr(AUTHOID, tuple, + Anum_pg_authid_rolpassword, + &isnull); + if (password && !isnull) + { + char *verifier = TextDatumGetCString(rolpassword); + + append_ddl_option(&buf, pretty, 4, "PASSWORD %s", + quote_literal_cstr(verifier)); + pfree(verifier); + } + rolevaliduntil = SysCacheGetAttr(AUTHOID, tuple, Anum_pg_authid_rolvaliduntil, &isnull); @@ -252,13 +283,6 @@ pg_get_role_ddl_internal(Oid roleid, bool pretty, bool memberships) ReleaseSysCache(tuple); - /* - * We intentionally omit PASSWORD. There's no way to retrieve the - * original password text from the stored hash, and even if we could, - * exposing passwords through a SQL function would be a security issue. - * Users must set passwords separately after recreating roles. - */ - appendStringInfoChar(&buf, ';'); statements = lappend(statements, pstrdup(buf.data)); @@ -367,9 +391,15 @@ pg_get_role_ddl_internal(Oid roleid, bool pretty, bool memberships) * Scan pg_auth_members for role memberships. We look for rows where * member = roleid, meaning this role has been granted membership in other * roles. + * + * A grantor needs ADMIN OPTION on the granted role already, and the + * only grant of ours that can supply that is a self-grant, so + * self-granted rows must sort last. */ if (memberships) { + List *self_granted = NIL; + rel = table_open(AuthMemRelationId, AccessShareLock); ScanKeyInit(&scankey, Anum_pg_auth_members_member, @@ -398,7 +428,11 @@ pg_get_role_ddl_internal(Oid roleid, bool pretty, bool memberships) appendStringInfo(&buf, " GRANTED BY %s;", quote_identifier(grantor)); - statements = lappend(statements, pstrdup(buf.data)); + /* Self-grants wait for the grant that gave ADMIN OPTION. */ + if (memform->grantor == roleid) + self_granted = lappend(self_granted, pstrdup(buf.data)); + else + statements = lappend(statements, pstrdup(buf.data)); pfree(granted_role); pfree(grantor); @@ -406,6 +440,8 @@ pg_get_role_ddl_internal(Oid roleid, bool pretty, bool memberships) systable_endscan(scan); table_close(rel, AccessShareLock); + + statements = list_concat(statements, self_granted); } pfree(buf.data); @@ -418,9 +454,10 @@ pg_get_role_ddl_internal(Oid roleid, bool pretty, bool memberships) * pg_get_role_ddl * Return DDL to recreate a role as a set of text rows. * - * Each row is a complete SQL statement. The first row is always the - * CREATE ROLE statement; subsequent rows are ALTER ROLE SET statements - * and optionally GRANT statements for role memberships. + * Each row is a complete SQL statement. The first two rows are always the + * CREATE ROLE statement and the ALTER ROLE statement carrying the role + * attributes; subsequent rows are ALTER ROLE SET statements and optionally + * GRANT statements for role memberships. */ Datum pg_get_role_ddl(PG_FUNCTION_ARGS) @@ -434,6 +471,7 @@ pg_get_role_ddl(PG_FUNCTION_ARGS) Oid roleid; bool pretty; bool memberships; + bool password; funcctx = SRF_FIRSTCALL_INIT(); oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx); @@ -441,8 +479,10 @@ pg_get_role_ddl(PG_FUNCTION_ARGS) roleid = PG_GETARG_OID(0); pretty = PG_GETARG_BOOL(1); memberships = PG_GETARG_BOOL(2); + password = PG_GETARG_BOOL(3); - statements = pg_get_role_ddl_internal(roleid, pretty, memberships); + statements = pg_get_role_ddl_internal(roleid, pretty, memberships, + password); funcctx->user_fctx = statements; funcctx->max_calls = list_length(statements); diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat index c53ce68c717..9595e21b3eb 100644 --- a/src/include/catalog/pg_proc.dat +++ b/src/include/catalog/pg_proc.dat @@ -8669,10 +8669,10 @@ proargtypes => 'oid bool', prosrc => 'pg_get_constraintdef_ext' }, { oid => '6501', descr => 'get DDL to recreate a role', proname => 'pg_get_role_ddl', prorows => '10', proretset => 't', - provolatile => 's', pronargdefaults => '2', prorettype => 'text', - proargtypes => 'regrole bool bool', - proargnames => '{role,pretty,memberships}', proargdefaults => '{false,true}', - prosrc => 'pg_get_role_ddl' }, + provolatile => 's', pronargdefaults => '3', prorettype => 'text', + proargtypes => 'regrole bool bool bool', + proargnames => '{role,pretty,memberships,password}', + proargdefaults => '{false,true,true}', prosrc => 'pg_get_role_ddl' }, { oid => '6499', descr => 'get DDL to recreate a tablespace', proname => 'pg_get_tablespace_ddl', prorows => '10', proretset => 't', provolatile => 's', pronargdefaults => '2', prorettype => 'text', -- 2.43.0
v6-0002-pg_get_tablespace_ddl-pg_get_database_ddl-output-.patch (text/x-patch, 5.1K) download From 9798a2e6c5a22eea217269b038c89f7e522e7ba8 Mon Sep 17 00:00:00 2001 From: Andrew Dunstan <andrew@dunslane.net> Date: Thu, 10 Sep 2026 11:08:05 -0400 Subject: [PATCH v6 2/5] pg_get_tablespace_ddl, pg_get_database_ddl: output-format fixes Print tablespace options unquoted, matching pg_dumpall: they're already "name=value" text and every option is numeric, so the generic reloptions-printing code's quoting was both unnecessary and a needless difference from pg_dumpall's output. This drops the only caller of get_reloptions() outside ruleutils.c, so make it static again. Compare a database's tablespace against DEFAULTTABLESPACE_OID instead of the tablespace name against the literal string "pg_default": tablespace names are case-sensitive, so a user-created "PG_DEFAULT" is a distinct, valid tablespace that the old comparison would misidentify. Author: Euler Taveira <euler@eulerto.com> Reported-by: Noah Misch <noah@leadboat.com> Reviewed-by: Andrew Dunstan <andrew@dunslane.net> Discussion: https://postgr.es/m/20260827015242.54.noahmisch@microsoft.com --- src/backend/utils/adt/ddlutils.c | 37 +++++++++++++++++++++++++------ src/backend/utils/adt/ruleutils.c | 4 ++-- src/include/utils/ruleutils.h | 1 - 3 files changed, 32 insertions(+), 10 deletions(-) diff --git a/src/backend/utils/adt/ddlutils.c b/src/backend/utils/adt/ddlutils.c index 913a35fb9d9..8343cc5614f 100644 --- a/src/backend/utils/adt/ddlutils.c +++ b/src/backend/utils/adt/ddlutils.c @@ -40,7 +40,6 @@ #include "utils/lsyscache.h" #include "utils/pg_locale.h" #include "utils/rel.h" -#include "utils/ruleutils.h" #include "utils/syscache.h" #include "utils/timestamp.h" #include "utils/varlena.h" @@ -597,10 +596,30 @@ pg_get_tablespace_ddl_internal(Oid tsid, bool pretty, bool no_owner) Anum_pg_tablespace_spcoptions, &isNull); if (!isNull) { + Datum *options; + int noptions; + resetStringInfo(&buf); appendStringInfo(&buf, "ALTER TABLESPACE %s SET (", quote_identifier(spcname)); - get_reloptions(&buf, datum); + + /* + * Elements are already "name=value", and every option is numeric, + * so emit verbatim, matching pg_dumpall. + */ + deconstruct_array_builtin(DatumGetArrayTypeP(datum), TEXTOID, + &options, NULL, &noptions); + for (int i = 0; i < noptions; i++) + { + char *option = TextDatumGetCString(options[i]); + + if (i > 0) + appendStringInfoString(&buf, ", "); + appendStringInfoString(&buf, option); + pfree(option); + } + pfree(options); + appendStringInfoString(&buf, ");"); statements = lappend(statements, pstrdup(buf.data)); } @@ -819,8 +838,13 @@ pg_get_database_ddl_internal(Oid dbid, bool pretty, append_ddl_option(&buf, pretty, 4, "ICU_RULES = %s", quote_literal_cstr(TextDatumGetCString(datum))); - /* TABLESPACE */ - if (!no_tablespace && OidIsValid(dbform->dattablespace)) + /* + * TABLESPACE. Skip the default tablespace. Compare by OID: tablespace + * names are case-sensitive, so a user-defined "PG_DEFAULT" is a + * different, valid tablespace. + */ + if (!no_tablespace && OidIsValid(dbform->dattablespace) && + dbform->dattablespace != DEFAULTTABLESPACE_OID) { char *spcname = get_tablespace_name(dbform->dattablespace); @@ -831,9 +855,8 @@ pg_get_database_ddl_internal(Oid dbid, bool pretty, dbform->dattablespace), errdetail("It may have been concurrently dropped."))); - if (pg_strcasecmp(spcname, "pg_default") != 0) - append_ddl_option(&buf, pretty, 4, "TABLESPACE = %s", - quote_identifier(spcname)); + append_ddl_option(&buf, pretty, 4, "TABLESPACE = %s", + quote_identifier(spcname)); } appendStringInfoChar(&buf, ';'); diff --git a/src/backend/utils/adt/ruleutils.c b/src/backend/utils/adt/ruleutils.c index f42263bf9c9..390e11a642a 100644 --- a/src/backend/utils/adt/ruleutils.c +++ b/src/backend/utils/adt/ruleutils.c @@ -542,7 +542,7 @@ static void add_cast_to(StringInfo buf, Oid typid); static char *generate_qualified_type_name(Oid typid); static text *string_to_text(char *str); static char *flatten_reloptions(Oid relid); -void get_reloptions(StringInfo buf, Datum reloptions); +static void get_reloptions(StringInfo buf, Datum reloptions); static void get_json_path_spec(Node *path_spec, deparse_context *context, bool showimplicit); static void get_json_table_columns(TableFunc *tf, JsonTablePathScan *scan, @@ -13821,7 +13821,7 @@ string_to_text(char *str) /* * Generate a C string representing a relation options from text[] datum. */ -void +static void get_reloptions(StringInfo buf, Datum reloptions) { Datum *options; diff --git a/src/include/utils/ruleutils.h b/src/include/utils/ruleutils.h index 25c05e2f649..059e6474f3b 100644 --- a/src/include/utils/ruleutils.h +++ b/src/include/utils/ruleutils.h @@ -51,7 +51,6 @@ extern char *get_window_frame_options_for_explain(int frameOptions, extern char *generate_collation_name(Oid collid); extern char *generate_opclass_name(Oid opclass); extern char *get_range_partbound_string(List *bound_datums); -extern void get_reloptions(StringInfo buf, Datum reloptions); extern char *pg_get_statisticsobjdef_string(Oid statextid); -- 2.43.0
v6-0003-pg_get_role_ddl-pg_get_tablespace_ddl-pg_get_data.patch (text/x-patch, 7.6K) download From f21ade63e94d94653f030ff8e176856486a26c9c Mon Sep 17 00:00:00 2001 From: Andrew Dunstan <andrew@dunslane.net> Date: Thu, 10 Sep 2026 11:09:49 -0400 Subject: [PATCH v6 3/5] pg_get_role_ddl, pg_get_tablespace_ddl, pg_get_database_ddl: allow suppressing IN DATABASE settings, fix concurrent-drop races Add in_database_settings (default true) to pg_get_role_ddl(), so a caller assembling a role's DDL before any database exists can ask for just the role-wide ALTER ROLE SET statements, without the IN DATABASE ones that depend on the database already existing. Fix a concurrent-drop race shared by all three functions: each looked up its target by OID, then made later catalog scans keyed by that OID without holding a lock in between. A concurrent DROP after the lookup left those scans finding no rows -- since DROP cleans up dependents too -- so the function silently returned an incomplete result instead of erroring. Fix by calling shdepLockAndCheckObject() right after the initial lookup, in all three functions. Reported-by: Noah Misch <noah@leadboat.com> Reported-by: Japin Li <japinli@hotmail.com> Discussion: https://postgr.es/m/20260827015242.54.noahmisch@microsoft.com Discussion: https://postgr.es/m/MEAPR01MB3031C47538F35A6C25B20DA5B682A@MEAPR01MB3031.ausprd01.prod.outlook.com --- src/backend/utils/adt/ddlutils.c | 49 ++++++++++++++++++++++++-------- src/include/catalog/pg_proc.dat | 8 +++--- 2 files changed, 41 insertions(+), 16 deletions(-) diff --git a/src/backend/utils/adt/ddlutils.c b/src/backend/utils/adt/ddlutils.c index 8343cc5614f..64258776bb8 100644 --- a/src/backend/utils/adt/ddlutils.c +++ b/src/backend/utils/adt/ddlutils.c @@ -21,6 +21,7 @@ #include "access/genam.h" #include "access/htup_details.h" #include "access/table.h" +#include "catalog/dependency.h" #include "catalog/pg_auth_members.h" #include "catalog/pg_authid.h" #include "catalog/pg_collation.h" @@ -50,7 +51,8 @@ static void append_ddl_option(StringInfo buf, bool pretty, int indent, static void append_guc_value(StringInfo buf, const char *name, const char *value); static List *pg_get_role_ddl_internal(Oid roleid, bool pretty, - bool memberships, bool password); + bool memberships, bool password, + bool in_database_settings); static List *pg_get_tablespace_ddl_internal(Oid tsid, bool pretty, bool no_owner); static Datum pg_get_tablespace_ddl_srf(FunctionCallInfo fcinfo, Oid tsid); static List *pg_get_database_ddl_internal(Oid dbid, bool pretty, @@ -139,16 +141,13 @@ append_guc_value(StringInfo buf, const char *name, const char *value) * Generate DDL statements to recreate a role * * Returns a List of palloc'd strings, each being a complete SQL statement. - * The first two list elements are always the CREATE ROLE statement and an - * ALTER ROLE statement carrying the role attributes; subsequent elements are - * ALTER ROLE SET statements for any role-specific or role-in-database - * configuration settings. If memberships is true, GRANT statements for - * role memberships are appended. If password is false, the PASSWORD - * clause is omitted. + * The first two elements are the CREATE ROLE statement and an ALTER ROLE + * carrying the attributes; the rest are ALTER ROLE SET statements, plus + * GRANT statements for memberships if requested. */ static List * pg_get_role_ddl_internal(Oid roleid, bool pretty, bool memberships, - bool password) + bool password, bool in_database_settings) { HeapTuple tuple; Form_pg_authid roleform; @@ -171,6 +170,12 @@ pg_get_role_ddl_internal(Oid roleid, bool pretty, bool memberships, roleform = (Form_pg_authid) GETSTRUCT(tuple); rolname = pstrdup(NameStr(roleform->rolname)); + /* + * Lock and re-verify existence, closing the window for a concurrent + * DROP ROLE before the scans below. + */ + shdepLockAndCheckObject(AuthIdRelationId, roleid); + /* * rolpassword needs SELECT on pg_authid; nothing else here is * sensitive, so only check it when the PASSWORD clause is wanted. @@ -314,11 +319,16 @@ pg_get_role_ddl_internal(Oid roleid, bool pretty, bool memberships, /* * If setdatabase is valid, this is a role-in-database setting; - * otherwise it's a role-wide setting. Look up the database name once - * for all settings in this row. + * otherwise it's a role-wide setting. In-database settings depend on + * that database already existing, so they're optional; role-wide ones + * are not. Look up the database name once for all settings in this + * row. */ if (OidIsValid(datid)) { + if (!in_database_settings) + continue; + datname = get_database_name(datid); /* Database has been dropped; skip all settings in this row. */ if (datname == NULL) @@ -471,6 +481,7 @@ pg_get_role_ddl(PG_FUNCTION_ARGS) bool pretty; bool memberships; bool password; + bool in_database_settings; funcctx = SRF_FIRSTCALL_INIT(); oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx); @@ -479,9 +490,10 @@ pg_get_role_ddl(PG_FUNCTION_ARGS) pretty = PG_GETARG_BOOL(1); memberships = PG_GETARG_BOOL(2); password = PG_GETARG_BOOL(3); + in_database_settings = PG_GETARG_BOOL(4); statements = pg_get_role_ddl_internal(roleid, pretty, memberships, - password); + password, in_database_settings); funcctx->user_fctx = statements; funcctx->max_calls = list_length(statements); @@ -537,7 +549,14 @@ pg_get_tablespace_ddl_internal(Oid tsid, bool pretty, bool no_owner) tspForm = (Form_pg_tablespace) GETSTRUCT(tuple); spcname = pstrdup(NameStr(tspForm->spcname)); - /* User must have SELECT privilege on pg_tablespace. */ + /* Guard against a concurrent DROP TABLESPACE, as for roles/databases. */ + shdepLockAndCheckObject(TableSpaceRelationId, tsid); + + /* + * User must have SELECT privilege on pg_tablespace. As in + * pg_get_role_ddl_internal(), the error below names the tablespace, not + * pg_tablespace, for the same reason. + */ if (pg_class_aclcheck(TableSpaceRelationId, GetUserId(), ACL_SELECT) != ACLCHECK_OK) { ReleaseSysCache(tuple); @@ -744,6 +763,12 @@ pg_get_database_ddl_internal(Oid dbid, bool pretty, dbform = (Form_pg_database) GETSTRUCT(tuple); dbname = pstrdup(NameStr(dbform->datname)); + /* + * Lock and re-verify existence, closing the window for a concurrent + * DROP DATABASE before the scan below. + */ + shdepLockAndCheckObject(DatabaseRelationId, dbid); + /* * Reject invalid databases. Deparsing a pg_database row in invalid state * can produce SQL that is not executable, such as CONNECTION LIMIT = -2. diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat index 9595e21b3eb..4db14a008ba 100644 --- a/src/include/catalog/pg_proc.dat +++ b/src/include/catalog/pg_proc.dat @@ -8669,10 +8669,10 @@ proargtypes => 'oid bool', prosrc => 'pg_get_constraintdef_ext' }, { oid => '6501', descr => 'get DDL to recreate a role', proname => 'pg_get_role_ddl', prorows => '10', proretset => 't', - provolatile => 's', pronargdefaults => '3', prorettype => 'text', - proargtypes => 'regrole bool bool bool', - proargnames => '{role,pretty,memberships,password}', - proargdefaults => '{false,true,true}', prosrc => 'pg_get_role_ddl' }, + provolatile => 's', pronargdefaults => '4', prorettype => 'text', + proargtypes => 'regrole bool bool bool bool', + proargnames => '{role,pretty,memberships,password,in_database_settings}', + proargdefaults => '{false,true,true,true}', prosrc => 'pg_get_role_ddl' }, { oid => '6499', descr => 'get DDL to recreate a tablespace', proname => 'pg_get_tablespace_ddl', prorows => '10', proretset => 't', provolatile => 's', pronargdefaults => '2', prorettype => 'text', -- 2.43.0
v6-0004-ddlutils-refactor-for-maintainability.patch (text/x-patch, 18.0K) download From 8963060e3ab0987dafa97a891c88c2354be70e66 Mon Sep 17 00:00:00 2001 From: Andrew Dunstan <andrew@dunslane.net> Date: Thu, 10 Sep 2026 11:13:02 -0400 Subject: [PATCH v6 4/5] ddlutils: refactor for maintainability Factor out push_statement() for the repeated "append buf to the statements list, then reset buf" pattern, and one ddl_statements_srf() driver shared by all three SRFs, replacing three copies of the same boilerplate. Use timestamptz_to_str() for VALID UNTIL instead of a hand-rolled duplicate of its ISO-style formatting. Reorder each function's permission check before its object lock: a caller who can't see the object has no business locking it. No behavior change. Discussion: https://postgr.es/m/20260827015242.54.noahmisch@microsoft.com Discussion: https://postgr.es/m/ia2gifmcdsiunj3j6i4yumnnzru45nvet4mxtydb6nodwrvkhe@qkd7lzlxsrht --- src/backend/utils/adt/ddlutils.c | 361 +++++++++++++++---------------- 1 file changed, 176 insertions(+), 185 deletions(-) diff --git a/src/backend/utils/adt/ddlutils.c b/src/backend/utils/adt/ddlutils.c index 64258776bb8..cb457380fab 100644 --- a/src/backend/utils/adt/ddlutils.c +++ b/src/backend/utils/adt/ddlutils.c @@ -35,7 +35,6 @@ #include "miscadmin.h" #include "utils/acl.h" #include "utils/builtins.h" -#include "utils/datetime.h" #include "utils/fmgroids.h" #include "utils/guc.h" #include "utils/lsyscache.h" @@ -50,6 +49,13 @@ static void append_ddl_option(StringInfo buf, bool pretty, int indent, pg_attribute_printf(4, 5); static void append_guc_value(StringInfo buf, const char *name, const char *value); +static void push_statement(List **statements, StringInfo buf); +static Datum ddl_statements_srf(FunctionCallInfo fcinfo, + List *(*getstatements) (void *arg), + void *arg); +static List *get_role_ddl_statements(void *arg); +static List *get_tablespace_ddl_statements(void *arg); +static List *get_database_ddl_statements(void *arg); static List *pg_get_role_ddl_internal(Oid roleid, bool pretty, bool memberships, bool password, bool in_database_settings); @@ -136,6 +142,19 @@ append_guc_value(StringInfo buf, const char *name, const char *value) pfree(rawval); } +/* + * push_statement + * Append the SQL text currently in buf to *statements as a + * separate, complete statement, then reset buf so the caller can + * build the next one. + */ +static void +push_statement(List **statements, StringInfo buf) +{ + *statements = lappend(*statements, pstrdup(buf->data)); + resetStringInfo(buf); +} + /* * pg_get_role_ddl_internal * Generate DDL statements to recreate a role @@ -170,12 +189,6 @@ pg_get_role_ddl_internal(Oid roleid, bool pretty, bool memberships, roleform = (Form_pg_authid) GETSTRUCT(tuple); rolname = pstrdup(NameStr(roleform->rolname)); - /* - * Lock and re-verify existence, closing the window for a concurrent - * DROP ROLE before the scans below. - */ - shdepLockAndCheckObject(AuthIdRelationId, roleid); - /* * rolpassword needs SELECT on pg_authid; nothing else here is * sensitive, so only check it when the PASSWORD clause is wanted. @@ -190,6 +203,12 @@ pg_get_role_ddl_internal(Oid roleid, bool pretty, bool memberships, errmsg("permission denied for role %s", rolname))); } + /* + * Lock and re-verify existence, closing the window for a concurrent + * DROP ROLE before the scans below. + */ + shdepLockAndCheckObject(AuthIdRelationId, roleid); + /* * We don't support generating DDL for system roles. The primary reason * for this is that users shouldn't be recreating them. @@ -207,9 +226,8 @@ pg_get_role_ddl_internal(Oid roleid, bool pretty, bool memberships, * still apply when replayed over a role that already exists. */ appendStringInfo(&buf, "CREATE ROLE %s;", quote_identifier(rolname)); - statements = lappend(statements, pstrdup(buf.data)); + push_statement(&statements, &buf); - resetStringInfo(&buf); appendStringInfo(&buf, "ALTER ROLE %s WITH", quote_identifier(rolname)); /* @@ -264,32 +282,21 @@ pg_get_role_ddl_internal(Oid roleid, bool pretty, bool memberships, &isnull); if (!isnull) { - TimestampTz ts; - int tz; - struct pg_tm tm; - fsec_t fsec; - const char *tzn; - char ts_str[MAXDATELEN + 1]; - - ts = DatumGetTimestampTz(rolevaliduntil); - if (TIMESTAMP_NOT_FINITE(ts)) - EncodeSpecialTimestamp(ts, ts_str); - else if (timestamp2tm(ts, &tz, &tm, &fsec, &tzn, NULL) == 0) - EncodeDateTime(&tm, fsec, true, tz, tzn, USE_ISO_DATES, ts_str); - else - ereport(ERROR, - (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE), - errmsg("timestamp out of range"))); - + /* + * timestamptz_to_str() already formats in ISO style regardless of the + * session's DateStyle, which is what we want here: the output must + * parse the same in any receiving session. timestamptz_out() is not + * a substitute -- it honors DateStyle. + */ append_ddl_option(&buf, pretty, 4, "VALID UNTIL %s", - quote_literal_cstr(ts_str)); + quote_literal_cstr(timestamptz_to_str(DatumGetTimestampTz(rolevaliduntil)))); } ReleaseSysCache(tuple); appendStringInfoChar(&buf, ';'); - statements = lappend(statements, pstrdup(buf.data)); + push_statement(&statements, &buf); /* * Now scan pg_db_role_setting for ALTER ROLE SET configurations. @@ -366,7 +373,6 @@ pg_get_role_ddl_internal(Oid roleid, bool pretty, bool memberships, *p++ = '\0'; /* Build a fresh ALTER ROLE statement for this setting */ - resetStringInfo(&buf); appendStringInfo(&buf, "ALTER ROLE %s", quote_identifier(rolname)); if (datname != NULL) @@ -380,7 +386,7 @@ pg_get_role_ddl_internal(Oid roleid, bool pretty, bool memberships, appendStringInfoChar(&buf, ';'); - statements = lappend(statements, pstrdup(buf.data)); + push_statement(&statements, &buf); pfree(s); } @@ -426,7 +432,6 @@ pg_get_role_ddl_internal(Oid roleid, bool pretty, bool memberships, granted_role = GetUserNameFromId(memform->roleid, false); grantor = GetUserNameFromId(memform->grantor, false); - resetStringInfo(&buf); appendStringInfo(&buf, "GRANT %s TO %s", quote_identifier(granted_role), quote_identifier(rolname)); @@ -439,9 +444,9 @@ pg_get_role_ddl_internal(Oid roleid, bool pretty, bool memberships, /* Self-grants wait for the grant that gave ADMIN OPTION. */ if (memform->grantor == roleid) - self_granted = lappend(self_granted, pstrdup(buf.data)); + push_statement(&self_granted, &buf); else - statements = lappend(statements, pstrdup(buf.data)); + push_statement(&statements, &buf); pfree(granted_role); pfree(grantor); @@ -459,63 +464,83 @@ pg_get_role_ddl_internal(Oid roleid, bool pretty, bool memberships, return statements; } +/* + * ddl_statements_srf + * Shared SRF driver for the pg_get_*_ddl() family. + * + * getstatements(arg) is called once, returning a List of palloc'd + * statement strings; subsequent calls stream it out one row per call. + */ +static Datum +ddl_statements_srf(FunctionCallInfo fcinfo, + List *(*getstatements) (void *arg), + void *arg) +{ + FuncCallContext *funcctx; + List *statements; + + if (SRF_IS_FIRSTCALL()) + { + MemoryContext oldcontext; + + funcctx = SRF_FIRSTCALL_INIT(); + oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx); + + statements = getstatements(arg); + funcctx->user_fctx = statements; + funcctx->max_calls = list_length(statements); + + MemoryContextSwitchTo(oldcontext); + } + + funcctx = SRF_PERCALL_SETUP(); + statements = (List *) funcctx->user_fctx; + + if (funcctx->call_cntr < funcctx->max_calls) + { + char *stmt = (char *) list_nth(statements, funcctx->call_cntr); + + SRF_RETURN_NEXT(funcctx, CStringGetTextDatum(stmt)); + } + + list_free_deep(statements); + SRF_RETURN_DONE(funcctx); +} + +struct RoleDdlArgs +{ + Oid roleid; + bool pretty; + bool memberships; + bool password; + bool in_database_settings; +}; + +static List * +get_role_ddl_statements(void *arg) +{ + struct RoleDdlArgs *a = (struct RoleDdlArgs *) arg; + + return pg_get_role_ddl_internal(a->roleid, a->pretty, a->memberships, + a->password, a->in_database_settings); +} + /* * pg_get_role_ddl * Return DDL to recreate a role as a set of text rows. - * - * Each row is a complete SQL statement. The first two rows are always the - * CREATE ROLE statement and the ALTER ROLE statement carrying the role - * attributes; subsequent rows are ALTER ROLE SET statements and optionally - * GRANT statements for role memberships. */ Datum pg_get_role_ddl(PG_FUNCTION_ARGS) { - FuncCallContext *funcctx; - List *statements; + struct RoleDdlArgs args; - if (SRF_IS_FIRSTCALL()) - { - MemoryContext oldcontext; - Oid roleid; - bool pretty; - bool memberships; - bool password; - bool in_database_settings; + args.roleid = PG_GETARG_OID(0); + args.pretty = PG_GETARG_BOOL(1); + args.memberships = PG_GETARG_BOOL(2); + args.password = PG_GETARG_BOOL(3); + args.in_database_settings = PG_GETARG_BOOL(4); - funcctx = SRF_FIRSTCALL_INIT(); - oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx); - - roleid = PG_GETARG_OID(0); - pretty = PG_GETARG_BOOL(1); - memberships = PG_GETARG_BOOL(2); - password = PG_GETARG_BOOL(3); - in_database_settings = PG_GETARG_BOOL(4); - - statements = pg_get_role_ddl_internal(roleid, pretty, memberships, - password, in_database_settings); - funcctx->user_fctx = statements; - funcctx->max_calls = list_length(statements); - - MemoryContextSwitchTo(oldcontext); - } - - funcctx = SRF_PERCALL_SETUP(); - statements = (List *) funcctx->user_fctx; - - if (funcctx->call_cntr < funcctx->max_calls) - { - char *stmt; - - stmt = list_nth(statements, funcctx->call_cntr); - - SRF_RETURN_NEXT(funcctx, CStringGetTextDatum(stmt)); - } - else - { - list_free_deep(statements); - SRF_RETURN_DONE(funcctx); - } + return ddl_statements_srf(fcinfo, get_role_ddl_statements, &args); } /* @@ -549,20 +574,20 @@ pg_get_tablespace_ddl_internal(Oid tsid, bool pretty, bool no_owner) tspForm = (Form_pg_tablespace) GETSTRUCT(tuple); spcname = pstrdup(NameStr(tspForm->spcname)); + /* + * Everything this emits is public by default, so what matters is + * catalog SELECT on pg_tablespace, not any object-specific privilege. + */ + if (pg_class_aclcheck(TableSpaceRelationId, GetUserId(), + ACL_SELECT) != ACLCHECK_OK) + { + ReleaseSysCache(tuple); + aclcheck_error(ACLCHECK_NO_PRIV, OBJECT_TABLESPACE, spcname); + } + /* Guard against a concurrent DROP TABLESPACE, as for roles/databases. */ shdepLockAndCheckObject(TableSpaceRelationId, tsid); - /* - * User must have SELECT privilege on pg_tablespace. As in - * pg_get_role_ddl_internal(), the error below names the tablespace, not - * pg_tablespace, for the same reason. - */ - if (pg_class_aclcheck(TableSpaceRelationId, GetUserId(), ACL_SELECT) != ACLCHECK_OK) - { - ReleaseSysCache(tuple); - aclcheck_error(ACLCHECK_NO_PRIV, OBJECT_TABLESPACE, spcname); - } - /* * We don't support generating DDL for system tablespaces. The primary * reason for this is that users shouldn't be recreating them. @@ -608,7 +633,7 @@ pg_get_tablespace_ddl_internal(Oid tsid, bool pretty, bool no_owner) pfree(path); appendStringInfoChar(&buf, ';'); - statements = lappend(statements, pstrdup(buf.data)); + push_statement(&statements, &buf); /* Check for tablespace options */ datum = SysCacheGetAttr(TABLESPACEOID, tuple, @@ -618,7 +643,6 @@ pg_get_tablespace_ddl_internal(Oid tsid, bool pretty, bool no_owner) Datum *options; int noptions; - resetStringInfo(&buf); appendStringInfo(&buf, "ALTER TABLESPACE %s SET (", quote_identifier(spcname)); @@ -640,7 +664,7 @@ pg_get_tablespace_ddl_internal(Oid tsid, bool pretty, bool no_owner) pfree(options); appendStringInfoString(&buf, ");"); - statements = lappend(statements, pstrdup(buf.data)); + push_statement(&statements, &buf); } ReleaseSysCache(tuple); @@ -650,50 +674,36 @@ pg_get_tablespace_ddl_internal(Oid tsid, bool pretty, bool no_owner) return statements; } +struct TablespaceDdlArgs +{ + Oid tsid; + bool pretty; + bool no_owner; +}; + +static List * +get_tablespace_ddl_statements(void *arg) +{ + struct TablespaceDdlArgs *a = (struct TablespaceDdlArgs *) arg; + + return pg_get_tablespace_ddl_internal(a->tsid, a->pretty, a->no_owner); +} + /* - * pg_get_tablespace_ddl_srf - common SRF logic for tablespace DDL + * pg_get_tablespace_ddl_srf + * Extract arguments and hand off to the shared SRF driver; called by + * both the OID- and name-based pg_get_tablespace_ddl() entry points. */ static Datum pg_get_tablespace_ddl_srf(FunctionCallInfo fcinfo, Oid tsid) { - FuncCallContext *funcctx; - List *statements; + struct TablespaceDdlArgs args; - if (SRF_IS_FIRSTCALL()) - { - MemoryContext oldcontext; - bool pretty; - bool no_owner; + args.tsid = tsid; + args.pretty = PG_GETARG_BOOL(1); + args.no_owner = !PG_GETARG_BOOL(2); - funcctx = SRF_FIRSTCALL_INIT(); - oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx); - - pretty = PG_GETARG_BOOL(1); - no_owner = !PG_GETARG_BOOL(2); - - statements = pg_get_tablespace_ddl_internal(tsid, pretty, no_owner); - funcctx->user_fctx = statements; - funcctx->max_calls = list_length(statements); - - MemoryContextSwitchTo(oldcontext); - } - - funcctx = SRF_PERCALL_SETUP(); - statements = (List *) funcctx->user_fctx; - - if (funcctx->call_cntr < funcctx->max_calls) - { - char *stmt; - - stmt = (char *) list_nth(statements, funcctx->call_cntr); - - SRF_RETURN_NEXT(funcctx, CStringGetTextDatum(stmt)); - } - else - { - list_free_deep(statements); - SRF_RETURN_DONE(funcctx); - } + return ddl_statements_srf(fcinfo, get_tablespace_ddl_statements, &args); } /* @@ -754,7 +764,11 @@ pg_get_database_ddl_internal(Oid dbid, bool pretty, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("database with OID %u does not exist", dbid))); - /* User must have connect privilege for target database. */ + /* + * User must have connect privilege for target database. Check this + * before taking any lock below: a caller who can't connect to the + * database has no business holding a lock on it either. + */ aclresult = object_aclcheck(DatabaseRelationId, dbid, GetUserId(), ACL_CONNECT); if (aclresult != ACLCHECK_OK) aclcheck_error(aclresult, OBJECT_DATABASE, @@ -885,45 +899,41 @@ pg_get_database_ddl_internal(Oid dbid, bool pretty, } appendStringInfoChar(&buf, ';'); - statements = lappend(statements, pstrdup(buf.data)); + push_statement(&statements, &buf); /* OWNER */ if (!no_owner && OidIsValid(dbform->datdba)) { char *owner = GetUserNameFromId(dbform->datdba, false); - resetStringInfo(&buf); appendStringInfo(&buf, "ALTER DATABASE %s OWNER TO %s;", quote_identifier(dbname), quote_identifier(owner)); pfree(owner); - statements = lappend(statements, pstrdup(buf.data)); + push_statement(&statements, &buf); } /* CONNECTION LIMIT */ if (dbform->datconnlimit != -1) { - resetStringInfo(&buf); appendStringInfo(&buf, "ALTER DATABASE %s CONNECTION LIMIT = %d;", quote_identifier(dbname), dbform->datconnlimit); - statements = lappend(statements, pstrdup(buf.data)); + push_statement(&statements, &buf); } /* IS_TEMPLATE */ if (dbform->datistemplate) { - resetStringInfo(&buf); appendStringInfo(&buf, "ALTER DATABASE %s IS_TEMPLATE = true;", quote_identifier(dbname)); - statements = lappend(statements, pstrdup(buf.data)); + push_statement(&statements, &buf); } /* ALLOW_CONNECTIONS */ if (!dbform->datallowconn) { - resetStringInfo(&buf); appendStringInfo(&buf, "ALTER DATABASE %s ALLOW_CONNECTIONS = false;", quote_identifier(dbname)); - statements = lappend(statements, pstrdup(buf.data)); + push_statement(&statements, &buf); } ReleaseSysCache(tuple); @@ -984,7 +994,6 @@ pg_get_database_ddl_internal(Oid dbid, bool pretty, } *p++ = '\0'; - resetStringInfo(&buf); appendStringInfo(&buf, "ALTER DATABASE %s SET %s TO ", quote_identifier(dbname), quote_identifier(s)); @@ -993,7 +1002,7 @@ pg_get_database_ddl_internal(Oid dbid, bool pretty, appendStringInfoChar(&buf, ';'); - statements = lappend(statements, pstrdup(buf.data)); + push_statement(&statements, &buf); pfree(s); } @@ -1012,6 +1021,23 @@ pg_get_database_ddl_internal(Oid dbid, bool pretty, return statements; } +struct DatabaseDdlArgs +{ + Oid dbid; + bool pretty; + bool no_owner; + bool no_tablespace; +}; + +static List * +get_database_ddl_statements(void *arg) +{ + struct DatabaseDdlArgs *a = (struct DatabaseDdlArgs *) arg; + + return pg_get_database_ddl_internal(a->dbid, a->pretty, a->no_owner, + a->no_tablespace); +} + /* * pg_get_database_ddl * Return DDL to recreate a database as a set of text rows. @@ -1019,47 +1045,12 @@ pg_get_database_ddl_internal(Oid dbid, bool pretty, Datum pg_get_database_ddl(PG_FUNCTION_ARGS) { - FuncCallContext *funcctx; - List *statements; + struct DatabaseDdlArgs args; - if (SRF_IS_FIRSTCALL()) - { - MemoryContext oldcontext; - Oid dbid; - bool pretty; - bool no_owner; - bool no_tablespace; + args.dbid = PG_GETARG_OID(0); + args.pretty = PG_GETARG_BOOL(1); + args.no_owner = !PG_GETARG_BOOL(2); + args.no_tablespace = !PG_GETARG_BOOL(3); - funcctx = SRF_FIRSTCALL_INIT(); - oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx); - - dbid = PG_GETARG_OID(0); - pretty = PG_GETARG_BOOL(1); - no_owner = !PG_GETARG_BOOL(2); - no_tablespace = !PG_GETARG_BOOL(3); - - statements = pg_get_database_ddl_internal(dbid, pretty, no_owner, - no_tablespace); - funcctx->user_fctx = statements; - funcctx->max_calls = list_length(statements); - - MemoryContextSwitchTo(oldcontext); - } - - funcctx = SRF_PERCALL_SETUP(); - statements = (List *) funcctx->user_fctx; - - if (funcctx->call_cntr < funcctx->max_calls) - { - char *stmt; - - stmt = list_nth(statements, funcctx->call_cntr); - - SRF_RETURN_NEXT(funcctx, CStringGetTextDatum(stmt)); - } - else - { - list_free_deep(statements); - SRF_RETURN_DONE(funcctx); - } + return ddl_statements_srf(fcinfo, get_database_ddl_statements, &args); } -- 2.43.0
v6-0005-pg_get_database_ddl-pg_get_role_ddl-require-catal.patch (text/x-patch, 83.3K) download From 9eaf74ae7919b3ccee051e99a3661301e4eac9c1 Mon Sep 17 00:00:00 2001 From: Andrew Dunstan <andrew@dunslane.net> Date: Thu, 10 Sep 2026 11:15:28 -0400 Subject: [PATCH v6 5/5] pg_get_database_ddl, pg_get_role_ddl: require catalog access matching what's actually public Everything these three functions emit is public by default -- pg_authid is revoked from PUBLIC at initdb, but pg_roles, pg_auth_members, pg_db_role_setting, pg_database, and pg_tablespace keep their default grants. An object-specific privilege like CONNECT on a database doesn't protect anything in the common case, and doesn't handle the case that matters: a site that has hardened catalog access. Alvaro Herrera raised this for pg_get_database_ddl(), where a narrow CONNECT grant let a role get full DDL even after an admin revoked catalog-wide SELECT on pg_database. pg_get_database_ddl(): replace the CONNECT check with SELECT on both pg_database and pg_db_role_setting (the ALTER DATABASE ... SET rows come from the latter). pg_get_role_ddl(): add an unconditional check requiring SELECT on pg_roles, pg_auth_members, and pg_db_role_setting together -- pg_roles alone misses membership and IN DATABASE settings, which it doesn't expose. The existing pg_authid check for the password clause is unchanged. pg_get_tablespace_ddl() already had the right check (pg_class_aclcheck(..., ACL_SELECT)); it was just undocumented. Extend this to catalogs reached only through a name-resolution helper: GetUserNameFromId(), get_tablespace_name(), and get_database_name() all read their catalog directly with no ACL check, so resolving a foreign object's name for display (an owner; a referenced tablespace or database) can disclose that catalog's content even after the checks above pass. Add the matching check before each such lookup: pg_roles before an OWNER clause (twice), pg_database before an IN DATABASE setting's database name, and pg_tablespace before a TABLESPACE clause. No equivalent check is needed for the membership grantor/grantee names in pg_get_role_ddl(), since the pg_roles check above already covers them. Add a "Requires ... privilege" paragraph to the docs for all three functions. Convert test_misc/012_ddlutils.pl's TAP assertions to a pg_regress script; add exact-row-shape checks, IS_TEMPLATE/ALLOW_CONNECTIONS coverage, and permission-check coverage for all of the above, each catalog revoked individually to prove the checks are a real AND. Add t/016_ddlutils_pg_dump_crosscheck.pl, comparing this output against pg_dump/pg_dumpall for the same objects. Discussion: https://postgr.es/m/20260827015242.54.noahmisch@microsoft.com Discussion: https://postgr.es/m/ia2gifmcdsiunj3j6i4yumnnzru45nvet4mxtydb6nodwrvkhe@qkd7lzlxsrht --- doc/src/sgml/func/func-info.sgml | 70 ++- src/backend/utils/adt/ddlutils.c | 124 +++- src/test/modules/test_misc/Makefile | 2 + .../modules/test_misc/expected/ddlutils.out | 579 ++++++++++++++++++ src/test/modules/test_misc/meson.build | 11 +- src/test/modules/test_misc/sql/ddlutils.sql | 382 ++++++++++++ src/test/modules/test_misc/t/012_ddlutils.pl | 341 ----------- .../t/016_ddlutils_pg_dump_crosscheck.pl | 115 ++++ 8 files changed, 1248 insertions(+), 376 deletions(-) create mode 100644 src/test/modules/test_misc/expected/ddlutils.out create mode 100644 src/test/modules/test_misc/sql/ddlutils.sql delete mode 100644 src/test/modules/test_misc/t/012_ddlutils.pl create mode 100644 src/test/modules/test_misc/t/016_ddlutils_pg_dump_crosscheck.pl diff --git a/doc/src/sgml/func/func-info.sgml b/doc/src/sgml/func/func-info.sgml index e56c9a22c42..c7ac3188ddc 100644 --- a/doc/src/sgml/func/func-info.sgml +++ b/doc/src/sgml/func/func-info.sgml @@ -3895,6 +3895,20 @@ acl | {postgres=arwdDxtm/postgres,foo=r/postgres} <literal>OWNER</literal> clause is omitted. When <parameter>tablespace</parameter> is false, the <literal>TABLESPACE</literal> clause is omitted. + </para> + <para> + Requires <literal>SELECT</literal> privilege on both the + <link linkend="catalog-pg-database"><structname>pg_database</structname></link> + and <link linkend="catalog-pg-db-role-setting"><structname>pg_db_role_setting</structname></link> + catalogs, both of which are readable by all roles by default. If + <parameter>owner</parameter> is true (the default), also requires + <literal>SELECT</literal> privilege on + <link linkend="view-pg-roles"><structname>pg_roles</structname></link>, + to name the database's owner. If <parameter>tablespace</parameter> + is true (the default) and the database is not in the default + tablespace, also requires <literal>SELECT</literal> privilege on + <link linkend="catalog-pg-tablespace"><structname>pg_tablespace</structname></link>, + to name the tablespace. </para></entry> </row> <row> @@ -3907,19 +3921,56 @@ acl | {postgres=arwdDxtm/postgres,foo=r/postgres} <optional>, <parameter>pretty</parameter> <type>boolean</type> <literal>DEFAULT</literal> false</optional> <optional>, <parameter>memberships</parameter> <type>boolean</type> + <literal>DEFAULT</literal> true</optional> + <optional>, <parameter>password</parameter> <type>boolean</type> + <literal>DEFAULT</literal> true</optional> + <optional>, <parameter>in_database_settings</parameter> <type>boolean</type> <literal>DEFAULT</literal> true</optional> ) <returnvalue>setof text</returnvalue> </para> <para> Reconstructs the <link linkend="sql-createrole"><command>CREATE ROLE - </command></link> statement and any <link linkend="sql-alterrole"> - <command>ALTER ROLE ... SET</command></link> statements for the given - role. Each statement is returned as a separate row. - Password information is never included in the output. + </command></link> statement for the given role, an <link + linkend="sql-alterrole"><command>ALTER ROLE</command></link> statement + carrying its attributes, and any role-wide <command>ALTER ROLE ... + SET</command> statements. Each statement is returned as a separate + row. If the role has a password, it is included in encrypted form, + exactly as stored in + <link linkend="catalog-pg-authid"><structname>pg_authid</structname></link>. When <parameter>pretty</parameter> is true, the output is pretty-printed. When <parameter>memberships</parameter> is false, <link linkend="sql-grant"><command>GRANT</command></link> statements - for role memberships are omitted. + for role memberships are omitted. When + <parameter>password</parameter> is false, the + <literal>PASSWORD</literal> clause is omitted and the function can be + used by any role. + </para> + <para> + Role-wide <command>ALTER ROLE ... SET</command> statements are + always emitted. <link linkend="sql-alterrole"><command>ALTER + ROLE ... IN DATABASE ... SET</command></link> statements, which + depend on the named database already existing, are also emitted + unless <parameter>in_database_settings</parameter> is false -- + useful when assembling this role's DDL before any database has + been created. + </para> + <para> + Requires <literal>SELECT</literal> privilege on the + <link linkend="view-pg-roles"><structname>pg_roles</structname></link>, + <link linkend="catalog-pg-auth-members"><structname>pg_auth_members</structname></link>, + and <link linkend="catalog-pg-db-role-setting"><structname>pg_db_role_setting</structname></link> + catalogs, all of which are readable by all roles by default. If + <parameter>password</parameter> is true (the default), also + requires <literal>SELECT</literal> privilege on + <link linkend="catalog-pg-authid"><structname>pg_authid</structname></link>, + which is not readable by ordinary roles by default -- pass + <parameter>password</parameter> as false to call this function + without that privilege. If <parameter>in_database_settings</parameter> + is true (the default) and the role has any <command>ALTER ROLE ... + IN DATABASE ... SET</command> settings, also requires + <literal>SELECT</literal> privilege on + <link linkend="catalog-pg-database"><structname>pg_database</structname></link>, + to name the database each such setting applies to. </para></entry> </row> <row> @@ -3953,6 +4004,15 @@ acl | {postgres=arwdDxtm/postgres,foo=r/postgres} returned as a separate row. When <parameter>pretty</parameter> is true, the output is pretty-printed. When <parameter>owner</parameter> is false, the <literal>OWNER</literal> clause is omitted. + </para> + <para> + Requires <literal>SELECT</literal> privilege on the + <link linkend="catalog-pg-tablespace"><structname>pg_tablespace</structname></link> + catalog, which is readable by all roles by default. If + <parameter>owner</parameter> is true (the default), also requires + <literal>SELECT</literal> privilege on + <link linkend="view-pg-roles"><structname>pg_roles</structname></link>, + to name the tablespace's owner. </para></entry> </row> </tbody> diff --git a/src/backend/utils/adt/ddlutils.c b/src/backend/utils/adt/ddlutils.c index cb457380fab..d8e0ade142b 100644 --- a/src/backend/utils/adt/ddlutils.c +++ b/src/backend/utils/adt/ddlutils.c @@ -27,6 +27,7 @@ #include "catalog/pg_collation.h" #include "catalog/pg_database.h" #include "catalog/pg_db_role_setting.h" +#include "catalog/pg_namespace_d.h" #include "catalog/pg_tablespace.h" #include "commands/tablespace.h" #include "common/relpath.h" @@ -179,6 +180,7 @@ pg_get_role_ddl_internal(Oid roleid, bool pretty, bool memberships, ScanKeyData scankey; SysScanDesc scan; List *statements = NIL; + Oid pgroles_relid; tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); if (!HeapTupleIsValid(tuple)) @@ -190,8 +192,28 @@ pg_get_role_ddl_internal(Oid roleid, bool pretty, bool memberships, rolname = pstrdup(NameStr(roleform->rolname)); /* - * rolpassword needs SELECT on pg_authid; nothing else here is - * sensitive, so only check it when the PASSWORD clause is wanted. + * Everything below except the password is public by default -- pg_authid + * is revoked from PUBLIC at initdb, but pg_roles, pg_auth_members, and + * pg_db_role_setting keep their default grants -- so the only thing worth + * checking is whether a site has hardened one of these catalogs. Check + * all three: pg_roles alone misses pg_auth_members (memberships) and + * pg_db_role_setting (settings), neither of which it exposes. + */ + pgroles_relid = get_relname_relid("pg_roles", PG_CATALOG_NAMESPACE); + if (!OidIsValid(pgroles_relid) || + pg_class_aclcheck(pgroles_relid, GetUserId(), ACL_SELECT) != ACLCHECK_OK || + pg_class_aclcheck(AuthMemRelationId, GetUserId(), ACL_SELECT) != ACLCHECK_OK || + pg_class_aclcheck(DbRoleSettingRelationId, GetUserId(), ACL_SELECT) != ACLCHECK_OK) + { + ReleaseSysCache(tuple); + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied for role %s", rolname))); + } + + /* + * rolpassword needs SELECT on pg_authid; nothing else here is sensitive, + * so only check it when the PASSWORD clause is wanted. */ if (password && pg_class_aclcheck(AuthIdRelationId, GetUserId(), @@ -204,8 +226,8 @@ pg_get_role_ddl_internal(Oid roleid, bool pretty, bool memberships, } /* - * Lock and re-verify existence, closing the window for a concurrent - * DROP ROLE before the scans below. + * Lock and re-verify existence, closing the window for a concurrent DROP + * ROLE before the scans below. */ shdepLockAndCheckObject(AuthIdRelationId, roleid); @@ -326,16 +348,22 @@ pg_get_role_ddl_internal(Oid roleid, bool pretty, bool memberships, /* * If setdatabase is valid, this is a role-in-database setting; - * otherwise it's a role-wide setting. In-database settings depend on - * that database already existing, so they're optional; role-wide ones - * are not. Look up the database name once for all settings in this - * row. + * otherwise a role-wide one. In-database settings are optional since + * they depend on that database existing; role-wide ones aren't. + * get_database_name() bypasses ACL checks, so verify pg_database + * access before resolving the name it would disclose. */ if (OidIsValid(datid)) { if (!in_database_settings) continue; + if (pg_class_aclcheck(DatabaseRelationId, GetUserId(), + ACL_SELECT) != ACLCHECK_OK) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied for role %s", rolname))); + datname = get_database_name(datid); /* Database has been dropped; skip all settings in this row. */ if (datname == NULL) @@ -407,9 +435,9 @@ pg_get_role_ddl_internal(Oid roleid, bool pretty, bool memberships, * member = roleid, meaning this role has been granted membership in other * roles. * - * A grantor needs ADMIN OPTION on the granted role already, and the - * only grant of ours that can supply that is a self-grant, so - * self-granted rows must sort last. + * A grantor needs ADMIN OPTION on the granted role already, and the only + * grant of ours that can supply that is a self-grant, so self-granted + * rows must sort last. */ if (memberships) { @@ -575,8 +603,8 @@ pg_get_tablespace_ddl_internal(Oid tsid, bool pretty, bool no_owner) spcname = pstrdup(NameStr(tspForm->spcname)); /* - * Everything this emits is public by default, so what matters is - * catalog SELECT on pg_tablespace, not any object-specific privilege. + * Everything this emits is public by default, so what matters is catalog + * SELECT on pg_tablespace, not any object-specific privilege. */ if (pg_class_aclcheck(TableSpaceRelationId, GetUserId(), ACL_SELECT) != ACLCHECK_OK) @@ -603,9 +631,21 @@ pg_get_tablespace_ddl_internal(Oid tsid, bool pretty, bool no_owner) /* Start building the CREATE TABLESPACE statement */ appendStringInfo(&buf, "CREATE TABLESPACE %s", quote_identifier(spcname)); - /* Add OWNER clause */ + /* + * GetUserNameFromId() bypasses ACL checks, so verify pg_roles access + * before resolving the owner's name. + */ if (!no_owner) { + Oid pgroles_relid = get_relname_relid("pg_roles", PG_CATALOG_NAMESPACE); + + if (!OidIsValid(pgroles_relid) || + pg_class_aclcheck(pgroles_relid, GetUserId(), ACL_SELECT) != ACLCHECK_OK) + { + ReleaseSysCache(tuple); + aclcheck_error(ACLCHECK_NO_PRIV, OBJECT_TABLESPACE, spcname); + } + spcowner = GetUserNameFromId(tspForm->spcowner, false); append_ddl_option(&buf, pretty, 4, "OWNER %s", quote_identifier(spcowner)); @@ -647,8 +687,8 @@ pg_get_tablespace_ddl_internal(Oid tsid, bool pretty, bool no_owner) quote_identifier(spcname)); /* - * Elements are already "name=value", and every option is numeric, - * so emit verbatim, matching pg_dumpall. + * Elements are already "name=value", and every option is numeric, so + * emit verbatim, matching pg_dumpall. */ deconstruct_array_builtin(DatumGetArrayTypeP(datum), TEXTOID, &options, NULL, &noptions); @@ -756,7 +796,6 @@ pg_get_database_ddl_internal(Oid dbid, bool pretty, ScanKeyData scankey[2]; SysScanDesc scan; List *statements = NIL; - AclResult aclresult; tuple = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(dbid)); if (!HeapTupleIsValid(tuple)) @@ -765,21 +804,25 @@ pg_get_database_ddl_internal(Oid dbid, bool pretty, errmsg("database with OID %u does not exist", dbid))); /* - * User must have connect privilege for target database. Check this - * before taking any lock below: a caller who can't connect to the - * database has no business holding a lock on it either. + * Everything this emits is public by default, so check catalog SELECT on + * pg_database and pg_db_role_setting (the SET rows come from the latter). */ - aclresult = object_aclcheck(DatabaseRelationId, dbid, GetUserId(), ACL_CONNECT); - if (aclresult != ACLCHECK_OK) - aclcheck_error(aclresult, OBJECT_DATABASE, + if (pg_class_aclcheck(DatabaseRelationId, GetUserId(), + ACL_SELECT) != ACLCHECK_OK || + pg_class_aclcheck(DbRoleSettingRelationId, GetUserId(), + ACL_SELECT) != ACLCHECK_OK) + { + ReleaseSysCache(tuple); + aclcheck_error(ACLCHECK_NO_PRIV, OBJECT_DATABASE, get_database_name(dbid)); + } dbform = (Form_pg_database) GETSTRUCT(tuple); dbname = pstrdup(NameStr(dbform->datname)); /* - * Lock and re-verify existence, closing the window for a concurrent - * DROP DATABASE before the scan below. + * Lock and re-verify existence, closing the window for a concurrent DROP + * DATABASE before the scan below. */ shdepLockAndCheckObject(DatabaseRelationId, dbid); @@ -880,12 +923,22 @@ pg_get_database_ddl_internal(Oid dbid, bool pretty, /* * TABLESPACE. Skip the default tablespace. Compare by OID: tablespace * names are case-sensitive, so a user-defined "PG_DEFAULT" is a - * different, valid tablespace. + * different, valid tablespace. get_tablespace_name() bypasses ACL + * checks, so verify pg_tablespace access first. */ if (!no_tablespace && OidIsValid(dbform->dattablespace) && dbform->dattablespace != DEFAULTTABLESPACE_OID) { - char *spcname = get_tablespace_name(dbform->dattablespace); + char *spcname; + + if (pg_class_aclcheck(TableSpaceRelationId, GetUserId(), + ACL_SELECT) != ACLCHECK_OK) + { + ReleaseSysCache(tuple); + aclcheck_error(ACLCHECK_NO_PRIV, OBJECT_DATABASE, dbname); + } + + spcname = get_tablespace_name(dbform->dattablespace); if (spcname == NULL) ereport(ERROR, @@ -901,10 +954,23 @@ pg_get_database_ddl_internal(Oid dbid, bool pretty, appendStringInfoChar(&buf, ';'); push_statement(&statements, &buf); - /* OWNER */ + /* + * OWNER. GetUserNameFromId() bypasses ACL checks, so verify pg_roles + * access before resolving the owner's name. + */ if (!no_owner && OidIsValid(dbform->datdba)) { - char *owner = GetUserNameFromId(dbform->datdba, false); + char *owner; + Oid pgroles_relid = get_relname_relid("pg_roles", PG_CATALOG_NAMESPACE); + + if (!OidIsValid(pgroles_relid) || + pg_class_aclcheck(pgroles_relid, GetUserId(), ACL_SELECT) != ACLCHECK_OK) + { + ReleaseSysCache(tuple); + aclcheck_error(ACLCHECK_NO_PRIV, OBJECT_DATABASE, dbname); + } + + owner = GetUserNameFromId(dbform->datdba, false); appendStringInfo(&buf, "ALTER DATABASE %s OWNER TO %s;", quote_identifier(dbname), quote_identifier(owner)); diff --git a/src/test/modules/test_misc/Makefile b/src/test/modules/test_misc/Makefile index fedbef071ef..927ffb83224 100644 --- a/src/test/modules/test_misc/Makefile +++ b/src/test/modules/test_misc/Makefile @@ -1,5 +1,7 @@ # src/test/modules/test_misc/Makefile +REGRESS = ddlutils + TAP_TESTS = 1 EXTRA_INSTALL=src/test/modules/injection_points \ diff --git a/src/test/modules/test_misc/expected/ddlutils.out b/src/test/modules/test_misc/expected/ddlutils.out new file mode 100644 index 00000000000..9a5418b35eb --- /dev/null +++ b/src/test/modules/test_misc/expected/ddlutils.out @@ -0,0 +1,579 @@ +-- +-- pg_get_role_ddl, pg_get_tablespace_ddl, pg_get_database_ddl +-- +-- Converted from t/012_ddlutils.pl: none of its checks actually needed a +-- fresh backend per assertion. +-- +-- Two things need pinning for a deterministic flat expected-output file: +-- SCRAM verifiers (compared as booleans against the live pg_authid value, +-- not printed) and LOCALE_PROVIDER/timezone (pinned explicitly rather than +-- filtered post hoc, as the original TAP test did). +SET timezone = 'UTC'; +SET allow_in_place_tablespaces = true; +-- +-- pg_get_role_ddl +-- +-- Basic role: CREATE ROLE carries just the name; attributes are a +-- separate ALTER ROLE. +CREATE ROLE regress_role_ddl_test1; +SELECT * FROM pg_get_role_ddl('regress_role_ddl_test1'); + pg_get_role_ddl +----------------------------------------------------------------------------------------------------------------------- + CREATE ROLE regress_role_ddl_test1; + ALTER ROLE regress_role_ddl_test1 WITH NOSUPERUSER INHERIT NOCREATEROLE NOCREATEDB NOLOGIN NOREPLICATION NOBYPASSRLS; +(2 rows) + +-- Replaying over an existing role: CREATE fails but the ALTER still +-- applies. Captured into a temp table so each statement replays +-- separately -- a single multi-statement string would abort on the +-- failed CREATE and never reach the ALTER. +CREATE ROLE regress_role_ddl_exists NOLOGIN; +CREATE TEMP TABLE exists_ddl_capture AS + SELECT stmt, ord FROM pg_get_role_ddl('regress_role_ddl_exists') + WITH ORDINALITY AS t(stmt, ord); +ALTER ROLE regress_role_ddl_exists LOGIN CREATEDB; +SELECT stmt FROM exists_ddl_capture ORDER BY ord \gexec +CREATE ROLE regress_role_ddl_exists; +ERROR: role "regress_role_ddl_exists" already exists +ALTER ROLE regress_role_ddl_exists WITH NOSUPERUSER INHERIT NOCREATEROLE NOCREATEDB NOLOGIN NOREPLICATION NOBYPASSRLS; +SELECT rolcanlogin, rolcreatedb FROM pg_roles + WHERE rolname = 'regress_role_ddl_exists'; + rolcanlogin | rolcreatedb +-------------+------------- + f | f +(1 row) + +DROP TABLE exists_ddl_capture; +-- Role with privileges, password, and VALID UNTIL set directly in +-- CREATE ROLE. +CREATE ROLE regress_role_ddl_test2 + LOGIN SUPERUSER CREATEDB CREATEROLE + CONNECTION LIMIT 5 + PASSWORD 'secret' + VALID UNTIL '2030-12-31 23:59:59+00'; +-- Boolean checks, not a printed row, since it also carries PASSWORD. +SELECT stmt ~ 'SUPERUSER' AS has_superuser, + stmt ~ 'CREATEDB' AS has_createdb, + stmt ~ 'CONNECTION LIMIT 5' AS has_connection_limit, + stmt ~ 'VALID UNTIL ''2030-12-31' AS has_valid_until + FROM pg_get_role_ddl('regress_role_ddl_test2') AS t(stmt) + WHERE stmt LIKE 'ALTER ROLE%WITH%'; + has_superuser | has_createdb | has_connection_limit | has_valid_until +---------------+--------------+----------------------+----------------- + t | t | t | t +(1 row) + +-- Role without a password emits no PASSWORD clause. +SELECT NOT EXISTS ( + SELECT 1 FROM pg_get_role_ddl('regress_role_ddl_test1') AS t(stmt) + WHERE stmt LIKE '%PASSWORD%') AS role_without_password_has_no_password_clause; + role_without_password_has_no_password_clause +---------------------------------------------- + t +(1 row) + +-- PASSWORD clause carries the stored verifier, compared as a boolean +-- since it's randomly salted. +SELECT EXISTS ( + SELECT 1 + FROM pg_get_role_ddl('regress_role_ddl_test2') AS t(stmt) + JOIN pg_authid a ON a.rolname = 'regress_role_ddl_test2' + WHERE stmt LIKE '%PASSWORD ' || quote_literal(a.rolpassword) || '%' +) AS password_clause_matches_stored_verifier; + password_clause_matches_stored_verifier +----------------------------------------- + t +(1 row) + +SELECT NOT EXISTS ( + SELECT 1 FROM pg_get_role_ddl('regress_role_ddl_test2') AS t(stmt) + WHERE stmt LIKE '%secret%') AS plaintext_password_not_exposed; + plaintext_password_not_exposed +-------------------------------- + t +(1 row) + +-- password => false suppresses the PASSWORD clause. +SELECT NOT EXISTS ( + SELECT 1 FROM pg_get_role_ddl('regress_role_ddl_test2', password => false) AS t(stmt) + WHERE stmt LIKE '%PASSWORD%') AS password_suppressed; + password_suppressed +--------------------- + t +(1 row) + +-- Role-wide settings (test1 has no password, safe to print directly). +ALTER ROLE regress_role_ddl_test1 SET work_mem TO '256MB'; +ALTER ROLE regress_role_ddl_test1 SET search_path TO myschema, public; +SELECT stmt FROM pg_get_role_ddl('regress_role_ddl_test1') AS t(stmt) + WHERE stmt LIKE '%work_mem%' OR stmt LIKE '%search_path%' + ORDER BY stmt; + stmt +---------------------------------------------------------------------------- + ALTER ROLE regress_role_ddl_test1 SET search_path TO 'myschema', 'public'; + ALTER ROLE regress_role_ddl_test1 SET work_mem TO '256MB'; +(2 rows) + +-- Role with a database-specific setting; LOCALE_PROVIDER pinned for +-- later determinism. +CREATE DATABASE regression_ddlutils_test + TEMPLATE template0 ENCODING 'UTF8' LOCALE_PROVIDER libc + LC_COLLATE 'C' LC_CTYPE 'C'; +ALTER ROLE regress_role_ddl_test2 + IN DATABASE regression_ddlutils_test SET work_mem TO '128MB'; +-- No PASSWORD clause on this row, safe to print directly. +SELECT stmt FROM pg_get_role_ddl('regress_role_ddl_test2') AS t(stmt) + WHERE stmt LIKE '%IN DATABASE%'; + stmt +------------------------------------------------------------------------------------------------- + ALTER ROLE regress_role_ddl_test2 IN DATABASE regression_ddlutils_test SET work_mem TO '128MB'; +(1 row) + +-- Exact-shape check: each statement must be its own row, not +-- concatenated -- this would catch a buffer-reuse bug in +-- push_statement(). +SELECT count(*) AS role_ddl_test2_row_count, + count(*) FILTER (WHERE stmt ~ ';\s*\S') AS role_ddl_test2_rows_with_embedded_statement + FROM pg_get_role_ddl('regress_role_ddl_test2') AS t(stmt); + role_ddl_test2_row_count | role_ddl_test2_rows_with_embedded_statement +--------------------------+--------------------------------------------- + 3 | 0 +(1 row) + +-- in_database_settings => false drops IN DATABASE settings, keeps +-- role-wide ones. +SELECT stmt FROM pg_get_role_ddl('regress_role_ddl_test1', in_database_settings => false) AS t(stmt) + WHERE stmt LIKE '%work_mem%'; + stmt +------------------------------------------------------------ + ALTER ROLE regress_role_ddl_test1 SET work_mem TO '256MB'; +(1 row) + +SELECT NOT EXISTS ( + SELECT 1 FROM pg_get_role_ddl('regress_role_ddl_test2', in_database_settings => false) AS t(stmt) + WHERE stmt LIKE '%IN DATABASE%') AS in_database_settings_false_suppresses_in_database; + in_database_settings_false_suppresses_in_database +--------------------------------------------------- + t +(1 row) + +-- Role with special characters (requires quoting). +CREATE ROLE "regress_role-with-dash"; +SELECT * FROM pg_get_role_ddl('regress_role-with-dash'); + pg_get_role_ddl +------------------------------------------------------------------------------------------------------------------------- + CREATE ROLE "regress_role-with-dash"; + ALTER ROLE "regress_role-with-dash" WITH NOSUPERUSER INHERIT NOCREATEROLE NOCREATEDB NOLOGIN NOREPLICATION NOBYPASSRLS; +(2 rows) + +-- Pretty-printed; boolean check again since the row carries PASSWORD. +SELECT EXISTS ( + SELECT 1 FROM pg_get_role_ddl('regress_role_ddl_test2', pretty => true) AS t(stmt) + WHERE stmt ~ '\n\s+SUPERUSER') AS pretty_print_indents_attributes; + pretty_print_indents_attributes +--------------------------------- + t +(1 row) + +-- Role with memberships. +CREATE ROLE regress_role_ddl_grantor CREATEROLE; +CREATE ROLE regress_role_ddl_group1; +CREATE ROLE regress_role_ddl_group2; +CREATE ROLE regress_role_ddl_member; +GRANT regress_role_ddl_group1 TO regress_role_ddl_grantor WITH ADMIN TRUE; +GRANT regress_role_ddl_group2 TO regress_role_ddl_grantor WITH ADMIN TRUE; +SET ROLE regress_role_ddl_grantor; +GRANT regress_role_ddl_group1 TO regress_role_ddl_member + WITH INHERIT TRUE, SET FALSE; +GRANT regress_role_ddl_group2 TO regress_role_ddl_member + WITH ADMIN TRUE; +RESET ROLE; +SELECT * FROM pg_get_role_ddl('regress_role_ddl_member'); + pg_get_role_ddl +----------------------------------------------------------------------------------------------------------------------------------------- + CREATE ROLE regress_role_ddl_member; + ALTER ROLE regress_role_ddl_member WITH NOSUPERUSER INHERIT NOCREATEROLE NOCREATEDB NOLOGIN NOREPLICATION NOBYPASSRLS; + GRANT regress_role_ddl_group1 TO regress_role_ddl_member WITH ADMIN FALSE, INHERIT TRUE, SET FALSE GRANTED BY regress_role_ddl_grantor; + GRANT regress_role_ddl_group2 TO regress_role_ddl_member WITH ADMIN TRUE, INHERIT TRUE, SET TRUE GRANTED BY regress_role_ddl_grantor; +(4 rows) + +-- Membership ordering: a self-grant must come after the grant that +-- gave ADMIN OPTION; the catalog scan's OID order doesn't guarantee +-- that. +CREATE ROLE regress_role_ddl_group3; +CREATE ROLE regress_role_ddl_self; +CREATE ROLE regress_role_ddl_admin CREATEROLE; +GRANT regress_role_ddl_group3 TO regress_role_ddl_admin WITH ADMIN TRUE; +SET ROLE regress_role_ddl_admin; +GRANT regress_role_ddl_group3 TO regress_role_ddl_self WITH ADMIN TRUE; +SET ROLE regress_role_ddl_self; +GRANT regress_role_ddl_group3 TO regress_role_ddl_self WITH INHERIT FALSE; +RESET ROLE; +SELECT (ord_admin IS NOT NULL AND ord_self IS NOT NULL) AS both_membership_grants_emitted, + (ord_admin < ord_self) AS admin_grant_precedes_self_grant + FROM (SELECT min(ord) FILTER (WHERE stmt LIKE '%GRANTED BY regress_role_ddl_admin%') AS ord_admin, + min(ord) FILTER (WHERE stmt LIKE '%GRANTED BY regress_role_ddl_self%') AS ord_self + FROM pg_get_role_ddl('regress_role_ddl_self') WITH ORDINALITY AS t(stmt, ord)) s; + both_membership_grants_emitted | admin_grant_precedes_self_grant +--------------------------------+--------------------------------- + t | t +(1 row) + +-- That order makes the payload replayable; captured for per-statement +-- replay as above. +CREATE TEMP TABLE self_ddl_capture AS + SELECT stmt, ord FROM pg_get_role_ddl('regress_role_ddl_self') + WITH ORDINALITY AS t(stmt, ord); +DROP ROLE regress_role_ddl_self; +SELECT stmt FROM self_ddl_capture ORDER BY ord \gexec +CREATE ROLE regress_role_ddl_self; +ALTER ROLE regress_role_ddl_self WITH NOSUPERUSER INHERIT NOCREATEROLE NOCREATEDB NOLOGIN NOREPLICATION NOBYPASSRLS; +GRANT regress_role_ddl_group3 TO regress_role_ddl_self WITH ADMIN TRUE, INHERIT TRUE, SET TRUE GRANTED BY regress_role_ddl_admin; +GRANT regress_role_ddl_group3 TO regress_role_ddl_self WITH ADMIN FALSE, INHERIT FALSE, SET TRUE GRANTED BY regress_role_ddl_self; +DROP TABLE self_ddl_capture; +-- memberships => false suppresses GRANT statements. +SELECT NOT EXISTS ( + SELECT 1 FROM pg_get_role_ddl('regress_role_ddl_member', memberships => false) AS t(stmt) + WHERE stmt LIKE '%GRANT%') AS memberships_suppressed; + memberships_suppressed +------------------------ + t +(1 row) + +-- Non-existent role errors. +SELECT * FROM pg_get_role_ddl(9999999::oid); +ERROR: role with OID 9999999 does not exist +-- NULL input returns no rows. +SELECT count(*) FROM pg_get_role_ddl(NULL); + count +------- + 0 +(1 row) + +-- Needs SELECT on pg_authid even for a passwordless role, to determine +-- password status. +CREATE ROLE regress_role_ddl_noaccess; +REVOKE SELECT ON pg_authid FROM PUBLIC; +SET ROLE regress_role_ddl_noaccess; +SELECT * FROM pg_get_role_ddl('regress_role_ddl_test1'); +ERROR: permission denied for role regress_role_ddl_test1 +RESET ROLE; +-- password => false needs no pg_authid access; everything else is +-- public via pg_roles/pg_auth_members/pg_db_role_setting. +SET ROLE regress_role_ddl_noaccess; +SELECT * FROM pg_get_role_ddl('regress_role_ddl_test2', password => false); + pg_get_role_ddl +----------------------------------------------------------------------------------------------------------------------------------------------------------------------- + CREATE ROLE regress_role_ddl_test2; + ALTER ROLE regress_role_ddl_test2 WITH SUPERUSER INHERIT CREATEROLE CREATEDB LOGIN NOREPLICATION NOBYPASSRLS CONNECTION LIMIT 5 VALID UNTIL '2030-12-31 23:59:59+00'; + ALTER ROLE regress_role_ddl_test2 IN DATABASE regression_ddlutils_test SET work_mem TO '128MB'; +(3 rows) + +RESET ROLE; +-- Also requires pg_roles, pg_auth_members, and pg_db_role_setting, +-- unconditionally. Revoke each individually to prove the check is a +-- real AND across all three, not satisfiable by a subset. +REVOKE SELECT ON pg_roles FROM PUBLIC; +SET ROLE regress_role_ddl_noaccess; +SELECT * FROM pg_get_role_ddl('regress_role_ddl_test2', password => false); +ERROR: permission denied for role regress_role_ddl_test2 +RESET ROLE; +GRANT SELECT ON pg_roles TO PUBLIC; +REVOKE SELECT ON pg_auth_members FROM PUBLIC; +SET ROLE regress_role_ddl_noaccess; +SELECT * FROM pg_get_role_ddl('regress_role_ddl_test2', password => false); +ERROR: permission denied for role regress_role_ddl_test2 +RESET ROLE; +GRANT SELECT ON pg_auth_members TO PUBLIC; +REVOKE SELECT ON pg_db_role_setting FROM PUBLIC; +SET ROLE regress_role_ddl_noaccess; +SELECT * FROM pg_get_role_ddl('regress_role_ddl_test2', password => false); +ERROR: permission denied for role regress_role_ddl_test2 +RESET ROLE; +GRANT SELECT ON pg_db_role_setting TO PUBLIC; +-- Also requires pg_database before an IN DATABASE clause +-- (get_database_name() bypasses ACL checks otherwise). +-- regress_role_ddl_test2 already has an IN DATABASE setting, so this +-- exercises the real path. +REVOKE SELECT ON pg_database FROM PUBLIC; +SET ROLE regress_role_ddl_noaccess; +SELECT * FROM pg_get_role_ddl('regress_role_ddl_test2', password => false); +ERROR: permission denied for role regress_role_ddl_test2 +RESET ROLE; +GRANT SELECT ON pg_database TO PUBLIC; +-- All catalogs granted: allowed. +SET ROLE regress_role_ddl_noaccess; +SELECT * FROM pg_get_role_ddl('regress_role_ddl_test2', password => false); + pg_get_role_ddl +----------------------------------------------------------------------------------------------------------------------------------------------------------------------- + CREATE ROLE regress_role_ddl_test2; + ALTER ROLE regress_role_ddl_test2 WITH SUPERUSER INHERIT CREATEROLE CREATEDB LOGIN NOREPLICATION NOBYPASSRLS CONNECTION LIMIT 5 VALID UNTIL '2030-12-31 23:59:59+00'; + ALTER ROLE regress_role_ddl_test2 IN DATABASE regression_ddlutils_test SET work_mem TO '128MB'; +(3 rows) + +RESET ROLE; +-- +-- pg_get_database_ddl +-- +ALTER DATABASE regression_ddlutils_test OWNER TO regress_role_ddl_test2; +ALTER DATABASE regression_ddlutils_test CONNECTION LIMIT 123; +ALTER DATABASE regression_ddlutils_test SET random_page_cost = 2.0; +ALTER ROLE regress_role_ddl_test2 + IN DATABASE regression_ddlutils_test SET random_page_cost = 1.1; +-- Non-existent database errors. +SELECT * FROM pg_get_database_ddl('regression_no_such_db'); +ERROR: database "regression_no_such_db" does not exist +LINE 1: SELECT * FROM pg_get_database_ddl('regression_no_such_db'); + ^ +-- NULL input returns no rows. +SELECT count(*) FROM pg_get_database_ddl(NULL); + count +------- + 0 +(1 row) + +-- Invalid option (bad boolean cast) errors. +SELECT * FROM pg_get_database_ddl('regression_ddlutils_test', owner => 'invalid'); +ERROR: invalid input syntax for type boolean: "invalid" +LINE 1: ...database_ddl('regression_ddlutils_test', owner => 'invalid')... + ^ +-- Duplicate named argument errors. +SELECT * FROM pg_get_database_ddl('regression_ddlutils_test', owner => false, owner => true); +ERROR: argument name "owner" used more than once +LINE 1: ...e_ddl('regression_ddlutils_test', owner => false, owner => t... + ^ +-- IS_TEMPLATE/ALLOW_CONNECTIONS coverage; reset immediately so later +-- checks aren't affected. +ALTER DATABASE regression_ddlutils_test IS_TEMPLATE true; +ALTER DATABASE regression_ddlutils_test ALLOW_CONNECTIONS false; +SELECT pg_get_database_ddl FROM pg_get_database_ddl('regression_ddlutils_test'); + pg_get_database_ddl +--------------------------------------------------------------------------------------------------------------------------- + CREATE DATABASE regression_ddlutils_test WITH TEMPLATE = template0 ENCODING = 'UTF8' LOCALE_PROVIDER = libc LOCALE = 'C'; + ALTER DATABASE regression_ddlutils_test OWNER TO regress_role_ddl_test2; + ALTER DATABASE regression_ddlutils_test CONNECTION LIMIT = 123; + ALTER DATABASE regression_ddlutils_test IS_TEMPLATE = true; + ALTER DATABASE regression_ddlutils_test ALLOW_CONNECTIONS = false; + ALTER DATABASE regression_ddlutils_test SET random_page_cost TO '2.0'; +(6 rows) + +ALTER DATABASE regression_ddlutils_test ALLOW_CONNECTIONS true; +ALTER DATABASE regression_ddlutils_test IS_TEMPLATE false; +-- Basic output; LOCALE_PROVIDER above keeps this deterministic. +SELECT pg_get_database_ddl FROM pg_get_database_ddl('regression_ddlutils_test'); + pg_get_database_ddl +--------------------------------------------------------------------------------------------------------------------------- + CREATE DATABASE regression_ddlutils_test WITH TEMPLATE = template0 ENCODING = 'UTF8' LOCALE_PROVIDER = libc LOCALE = 'C'; + ALTER DATABASE regression_ddlutils_test OWNER TO regress_role_ddl_test2; + ALTER DATABASE regression_ddlutils_test CONNECTION LIMIT = 123; + ALTER DATABASE regression_ddlutils_test SET random_page_cost TO '2.0'; +(4 rows) + +-- Exact-shape check: same buffer-reuse concern as pg_get_role_ddl() +-- above. +SELECT count(*) AS database_ddl_row_count, + count(*) FILTER (WHERE pg_get_database_ddl ~ ';\s*\S') AS database_ddl_rows_with_embedded_statement + FROM pg_get_database_ddl('regression_ddlutils_test'); + database_ddl_row_count | database_ddl_rows_with_embedded_statement +------------------------+------------------------------------------- + 4 | 0 +(1 row) + +-- Pretty-printed output, without the default tablespace clause. +SELECT pg_get_database_ddl + FROM pg_get_database_ddl('regression_ddlutils_test', pretty => true, tablespace => false); + pg_get_database_ddl +-------------------------------------------------------------------------- + CREATE DATABASE regression_ddlutils_test + + WITH TEMPLATE = template0 + + ENCODING = 'UTF8' + + LOCALE_PROVIDER = libc + + LOCALE = 'C'; + ALTER DATABASE regression_ddlutils_test OWNER TO regress_role_ddl_test2; + ALTER DATABASE regression_ddlutils_test CONNECTION LIMIT = 123; + ALTER DATABASE regression_ddlutils_test SET random_page_cost TO '2.0'; +(4 rows) + +-- Owner suppressed. +SELECT pg_get_database_ddl + FROM pg_get_database_ddl('regression_ddlutils_test', owner => false); + pg_get_database_ddl +--------------------------------------------------------------------------------------------------------------------------- + CREATE DATABASE regression_ddlutils_test WITH TEMPLATE = template0 ENCODING = 'UTF8' LOCALE_PROVIDER = libc LOCALE = 'C'; + ALTER DATABASE regression_ddlutils_test CONNECTION LIMIT = 123; + ALTER DATABASE regression_ddlutils_test SET random_page_cost TO '2.0'; +(3 rows) + +-- Requires SELECT on both pg_database and pg_db_role_setting (the SET +-- rows come from the latter). +REVOKE SELECT ON pg_database FROM PUBLIC; +SET ROLE regress_role_ddl_noaccess; +SELECT * FROM pg_get_database_ddl('regression_ddlutils_test'); +ERROR: permission denied for database regression_ddlutils_test +RESET ROLE; +GRANT SELECT ON pg_database TO PUBLIC; +-- Reverse case: proves the check is an AND, not an OR either catalog +-- alone would satisfy. +REVOKE SELECT ON pg_db_role_setting FROM PUBLIC; +SET ROLE regress_role_ddl_noaccess; +SELECT * FROM pg_get_database_ddl('regression_ddlutils_test'); +ERROR: permission denied for database regression_ddlutils_test +RESET ROLE; +GRANT SELECT ON pg_db_role_setting TO PUBLIC; +-- Both catalogs readable: allowed. +SET ROLE regress_role_ddl_noaccess; +SELECT * FROM pg_get_database_ddl('regression_ddlutils_test'); + pg_get_database_ddl +--------------------------------------------------------------------------------------------------------------------------- + CREATE DATABASE regression_ddlutils_test WITH TEMPLATE = template0 ENCODING = 'UTF8' LOCALE_PROVIDER = libc LOCALE = 'C'; + ALTER DATABASE regression_ddlutils_test OWNER TO regress_role_ddl_test2; + ALTER DATABASE regression_ddlutils_test CONNECTION LIMIT = 123; + ALTER DATABASE regression_ddlutils_test SET random_page_cost TO '2.0'; +(4 rows) + +RESET ROLE; +-- Also requires pg_roles before the OWNER clause (GetUserNameFromId() +-- bypasses ACL checks otherwise). +REVOKE SELECT ON pg_roles FROM PUBLIC; +SET ROLE regress_role_ddl_noaccess; +SELECT * FROM pg_get_database_ddl('regression_ddlutils_test'); +ERROR: permission denied for database regression_ddlutils_test +RESET ROLE; +GRANT SELECT ON pg_roles TO PUBLIC; +-- Also requires pg_tablespace before a non-default TABLESPACE clause. +-- Uses a throwaway database/tablespace since regression_ddlutils_test +-- is in the default tablespace. +CREATE TABLESPACE regress_ddl_tblsp_check LOCATION ''; +CREATE DATABASE regress_ddl_tblsp_check_db + TEMPLATE template0 ENCODING 'UTF8' LOCALE_PROVIDER libc + LC_COLLATE 'C' LC_CTYPE 'C' TABLESPACE regress_ddl_tblsp_check; +-- Owner would otherwise default to whoever runs this script; pin it +-- for determinism. +ALTER DATABASE regress_ddl_tblsp_check_db OWNER TO regress_role_ddl_test1; +REVOKE SELECT ON pg_tablespace FROM PUBLIC; +SET ROLE regress_role_ddl_noaccess; +SELECT * FROM pg_get_database_ddl('regress_ddl_tblsp_check_db'); +ERROR: permission denied for database regress_ddl_tblsp_check_db +RESET ROLE; +GRANT SELECT ON pg_tablespace TO PUBLIC; +SET ROLE regress_role_ddl_noaccess; +SELECT * FROM pg_get_database_ddl('regress_ddl_tblsp_check_db'); + pg_get_database_ddl +------------------------------------------------------------------------------------------------------------------------------------------------------------------ + CREATE DATABASE regress_ddl_tblsp_check_db WITH TEMPLATE = template0 ENCODING = 'UTF8' LOCALE_PROVIDER = libc LOCALE = 'C' TABLESPACE = regress_ddl_tblsp_check; + ALTER DATABASE regress_ddl_tblsp_check_db OWNER TO regress_role_ddl_test1; +(2 rows) + +RESET ROLE; +DROP DATABASE regress_ddl_tblsp_check_db; +DROP TABLESPACE regress_ddl_tblsp_check; +-- +-- pg_get_tablespace_ddl +-- +-- Non-existent tablespace by name and by OID both error. +SELECT * FROM pg_get_tablespace_ddl('regress_nonexistent_tblsp'); +ERROR: tablespace "regress_nonexistent_tblsp" does not exist +SELECT * FROM pg_get_tablespace_ddl(0::oid); +ERROR: tablespace with OID 0 does not exist +-- NULL input (name and OID variants) returns no rows. +SELECT count(*) FROM pg_get_tablespace_ddl(NULL::name); + count +------- + 0 +(1 row) + +SELECT count(*) FROM pg_get_tablespace_ddl(NULL::oid); + count +------- + 0 +(1 row) + +-- Tablespace name requiring quoting. +CREATE TABLESPACE "regress_ tblsp" OWNER regress_role_ddl_test1 + LOCATION ''; +SELECT * FROM pg_get_tablespace_ddl('regress_ tblsp'); + pg_get_tablespace_ddl +------------------------------------------------------------------------------ + CREATE TABLESPACE "regress_ tblsp" OWNER regress_role_ddl_test1 LOCATION ''; +(1 row) + +-- Rename and add options; reuse for remaining tests. +ALTER TABLESPACE "regress_ tblsp" RENAME TO regress_allopt_tblsp; +ALTER TABLESPACE regress_allopt_tblsp + SET (seq_page_cost = '1.5', random_page_cost = '1.1234567890', + effective_io_concurrency = '17', maintenance_io_concurrency = '18'); +-- Tablespace with multiple options. +SELECT * FROM pg_get_tablespace_ddl('regress_allopt_tblsp'); + pg_get_tablespace_ddl +----------------------------------------------------------------------------------------------------------------------------------------------------------- + CREATE TABLESPACE regress_allopt_tblsp OWNER regress_role_ddl_test1 LOCATION ''; + ALTER TABLESPACE regress_allopt_tblsp SET (seq_page_cost=1.5, random_page_cost=1.1234567890, effective_io_concurrency=17, maintenance_io_concurrency=18); +(2 rows) + +-- Exact-shape check: same buffer-reuse concern as above. +SELECT count(*) AS tablespace_ddl_row_count, + count(*) FILTER (WHERE pg_get_tablespace_ddl ~ ';\s*\S') AS tablespace_ddl_rows_with_embedded_statement + FROM pg_get_tablespace_ddl('regress_allopt_tblsp'); + tablespace_ddl_row_count | tablespace_ddl_rows_with_embedded_statement +--------------------------+--------------------------------------------- + 2 | 0 +(1 row) + +-- Pretty-printed output. +SELECT * FROM pg_get_tablespace_ddl('regress_allopt_tblsp', pretty => true); + pg_get_tablespace_ddl +----------------------------------------------------------------------------------------------------------------------------------------------------------- + CREATE TABLESPACE regress_allopt_tblsp + + OWNER regress_role_ddl_test1 + + LOCATION ''; + ALTER TABLESPACE regress_allopt_tblsp SET (seq_page_cost=1.5, random_page_cost=1.1234567890, effective_io_concurrency=17, maintenance_io_concurrency=18); +(2 rows) + +-- Owner suppressed. +SELECT * FROM pg_get_tablespace_ddl('regress_allopt_tblsp', owner => false); + pg_get_tablespace_ddl +----------------------------------------------------------------------------------------------------------------------------------------------------------- + CREATE TABLESPACE regress_allopt_tblsp LOCATION ''; + ALTER TABLESPACE regress_allopt_tblsp SET (seq_page_cost=1.5, random_page_cost=1.1234567890, effective_io_concurrency=17, maintenance_io_concurrency=18); +(2 rows) + +-- Lookup by OID. +SELECT pg_get_tablespace_ddl + FROM pg_get_tablespace_ddl( + (SELECT oid FROM pg_tablespace WHERE spcname = 'regress_allopt_tblsp')); + pg_get_tablespace_ddl +----------------------------------------------------------------------------------------------------------------------------------------------------------- + CREATE TABLESPACE regress_allopt_tblsp OWNER regress_role_ddl_test1 LOCATION ''; + ALTER TABLESPACE regress_allopt_tblsp SET (seq_page_cost=1.5, random_page_cost=1.1234567890, effective_io_concurrency=17, maintenance_io_concurrency=18); +(2 rows) + +-- Requires catalog-wide SELECT on pg_tablespace. +REVOKE SELECT ON pg_tablespace FROM PUBLIC; +SET ROLE regress_role_ddl_noaccess; +SELECT * FROM pg_get_tablespace_ddl('regress_allopt_tblsp'); +ERROR: permission denied for tablespace regress_allopt_tblsp +RESET ROLE; +GRANT SELECT ON pg_tablespace TO PUBLIC; +SET ROLE regress_role_ddl_noaccess; +SELECT * FROM pg_get_tablespace_ddl('regress_allopt_tblsp'); + pg_get_tablespace_ddl +----------------------------------------------------------------------------------------------------------------------------------------------------------- + CREATE TABLESPACE regress_allopt_tblsp OWNER regress_role_ddl_test1 LOCATION ''; + ALTER TABLESPACE regress_allopt_tblsp SET (seq_page_cost=1.5, random_page_cost=1.1234567890, effective_io_concurrency=17, maintenance_io_concurrency=18); +(2 rows) + +RESET ROLE; +-- Also requires pg_roles before the OWNER clause. +REVOKE SELECT ON pg_roles FROM PUBLIC; +SET ROLE regress_role_ddl_noaccess; +SELECT * FROM pg_get_tablespace_ddl('regress_allopt_tblsp'); +ERROR: permission denied for tablespace regress_allopt_tblsp +RESET ROLE; +GRANT SELECT ON pg_roles TO PUBLIC; +-- Cleanup. +DROP TABLESPACE regress_allopt_tblsp; +DROP DATABASE regression_ddlutils_test; +DROP ROLE regress_role_ddl_test1, regress_role_ddl_test2, regress_role_ddl_exists, + regress_role_ddl_noaccess, regress_role_ddl_grantor, regress_role_ddl_group1, + regress_role_ddl_group2, regress_role_ddl_member, regress_role_ddl_group3, + regress_role_ddl_self, regress_role_ddl_admin, "regress_role-with-dash"; diff --git a/src/test/modules/test_misc/meson.build b/src/test/modules/test_misc/meson.build index 5d81f5b13be..38c7ea1599c 100644 --- a/src/test/modules/test_misc/meson.build +++ b/src/test/modules/test_misc/meson.build @@ -4,6 +4,15 @@ tests += { 'name': 'test_misc', 'sd': meson.current_source_dir(), 'bd': meson.current_build_dir(), + 'regress': { + 'sql': [ + 'ddlutils', + ], + # The script grants/revokes on shared catalogs (pg_authid) and creates + # objects it doesn't clean up incrementally between statements, so it + # isn't safe to run against a live, persistent, possibly-shared cluster. + 'runningcheck': false, + }, 'tap': { 'env': { 'enable_injection_points': get_option('injection_points') ? 'yes' : 'no', @@ -20,10 +29,10 @@ tests += { 't/009_log_temp_files.pl', 't/010_index_concurrently_upsert.pl', 't/011_lock_stats.pl', - 't/012_ddlutils.pl', 't/013_temp_obj_multisession.pl', 't/014_log_statement_max_length.pl', 't/015_temp_schema_exit_deferrable.pl', + 't/016_ddlutils_pg_dump_crosscheck.pl', ], # The injection points are cluster-wide, so disable installcheck 'runningcheck': false, diff --git a/src/test/modules/test_misc/sql/ddlutils.sql b/src/test/modules/test_misc/sql/ddlutils.sql new file mode 100644 index 00000000000..dde3f50cdb6 --- /dev/null +++ b/src/test/modules/test_misc/sql/ddlutils.sql @@ -0,0 +1,382 @@ +-- +-- pg_get_role_ddl, pg_get_tablespace_ddl, pg_get_database_ddl +-- +-- Converted from t/012_ddlutils.pl: none of its checks actually needed a +-- fresh backend per assertion. +-- +-- Two things need pinning for a deterministic flat expected-output file: +-- SCRAM verifiers (compared as booleans against the live pg_authid value, +-- not printed) and LOCALE_PROVIDER/timezone (pinned explicitly rather than +-- filtered post hoc, as the original TAP test did). +SET timezone = 'UTC'; +SET allow_in_place_tablespaces = true; + +-- +-- pg_get_role_ddl +-- + +-- Basic role: CREATE ROLE carries just the name; attributes are a +-- separate ALTER ROLE. +CREATE ROLE regress_role_ddl_test1; +SELECT * FROM pg_get_role_ddl('regress_role_ddl_test1'); + +-- Replaying over an existing role: CREATE fails but the ALTER still +-- applies. Captured into a temp table so each statement replays +-- separately -- a single multi-statement string would abort on the +-- failed CREATE and never reach the ALTER. +CREATE ROLE regress_role_ddl_exists NOLOGIN; +CREATE TEMP TABLE exists_ddl_capture AS + SELECT stmt, ord FROM pg_get_role_ddl('regress_role_ddl_exists') + WITH ORDINALITY AS t(stmt, ord); +ALTER ROLE regress_role_ddl_exists LOGIN CREATEDB; +SELECT stmt FROM exists_ddl_capture ORDER BY ord \gexec +SELECT rolcanlogin, rolcreatedb FROM pg_roles + WHERE rolname = 'regress_role_ddl_exists'; +DROP TABLE exists_ddl_capture; + +-- Role with privileges, password, and VALID UNTIL set directly in +-- CREATE ROLE. +CREATE ROLE regress_role_ddl_test2 + LOGIN SUPERUSER CREATEDB CREATEROLE + CONNECTION LIMIT 5 + PASSWORD 'secret' + VALID UNTIL '2030-12-31 23:59:59+00'; + +-- Boolean checks, not a printed row, since it also carries PASSWORD. +SELECT stmt ~ 'SUPERUSER' AS has_superuser, + stmt ~ 'CREATEDB' AS has_createdb, + stmt ~ 'CONNECTION LIMIT 5' AS has_connection_limit, + stmt ~ 'VALID UNTIL ''2030-12-31' AS has_valid_until + FROM pg_get_role_ddl('regress_role_ddl_test2') AS t(stmt) + WHERE stmt LIKE 'ALTER ROLE%WITH%'; + +-- Role without a password emits no PASSWORD clause. +SELECT NOT EXISTS ( + SELECT 1 FROM pg_get_role_ddl('regress_role_ddl_test1') AS t(stmt) + WHERE stmt LIKE '%PASSWORD%') AS role_without_password_has_no_password_clause; + +-- PASSWORD clause carries the stored verifier, compared as a boolean +-- since it's randomly salted. +SELECT EXISTS ( + SELECT 1 + FROM pg_get_role_ddl('regress_role_ddl_test2') AS t(stmt) + JOIN pg_authid a ON a.rolname = 'regress_role_ddl_test2' + WHERE stmt LIKE '%PASSWORD ' || quote_literal(a.rolpassword) || '%' +) AS password_clause_matches_stored_verifier; +SELECT NOT EXISTS ( + SELECT 1 FROM pg_get_role_ddl('regress_role_ddl_test2') AS t(stmt) + WHERE stmt LIKE '%secret%') AS plaintext_password_not_exposed; + +-- password => false suppresses the PASSWORD clause. +SELECT NOT EXISTS ( + SELECT 1 FROM pg_get_role_ddl('regress_role_ddl_test2', password => false) AS t(stmt) + WHERE stmt LIKE '%PASSWORD%') AS password_suppressed; + +-- Role-wide settings (test1 has no password, safe to print directly). +ALTER ROLE regress_role_ddl_test1 SET work_mem TO '256MB'; +ALTER ROLE regress_role_ddl_test1 SET search_path TO myschema, public; +SELECT stmt FROM pg_get_role_ddl('regress_role_ddl_test1') AS t(stmt) + WHERE stmt LIKE '%work_mem%' OR stmt LIKE '%search_path%' + ORDER BY stmt; + +-- Role with a database-specific setting; LOCALE_PROVIDER pinned for +-- later determinism. +CREATE DATABASE regression_ddlutils_test + TEMPLATE template0 ENCODING 'UTF8' LOCALE_PROVIDER libc + LC_COLLATE 'C' LC_CTYPE 'C'; +ALTER ROLE regress_role_ddl_test2 + IN DATABASE regression_ddlutils_test SET work_mem TO '128MB'; +-- No PASSWORD clause on this row, safe to print directly. +SELECT stmt FROM pg_get_role_ddl('regress_role_ddl_test2') AS t(stmt) + WHERE stmt LIKE '%IN DATABASE%'; + +-- Exact-shape check: each statement must be its own row, not +-- concatenated -- this would catch a buffer-reuse bug in +-- push_statement(). +SELECT count(*) AS role_ddl_test2_row_count, + count(*) FILTER (WHERE stmt ~ ';\s*\S') AS role_ddl_test2_rows_with_embedded_statement + FROM pg_get_role_ddl('regress_role_ddl_test2') AS t(stmt); + +-- in_database_settings => false drops IN DATABASE settings, keeps +-- role-wide ones. +SELECT stmt FROM pg_get_role_ddl('regress_role_ddl_test1', in_database_settings => false) AS t(stmt) + WHERE stmt LIKE '%work_mem%'; +SELECT NOT EXISTS ( + SELECT 1 FROM pg_get_role_ddl('regress_role_ddl_test2', in_database_settings => false) AS t(stmt) + WHERE stmt LIKE '%IN DATABASE%') AS in_database_settings_false_suppresses_in_database; + +-- Role with special characters (requires quoting). +CREATE ROLE "regress_role-with-dash"; +SELECT * FROM pg_get_role_ddl('regress_role-with-dash'); + +-- Pretty-printed; boolean check again since the row carries PASSWORD. +SELECT EXISTS ( + SELECT 1 FROM pg_get_role_ddl('regress_role_ddl_test2', pretty => true) AS t(stmt) + WHERE stmt ~ '\n\s+SUPERUSER') AS pretty_print_indents_attributes; + +-- Role with memberships. +CREATE ROLE regress_role_ddl_grantor CREATEROLE; +CREATE ROLE regress_role_ddl_group1; +CREATE ROLE regress_role_ddl_group2; +CREATE ROLE regress_role_ddl_member; +GRANT regress_role_ddl_group1 TO regress_role_ddl_grantor WITH ADMIN TRUE; +GRANT regress_role_ddl_group2 TO regress_role_ddl_grantor WITH ADMIN TRUE; +SET ROLE regress_role_ddl_grantor; +GRANT regress_role_ddl_group1 TO regress_role_ddl_member + WITH INHERIT TRUE, SET FALSE; +GRANT regress_role_ddl_group2 TO regress_role_ddl_member + WITH ADMIN TRUE; +RESET ROLE; +SELECT * FROM pg_get_role_ddl('regress_role_ddl_member'); + +-- Membership ordering: a self-grant must come after the grant that +-- gave ADMIN OPTION; the catalog scan's OID order doesn't guarantee +-- that. +CREATE ROLE regress_role_ddl_group3; +CREATE ROLE regress_role_ddl_self; +CREATE ROLE regress_role_ddl_admin CREATEROLE; +GRANT regress_role_ddl_group3 TO regress_role_ddl_admin WITH ADMIN TRUE; +SET ROLE regress_role_ddl_admin; +GRANT regress_role_ddl_group3 TO regress_role_ddl_self WITH ADMIN TRUE; +SET ROLE regress_role_ddl_self; +GRANT regress_role_ddl_group3 TO regress_role_ddl_self WITH INHERIT FALSE; +RESET ROLE; +SELECT (ord_admin IS NOT NULL AND ord_self IS NOT NULL) AS both_membership_grants_emitted, + (ord_admin < ord_self) AS admin_grant_precedes_self_grant + FROM (SELECT min(ord) FILTER (WHERE stmt LIKE '%GRANTED BY regress_role_ddl_admin%') AS ord_admin, + min(ord) FILTER (WHERE stmt LIKE '%GRANTED BY regress_role_ddl_self%') AS ord_self + FROM pg_get_role_ddl('regress_role_ddl_self') WITH ORDINALITY AS t(stmt, ord)) s; + +-- That order makes the payload replayable; captured for per-statement +-- replay as above. +CREATE TEMP TABLE self_ddl_capture AS + SELECT stmt, ord FROM pg_get_role_ddl('regress_role_ddl_self') + WITH ORDINALITY AS t(stmt, ord); +DROP ROLE regress_role_ddl_self; +SELECT stmt FROM self_ddl_capture ORDER BY ord \gexec +DROP TABLE self_ddl_capture; + +-- memberships => false suppresses GRANT statements. +SELECT NOT EXISTS ( + SELECT 1 FROM pg_get_role_ddl('regress_role_ddl_member', memberships => false) AS t(stmt) + WHERE stmt LIKE '%GRANT%') AS memberships_suppressed; + +-- Non-existent role errors. +SELECT * FROM pg_get_role_ddl(9999999::oid); + +-- NULL input returns no rows. +SELECT count(*) FROM pg_get_role_ddl(NULL); + +-- Needs SELECT on pg_authid even for a passwordless role, to determine +-- password status. +CREATE ROLE regress_role_ddl_noaccess; +REVOKE SELECT ON pg_authid FROM PUBLIC; +SET ROLE regress_role_ddl_noaccess; +SELECT * FROM pg_get_role_ddl('regress_role_ddl_test1'); +RESET ROLE; + +-- password => false needs no pg_authid access; everything else is +-- public via pg_roles/pg_auth_members/pg_db_role_setting. +SET ROLE regress_role_ddl_noaccess; +SELECT * FROM pg_get_role_ddl('regress_role_ddl_test2', password => false); +RESET ROLE; + +-- Also requires pg_roles, pg_auth_members, and pg_db_role_setting, +-- unconditionally. Revoke each individually to prove the check is a +-- real AND across all three, not satisfiable by a subset. +REVOKE SELECT ON pg_roles FROM PUBLIC; +SET ROLE regress_role_ddl_noaccess; +SELECT * FROM pg_get_role_ddl('regress_role_ddl_test2', password => false); +RESET ROLE; +GRANT SELECT ON pg_roles TO PUBLIC; + +REVOKE SELECT ON pg_auth_members FROM PUBLIC; +SET ROLE regress_role_ddl_noaccess; +SELECT * FROM pg_get_role_ddl('regress_role_ddl_test2', password => false); +RESET ROLE; +GRANT SELECT ON pg_auth_members TO PUBLIC; + +REVOKE SELECT ON pg_db_role_setting FROM PUBLIC; +SET ROLE regress_role_ddl_noaccess; +SELECT * FROM pg_get_role_ddl('regress_role_ddl_test2', password => false); +RESET ROLE; +GRANT SELECT ON pg_db_role_setting TO PUBLIC; + +-- Also requires pg_database before an IN DATABASE clause +-- (get_database_name() bypasses ACL checks otherwise). +-- regress_role_ddl_test2 already has an IN DATABASE setting, so this +-- exercises the real path. +REVOKE SELECT ON pg_database FROM PUBLIC; +SET ROLE regress_role_ddl_noaccess; +SELECT * FROM pg_get_role_ddl('regress_role_ddl_test2', password => false); +RESET ROLE; +GRANT SELECT ON pg_database TO PUBLIC; + +-- All catalogs granted: allowed. +SET ROLE regress_role_ddl_noaccess; +SELECT * FROM pg_get_role_ddl('regress_role_ddl_test2', password => false); +RESET ROLE; + +-- +-- pg_get_database_ddl +-- + +ALTER DATABASE regression_ddlutils_test OWNER TO regress_role_ddl_test2; +ALTER DATABASE regression_ddlutils_test CONNECTION LIMIT 123; +ALTER DATABASE regression_ddlutils_test SET random_page_cost = 2.0; +ALTER ROLE regress_role_ddl_test2 + IN DATABASE regression_ddlutils_test SET random_page_cost = 1.1; + +-- Non-existent database errors. +SELECT * FROM pg_get_database_ddl('regression_no_such_db'); + +-- NULL input returns no rows. +SELECT count(*) FROM pg_get_database_ddl(NULL); + +-- Invalid option (bad boolean cast) errors. +SELECT * FROM pg_get_database_ddl('regression_ddlutils_test', owner => 'invalid'); + +-- Duplicate named argument errors. +SELECT * FROM pg_get_database_ddl('regression_ddlutils_test', owner => false, owner => true); + +-- IS_TEMPLATE/ALLOW_CONNECTIONS coverage; reset immediately so later +-- checks aren't affected. +ALTER DATABASE regression_ddlutils_test IS_TEMPLATE true; +ALTER DATABASE regression_ddlutils_test ALLOW_CONNECTIONS false; +SELECT pg_get_database_ddl FROM pg_get_database_ddl('regression_ddlutils_test'); +ALTER DATABASE regression_ddlutils_test ALLOW_CONNECTIONS true; +ALTER DATABASE regression_ddlutils_test IS_TEMPLATE false; + +-- Basic output; LOCALE_PROVIDER above keeps this deterministic. +SELECT pg_get_database_ddl FROM pg_get_database_ddl('regression_ddlutils_test'); + +-- Exact-shape check: same buffer-reuse concern as pg_get_role_ddl() +-- above. +SELECT count(*) AS database_ddl_row_count, + count(*) FILTER (WHERE pg_get_database_ddl ~ ';\s*\S') AS database_ddl_rows_with_embedded_statement + FROM pg_get_database_ddl('regression_ddlutils_test'); + +-- Pretty-printed output, without the default tablespace clause. +SELECT pg_get_database_ddl + FROM pg_get_database_ddl('regression_ddlutils_test', pretty => true, tablespace => false); + +-- Owner suppressed. +SELECT pg_get_database_ddl + FROM pg_get_database_ddl('regression_ddlutils_test', owner => false); + +-- Requires SELECT on both pg_database and pg_db_role_setting (the SET +-- rows come from the latter). +REVOKE SELECT ON pg_database FROM PUBLIC; +SET ROLE regress_role_ddl_noaccess; +SELECT * FROM pg_get_database_ddl('regression_ddlutils_test'); +RESET ROLE; +GRANT SELECT ON pg_database TO PUBLIC; + +-- Reverse case: proves the check is an AND, not an OR either catalog +-- alone would satisfy. +REVOKE SELECT ON pg_db_role_setting FROM PUBLIC; +SET ROLE regress_role_ddl_noaccess; +SELECT * FROM pg_get_database_ddl('regression_ddlutils_test'); +RESET ROLE; +GRANT SELECT ON pg_db_role_setting TO PUBLIC; + +-- Both catalogs readable: allowed. +SET ROLE regress_role_ddl_noaccess; +SELECT * FROM pg_get_database_ddl('regression_ddlutils_test'); +RESET ROLE; + +-- Also requires pg_roles before the OWNER clause (GetUserNameFromId() +-- bypasses ACL checks otherwise). +REVOKE SELECT ON pg_roles FROM PUBLIC; +SET ROLE regress_role_ddl_noaccess; +SELECT * FROM pg_get_database_ddl('regression_ddlutils_test'); +RESET ROLE; +GRANT SELECT ON pg_roles TO PUBLIC; + +-- Also requires pg_tablespace before a non-default TABLESPACE clause. +-- Uses a throwaway database/tablespace since regression_ddlutils_test +-- is in the default tablespace. +CREATE TABLESPACE regress_ddl_tblsp_check LOCATION ''; +CREATE DATABASE regress_ddl_tblsp_check_db + TEMPLATE template0 ENCODING 'UTF8' LOCALE_PROVIDER libc + LC_COLLATE 'C' LC_CTYPE 'C' TABLESPACE regress_ddl_tblsp_check; +-- Owner would otherwise default to whoever runs this script; pin it +-- for determinism. +ALTER DATABASE regress_ddl_tblsp_check_db OWNER TO regress_role_ddl_test1; +REVOKE SELECT ON pg_tablespace FROM PUBLIC; +SET ROLE regress_role_ddl_noaccess; +SELECT * FROM pg_get_database_ddl('regress_ddl_tblsp_check_db'); +RESET ROLE; +GRANT SELECT ON pg_tablespace TO PUBLIC; +SET ROLE regress_role_ddl_noaccess; +SELECT * FROM pg_get_database_ddl('regress_ddl_tblsp_check_db'); +RESET ROLE; +DROP DATABASE regress_ddl_tblsp_check_db; +DROP TABLESPACE regress_ddl_tblsp_check; + +-- +-- pg_get_tablespace_ddl +-- + +-- Non-existent tablespace by name and by OID both error. +SELECT * FROM pg_get_tablespace_ddl('regress_nonexistent_tblsp'); +SELECT * FROM pg_get_tablespace_ddl(0::oid); + +-- NULL input (name and OID variants) returns no rows. +SELECT count(*) FROM pg_get_tablespace_ddl(NULL::name); +SELECT count(*) FROM pg_get_tablespace_ddl(NULL::oid); + +-- Tablespace name requiring quoting. +CREATE TABLESPACE "regress_ tblsp" OWNER regress_role_ddl_test1 + LOCATION ''; +SELECT * FROM pg_get_tablespace_ddl('regress_ tblsp'); + +-- Rename and add options; reuse for remaining tests. +ALTER TABLESPACE "regress_ tblsp" RENAME TO regress_allopt_tblsp; +ALTER TABLESPACE regress_allopt_tblsp + SET (seq_page_cost = '1.5', random_page_cost = '1.1234567890', + effective_io_concurrency = '17', maintenance_io_concurrency = '18'); + +-- Tablespace with multiple options. +SELECT * FROM pg_get_tablespace_ddl('regress_allopt_tblsp'); + +-- Exact-shape check: same buffer-reuse concern as above. +SELECT count(*) AS tablespace_ddl_row_count, + count(*) FILTER (WHERE pg_get_tablespace_ddl ~ ';\s*\S') AS tablespace_ddl_rows_with_embedded_statement + FROM pg_get_tablespace_ddl('regress_allopt_tblsp'); + +-- Pretty-printed output. +SELECT * FROM pg_get_tablespace_ddl('regress_allopt_tblsp', pretty => true); + +-- Owner suppressed. +SELECT * FROM pg_get_tablespace_ddl('regress_allopt_tblsp', owner => false); + +-- Lookup by OID. +SELECT pg_get_tablespace_ddl + FROM pg_get_tablespace_ddl( + (SELECT oid FROM pg_tablespace WHERE spcname = 'regress_allopt_tblsp')); + +-- Requires catalog-wide SELECT on pg_tablespace. +REVOKE SELECT ON pg_tablespace FROM PUBLIC; +SET ROLE regress_role_ddl_noaccess; +SELECT * FROM pg_get_tablespace_ddl('regress_allopt_tblsp'); +RESET ROLE; +GRANT SELECT ON pg_tablespace TO PUBLIC; +SET ROLE regress_role_ddl_noaccess; +SELECT * FROM pg_get_tablespace_ddl('regress_allopt_tblsp'); +RESET ROLE; + +-- Also requires pg_roles before the OWNER clause. +REVOKE SELECT ON pg_roles FROM PUBLIC; +SET ROLE regress_role_ddl_noaccess; +SELECT * FROM pg_get_tablespace_ddl('regress_allopt_tblsp'); +RESET ROLE; +GRANT SELECT ON pg_roles TO PUBLIC; + +-- Cleanup. +DROP TABLESPACE regress_allopt_tblsp; +DROP DATABASE regression_ddlutils_test; +DROP ROLE regress_role_ddl_test1, regress_role_ddl_test2, regress_role_ddl_exists, + regress_role_ddl_noaccess, regress_role_ddl_grantor, regress_role_ddl_group1, + regress_role_ddl_group2, regress_role_ddl_member, regress_role_ddl_group3, + regress_role_ddl_self, regress_role_ddl_admin, "regress_role-with-dash"; diff --git a/src/test/modules/test_misc/t/012_ddlutils.pl b/src/test/modules/test_misc/t/012_ddlutils.pl deleted file mode 100644 index c4096879922..00000000000 --- a/src/test/modules/test_misc/t/012_ddlutils.pl +++ /dev/null @@ -1,341 +0,0 @@ - -# Copyright (c) 2026, PostgreSQL Global Development Group - -# Tests for pg_get_database_ddl(), pg_get_tablespace_ddl(), and -# pg_get_role_ddl(). These are TAP tests rather than plain regression -# tests because they create databases and tablespaces, which are -# heavyweight operations that should run only once rather than being -# repeated with every invocation of the core regression suite. - -use strict; -use warnings FATAL => 'all'; -use PostgreSQL::Test::Cluster; -use PostgreSQL::Test::Utils; -use Test::More; - -my $node = PostgreSQL::Test::Cluster->new('main'); -$node->init; -# Force UTC so that timestamptz values (e.g. VALID UNTIL) render the same -# way regardless of the host's local timezone. -$node->append_conf('postgresql.conf', "timezone = 'UTC'\n"); -$node->start; - -# Perl helper that strips locale/collation details from DDL output so -# that results are stable across platforms. -sub ddl_filter -{ - my ($text) = @_; - $text =~ s/\s*\bLOCALE_PROVIDER\b\s*=\s*(?:'[^']*'|"[^"]*"|\S+)//gi; - $text =~ s/\s*LC_COLLATE\s*=\s*(['"])[^'"]*\1//gi; - $text =~ s/\s*LC_CTYPE\s*=\s*(['"])[^'"]*\1//gi; - $text =~ s/\s*\S*LOCALE\S*\s*=?\s*(['"])[^'"]*\1//gi; - $text =~ s/\s*\S*COLLATION\S*\s*=?\s*(['"])[^'"]*\1//gi; - return $text; -} - - -######################################################################## -# pg_get_role_ddl tests -######################################################################## - -# Basic role -$node->safe_psql('postgres', 'CREATE ROLE regress_role_ddl_test1'); -my $result = $node->safe_psql('postgres', - q{SELECT * FROM pg_get_role_ddl('regress_role_ddl_test1')}); -like( - $result, - qr/CREATE ROLE regress_role_ddl_test1 .* NOLOGIN/, - 'basic role DDL'); - -# Role with multiple privileges -$node->safe_psql( - 'postgres', q{ - CREATE ROLE regress_role_ddl_test2 - LOGIN SUPERUSER CREATEDB CREATEROLE - CONNECTION LIMIT 5 - VALID UNTIL '2030-12-31 23:59:59+00'}); -$result = $node->safe_psql('postgres', - q{SELECT * FROM pg_get_role_ddl('regress_role_ddl_test2')}); -like($result, qr/SUPERUSER/, 'role with SUPERUSER'); -like($result, qr/CREATEDB/, 'role with CREATEDB'); -like($result, qr/CONNECTION LIMIT 5/, 'role with CONNECTION LIMIT'); -like($result, qr/VALID UNTIL '2030-12-31/, 'role with VALID UNTIL'); - -# Role with configuration parameters -$node->safe_psql( - 'postgres', q{ - ALTER ROLE regress_role_ddl_test1 SET work_mem TO '256MB'; - ALTER ROLE regress_role_ddl_test1 SET search_path TO myschema, public}); -$result = $node->safe_psql('postgres', - q{SELECT * FROM pg_get_role_ddl('regress_role_ddl_test1')}); -like($result, qr/SET work_mem TO '256MB'/, 'role with work_mem setting'); -like($result, qr/SET search_path TO/, 'role with search_path setting'); - -# Role with database-specific configuration (needs a real database) -$node->safe_psql( - 'postgres', q{ - CREATE DATABASE regression_ddlutils_test - TEMPLATE template0 ENCODING 'UTF8' LC_COLLATE 'C' LC_CTYPE 'C'; - ALTER ROLE regress_role_ddl_test2 - IN DATABASE regression_ddlutils_test SET work_mem TO '128MB'}); -$result = $node->safe_psql('postgres', - q{SELECT * FROM pg_get_role_ddl('regress_role_ddl_test2')}); -like( - $result, - qr/IN DATABASE regression_ddlutils_test SET work_mem TO '128MB'/, - 'role with database-specific setting'); - -# Role with special characters (requires quoting) -$node->safe_psql('postgres', q{CREATE ROLE "regress_role-with-dash"}); -$result = $node->safe_psql('postgres', - q{SELECT * FROM pg_get_role_ddl('regress_role-with-dash')}); -like($result, qr/"regress_role-with-dash"/, 'role name requiring quoting'); - -# Pretty-printed output -$result = $node->safe_psql('postgres', - q{SELECT * FROM pg_get_role_ddl('regress_role_ddl_test2', pretty => true)} -); -like($result, qr/\n\s+SUPERUSER/, 'role pretty-print indents attributes'); - -# Role with memberships -$node->safe_psql( - 'postgres', q{ - CREATE ROLE regress_role_ddl_grantor CREATEROLE; - CREATE ROLE regress_role_ddl_group1; - CREATE ROLE regress_role_ddl_group2; - CREATE ROLE regress_role_ddl_member; - GRANT regress_role_ddl_group1 TO regress_role_ddl_grantor WITH ADMIN TRUE; - GRANT regress_role_ddl_group2 TO regress_role_ddl_grantor WITH ADMIN TRUE; - SET ROLE regress_role_ddl_grantor; - GRANT regress_role_ddl_group1 TO regress_role_ddl_member - WITH INHERIT TRUE, SET FALSE; - GRANT regress_role_ddl_group2 TO regress_role_ddl_member - WITH ADMIN TRUE; - RESET ROLE}); -$result = $node->safe_psql('postgres', - q{SELECT * FROM pg_get_role_ddl('regress_role_ddl_member')}); -like( - $result, - qr/GRANT regress_role_ddl_group1 TO regress_role_ddl_member/, - 'role with memberships includes GRANT'); -like($result, qr/SET FALSE/, 'membership includes SET FALSE'); -like($result, qr/ADMIN TRUE/, 'membership includes ADMIN TRUE'); - -# Memberships suppressed -$result = $node->safe_psql('postgres', - q{SELECT * FROM pg_get_role_ddl('regress_role_ddl_member', memberships => false)} -); -unlike($result, qr/GRANT/, 'memberships suppressed'); - -# Non-existent role (should error) -my ($ret, $stdout, $stderr) = - $node->psql('postgres', q{SELECT * FROM pg_get_role_ddl(9999999::oid)}); -isnt($ret, 0, 'non-existent role errors'); -like($stderr, qr/does not exist/, 'non-existent role error message'); - -# NULL input (should return no rows) -$result = - $node->safe_psql('postgres', q{SELECT count(*) FROM pg_get_role_ddl(NULL)}); -is($result, '0', 'NULL role returns no rows'); - -# Permission check: revoke SELECT on pg_authid -$node->safe_psql( - 'postgres', q{ - CREATE ROLE regress_role_ddl_noaccess; - REVOKE SELECT ON pg_authid FROM PUBLIC}); -($ret, $stdout, $stderr) = $node->psql( - 'postgres', - q{SET ROLE regress_role_ddl_noaccess; - SELECT * FROM pg_get_role_ddl('regress_role_ddl_test1')}); -isnt($ret, 0, 'role DDL denied without pg_authid access'); -$node->safe_psql( - 'postgres', q{ - GRANT SELECT ON pg_authid TO PUBLIC}); - - -######################################################################## -# pg_get_database_ddl tests -######################################################################## - -# Set up: the test database was already created above for role tests. -$node->safe_psql( - 'postgres', q{ - ALTER DATABASE regression_ddlutils_test OWNER TO regress_role_ddl_test2; - ALTER DATABASE regression_ddlutils_test CONNECTION LIMIT 123; - ALTER DATABASE regression_ddlutils_test SET random_page_cost = 2.0; - ALTER ROLE regress_role_ddl_test2 - IN DATABASE regression_ddlutils_test SET random_page_cost = 1.1}); - -# Non-existent database -($ret, $stdout, $stderr) = $node->psql('postgres', - q{SELECT * FROM pg_get_database_ddl('regression_no_such_db')}); -isnt($ret, 0, 'non-existent database errors'); - -# NULL input -$result = $node->safe_psql('postgres', - q{SELECT count(*) FROM pg_get_database_ddl(NULL)}); -is($result, '0', 'NULL database returns no rows'); - -# Invalid option (bad boolean cast) -($ret, $stdout, $stderr) = $node->psql('postgres', - q{SELECT * FROM pg_get_database_ddl('regression_ddlutils_test', owner => 'invalid')} -); -isnt($ret, 0, 'invalid boolean option errors'); -like( - $stderr, - qr/invalid input syntax for type boolean/, - 'invalid option error message'); - -# Duplicate named argument -($ret, $stdout, $stderr) = $node->psql( - 'postgres', - q{SELECT * FROM pg_get_database_ddl('regression_ddlutils_test', - owner => false, owner => true)}); -isnt($ret, 0, 'duplicate option errors'); - -# Basic output (without locale details) -$result = ddl_filter( - $node->safe_psql( - 'postgres', - q{SELECT pg_get_database_ddl - FROM pg_get_database_ddl('regression_ddlutils_test')})); -like( - $result, - qr/CREATE DATABASE regression_ddlutils_test/, - 'database DDL includes CREATE'); -like($result, qr/TEMPLATE = template0/, 'database DDL includes TEMPLATE'); -like($result, qr/ENCODING = 'UTF8'/, 'database DDL includes ENCODING'); -like( - $result, - qr/OWNER TO regress_role_ddl_test2/, - 'database DDL includes OWNER'); -like($result, qr/CONNECTION LIMIT = 123/, 'database DDL includes CONNLIMIT'); -like( - $result, - qr/SET random_page_cost TO '2.0'/, - 'database DDL includes GUC setting'); - -# Pretty-printed output -$result = ddl_filter( - $node->safe_psql( - 'postgres', - q{SELECT pg_get_database_ddl - FROM pg_get_database_ddl('regression_ddlutils_test', - pretty => true, tablespace => false)})); -like($result, qr/\n\s+WITH TEMPLATE/, 'database DDL pretty-prints WITH'); - -# Owner suppressed -$result = ddl_filter( - $node->safe_psql( - 'postgres', - q{SELECT pg_get_database_ddl - FROM pg_get_database_ddl('regression_ddlutils_test', owner => false)})); -unlike($result, qr/OWNER/, 'database DDL owner suppressed'); - -# Permission check -$node->safe_psql( - 'postgres', q{ - REVOKE CONNECT ON DATABASE regression_ddlutils_test FROM PUBLIC}); -($ret, $stdout, $stderr) = $node->psql( - 'postgres', - q{SET ROLE regress_role_ddl_noaccess; - SELECT * FROM pg_get_database_ddl('regression_ddlutils_test')}); -isnt($ret, 0, 'database DDL denied without CONNECT'); -$node->safe_psql( - 'postgres', q{ - GRANT CONNECT ON DATABASE regression_ddlutils_test TO PUBLIC}); - - -######################################################################## -# pg_get_tablespace_ddl tests -######################################################################## - -# Non-existent tablespace by name -($ret, $stdout, $stderr) = $node->psql('postgres', - q{SELECT * FROM pg_get_tablespace_ddl('regress_nonexistent_tblsp')}); -isnt($ret, 0, 'non-existent tablespace errors'); - -# Non-existent tablespace by OID -($ret, $stdout, $stderr) = - $node->psql('postgres', q{SELECT * FROM pg_get_tablespace_ddl(0::oid)}); -isnt($ret, 0, 'non-existent tablespace OID errors'); - -# NULL input (name and OID variants) -$result = $node->safe_psql('postgres', - q{SELECT count(*) FROM pg_get_tablespace_ddl(NULL::name)}); -is($result, '0', 'NULL tablespace name returns no rows'); -$result = $node->safe_psql('postgres', - q{SELECT count(*) FROM pg_get_tablespace_ddl(NULL::oid)}); -is($result, '0', 'NULL tablespace OID returns no rows'); - -# Tablespace name requiring quoting -$node->safe_psql( - 'postgres', q{ - SET allow_in_place_tablespaces = true; - CREATE TABLESPACE "regress_ tblsp" OWNER regress_role_ddl_test1 - LOCATION ''}); -$result = $node->safe_psql('postgres', - q{SELECT * FROM pg_get_tablespace_ddl('regress_ tblsp')}); -like($result, qr/"regress_ tblsp"/, 'tablespace name is quoted'); - -# Rename and add options; reuse this tablespace for the remaining tests -$node->safe_psql( - 'postgres', q{ - ALTER TABLESPACE "regress_ tblsp" RENAME TO regress_allopt_tblsp; - ALTER TABLESPACE regress_allopt_tblsp - SET (seq_page_cost = '1.5', random_page_cost = '1.1234567890', - effective_io_concurrency = '17', maintenance_io_concurrency = '18')}); - -# Tablespace with multiple options -$result = $node->safe_psql('postgres', - q{SELECT * FROM pg_get_tablespace_ddl('regress_allopt_tblsp')}); -like( - $result, - qr/CREATE TABLESPACE regress_allopt_tblsp/, - 'tablespace DDL includes CREATE'); -like( - $result, - qr/OWNER regress_role_ddl_test1/, - 'tablespace DDL includes OWNER'); -like($result, qr/seq_page_cost='1.5'/, 'tablespace DDL includes options'); - -# Pretty-printed output -$result = $node->safe_psql( - 'postgres', - q{SELECT * FROM pg_get_tablespace_ddl('regress_allopt_tblsp', - pretty => true)}); -like($result, qr/\n\s+OWNER/, 'tablespace DDL pretty-prints OWNER'); - -# Owner suppressed -$result = $node->safe_psql( - 'postgres', - q{SELECT * FROM pg_get_tablespace_ddl('regress_allopt_tblsp', - owner => false)}); -unlike($result, qr/OWNER/, 'tablespace DDL owner suppressed'); - -# Lookup by OID -$result = $node->safe_psql( - 'postgres', q{ - SELECT pg_get_tablespace_ddl - FROM pg_get_tablespace_ddl( - (SELECT oid FROM pg_tablespace - WHERE spcname = 'regress_allopt_tblsp'))}); -like( - $result, - qr/CREATE TABLESPACE regress_allopt_tblsp/, - 'tablespace DDL by OID'); - -# Permission check -$node->safe_psql('postgres', q{REVOKE SELECT ON pg_tablespace FROM PUBLIC}); -($ret, $stdout, $stderr) = $node->psql( - 'postgres', - q{SET ROLE regress_role_ddl_noaccess; - SELECT * FROM pg_get_tablespace_ddl('regress_allopt_tblsp')}); -isnt($ret, 0, 'tablespace DDL denied without pg_tablespace access'); -$node->safe_psql( - 'postgres', q{ - GRANT SELECT ON pg_tablespace TO PUBLIC}); - -$node->stop; - -done_testing(); diff --git a/src/test/modules/test_misc/t/016_ddlutils_pg_dump_crosscheck.pl b/src/test/modules/test_misc/t/016_ddlutils_pg_dump_crosscheck.pl new file mode 100644 index 00000000000..99f4fd29979 --- /dev/null +++ b/src/test/modules/test_misc/t/016_ddlutils_pg_dump_crosscheck.pl @@ -0,0 +1,115 @@ +# Cross-check pg_get_role_ddl()/pg_get_tablespace_ddl()/pg_get_database_ddl() +# against pg_dumpall's own output for the same objects, per Andres Freund's +# review comment that nothing currently guards against the two diverging: +# https://postgr.es/m/ia2gifmcdsiunj3j6i4yumnnzru45nvet4mxtydb6nodwrvkhe@qkd7lzlxsrht +use strict; +use warnings FATAL => 'all'; +use PostgreSQL::Test::Cluster; +use PostgreSQL::Test::Utils; +use Test::More; + +my $node = PostgreSQL::Test::Cluster->new('main'); +$node->init; +$node->start; + +$node->safe_psql( + 'postgres', q{ + SET allow_in_place_tablespaces = true; + CREATE ROLE regress_ddl_crosscheck_role LOGIN CREATEDB + CONNECTION LIMIT 3 PASSWORD 'crosscheck_pw' + VALID UNTIL '2035-06-15 12:00:00+00'; + ALTER ROLE regress_ddl_crosscheck_role SET work_mem = '17MB'; + CREATE TABLESPACE regress_ddl_crosscheck_tblspc + OWNER regress_ddl_crosscheck_role LOCATION '' + WITH (random_page_cost = 2.25); + CREATE DATABASE regress_ddl_crosscheck_db + OWNER regress_ddl_crosscheck_role + TABLESPACE regress_ddl_crosscheck_tblspc + CONNECTION LIMIT 7; + ALTER DATABASE regress_ddl_crosscheck_db SET work_mem = '31MB'; + }); + +# Normalize: collapse whitespace, drop the trailing semicolon, and sort +# each statement's own whitespace-split tokens so clause/token order +# (which the two implementations aren't guaranteed to agree on) doesn't +# cause spurious failures. Returns an arrayref, sorted, one entry per +# input statement. +sub normalize_statements +{ + my (@statements) = @_; + my @out; + + for my $stmt (@statements) + { + $stmt =~ s/^\s+|\s+$//g; + $stmt =~ s/;$//; + $stmt =~ s/\s+/ /g; + next if $stmt eq ''; + push @out, join(' ', sort split(/\s+/, $stmt)); + } + return [ sort @out ]; +} + +# --- pg_dumpall globals (roles + tablespaces) --- +# connstr() gives pg_dumpall the right host/port without needing PGHOST/ +# PGPORT in the environment. +my ($globals_out, $globals_err); +run_log( + [ 'pg_dumpall', '--globals-only', '-d', $node->connstr('postgres') ], + '>', \$globals_out, '2>', \$globals_err) + or die "pg_dumpall --globals-only failed: $globals_err"; + +# Anchor on statement type, not just a substring match on the object's +# name: a plain name match also catches pg_dumpall's "-- User Config +# "role"" comment headers, and statements for other objects that merely +# reference this one (e.g. the tablespace's "OWNER regress_..._role" +# clause on its CREATE TABLESPACE line). +my @dumpall_role_lines = grep { + /regress_ddl_crosscheck_role/ && /^(CREATE|ALTER) ROLE/ +} split(/\n/, $globals_out); +my @dumpall_tblspc_lines = grep { + /regress_ddl_crosscheck_tblspc/ && /^(CREATE|ALTER) TABLESPACE/ +} split(/\n/, $globals_out); + +my $our_role_ddl = $node->safe_psql('postgres', + q{SELECT string_agg(pg_get_role_ddl, E'\n') FROM + pg_get_role_ddl('regress_ddl_crosscheck_role')}); +my $our_tblspc_ddl = $node->safe_psql('postgres', + q{SELECT string_agg(pg_get_tablespace_ddl, E'\n') FROM + pg_get_tablespace_ddl('regress_ddl_crosscheck_tblspc')}); + +is_deeply( + normalize_statements(split(/\n/, $our_role_ddl)), + normalize_statements(@dumpall_role_lines), + 'pg_get_role_ddl matches pg_dumpall --globals-only, token-for-token'); + +is_deeply( + normalize_statements(split(/\n/, $our_tblspc_ddl)), + normalize_statements(@dumpall_tblspc_lines), + 'pg_get_tablespace_ddl matches pg_dumpall --globals-only, token-for-token'); + +# --- pg_dump --create (database-level CREATE DATABASE + ALTER DATABASE) --- +my ($dbdump_out, $dbdump_err); +run_log( + [ + 'pg_dump', '--create', '--schema-only', + '-d', $node->connstr('regress_ddl_crosscheck_db'), + ], + '>', \$dbdump_out, '2>', \$dbdump_err) + or die "pg_dump --create failed: $dbdump_err"; + +my @pgdump_db_lines = + grep { /regress_ddl_crosscheck_db/ && /^(CREATE|ALTER) DATABASE/ } + split(/\n/, $dbdump_out); + +my $our_db_ddl = $node->safe_psql('postgres', + q{SELECT string_agg(pg_get_database_ddl, E'\n') FROM + pg_get_database_ddl('regress_ddl_crosscheck_db')}); + +is_deeply( + normalize_statements(split(/\n/, $our_db_ddl)), + normalize_statements(@pgdump_db_lines), + 'pg_get_database_ddl matches pg_dump --create, token-for-token'); + +$node->stop; +done_testing(); -- 2.43.0
^ permalink raw reply [nested|flat] 32+ messages in thread

* Re: pg_get_*_ddl() needs a redesign
  2026-08-27 01:52 pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 15:47 ` Re: pg_get_*_ddl() needs a redesign Melanie Plageman <melanieplageman@gmail.com>
  2026-09-09 16:24   ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-09 17:21     ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 17:34       ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-09 19:12         ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-09 20:12           ` Re: pg_get_*_ddl() needs a redesign Andres Freund <andres@anarazel.de>
  2026-09-09 22:25             ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-10 23:59               ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-13 18:28                 ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
@ 2026-09-14 02:21                   ` Michael Paquier <michael@paquier.xyz>
  2026-09-14 04:02                     ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  0 siblings, 1 reply; 32+ messages in thread

From: Michael Paquier @ 2026-09-14 02:21 UTC (permalink / raw)
  To: Andrew Dunstan <andrew@dunslane.net>; +Cc: Andres Freund <andres@anarazel.de>; Tom Lane <tgl@sss.pgh.pa.us>; Noah Misch <noah@leadboat.com>; Melanie Plageman <melanieplageman@gmail.com>; gonzalemario@gmail.com; dbryan.green@gmail.com; euler@eulerto.com; pgsql-hackers

On Sun, Sep 13, 2026 at 02:28:12PM -0400, Andrew Dunstan wrote:
> OK, I have done that revert. Here are the patches Euler and I have in mind.

The buildfarm is heavily broken on REL_19_STABLE due to a remaining
trace of ddlutils.o in a Makefile.  It's been a bit annoying here, and
it should be already late for you, so I will go ahead and fix it.

No worries.  :)
--
Michael

Attachments:

  signature.asc (application/pgp-signature, 832B) download

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

* Re: pg_get_*_ddl() needs a redesign
  2026-08-27 01:52 pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 15:47 ` Re: pg_get_*_ddl() needs a redesign Melanie Plageman <melanieplageman@gmail.com>
  2026-09-09 16:24   ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-09 17:21     ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 17:34       ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-09 19:12         ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-09 20:12           ` Re: pg_get_*_ddl() needs a redesign Andres Freund <andres@anarazel.de>
  2026-09-09 22:25             ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-10 23:59               ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-13 18:28                 ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-14 02:21                   ` Re: pg_get_*_ddl() needs a redesign Michael Paquier <michael@paquier.xyz>
@ 2026-09-14 04:02                     ` Andrew Dunstan <andrew@dunslane.net>
  0 siblings, 0 replies; 32+ messages in thread

From: Andrew Dunstan @ 2026-09-14 04:02 UTC (permalink / raw)
  To: Michael Paquier <michael@paquier.xyz>; +Cc: Andres Freund <andres@anarazel.de>; Tom Lane <tgl@sss.pgh.pa.us>; Noah Misch <noah@leadboat.com>; Melanie Plageman <melanieplageman@gmail.com>; gonzalemario@gmail.com; dbryan.green@gmail.com; euler@eulerto.com; pgsql-hackers



> On Sep 13, 2026, at 10:21 PM, Michael Paquier <michael@paquier.xyz> wrote:
> 
> On Sun, Sep 13, 2026 at 02:28:12PM -0400, Andrew Dunstan wrote:
>> OK, I have done that revert. Here are the patches Euler and I have in mind.
> 
> The buildfarm is heavily broken on REL_19_STABLE due to a remaining
> trace of ddlutils.o in a Makefile.  It's been a bit annoying here, and
> it should be already late for you, so I will go ahead and fix it.
> 
> No worries.  :)

*sigh* of course I checked, but using meson.

Thanks for fixing

Cheers

Andrew







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

* Re: pg_get_*_ddl() needs a redesign
  2026-08-27 01:52 pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 15:47 ` Re: pg_get_*_ddl() needs a redesign Melanie Plageman <melanieplageman@gmail.com>
  2026-09-09 16:24   ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-09 17:21     ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 17:34       ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-09 19:12         ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
@ 2026-09-10 03:59           ` Noah Misch <noah@leadboat.com>
  2026-09-11 04:19             ` Re: pg_get_*_ddl() needs a redesign Robert Haas <robertmhaas@gmail.com>
  1 sibling, 1 reply; 32+ messages in thread

From: Noah Misch @ 2026-09-10 03:59 UTC (permalink / raw)
  To: Andrew Dunstan <andrew@dunslane.net>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Melanie Plageman <melanieplageman@gmail.com>; gonzalemario@gmail.com; dbryan.green@gmail.com; euler@eulerto.com; pgsql-hackers

On Wed, Sep 09, 2026 at 03:12:26PM -0400, Andrew Dunstan wrote:
> On 2026-09-09 We 1:34 PM, Tom Lane wrote:
> > Noah Misch<noah@leadboat.com> writes:
> > > I want to clarify one thing before you spend much time on fixes.  I don't see
> > > "fixes" addressing this thread as a whole, unless you plan to dispute the
> > > premise that the feature needs a redesign.  In other words, I think the thread
> > > outcome should be one of these:
> > > - My review erred in determining that the feature needs a redesign.  The
> > >    design is sound and should proceed, possibly with some fixes.
> > > - Revert the feature.
> > FWIW, I agree with Noah's point that having two independent
> > implementations of SQL reverse compilation is not really a place
> > we want to be: it will be a major PITA for future development.
> > 
> > Unfortunately, I see no practical way to have pg_dump share code with
> > the backend for most of this stuff; not least because pg_dump has to
> > support dumping from old backends that won't have any such feature.
> > So we either swallow that duplication or decide that we're never
> > going to support this in the backend.  Neither choice is palatable,
> > but I don't think I want to be forced into the duplicative approach
> > when we've not explored other alternatives (such as refactoring
> > pg_dump to expose its internal logic in some way).
> > 
> > 			
> 
> 
> I first raised the idea of these functions on the mailing list in July 2025,
> although the idea was much older. [1] Among other things, you (Tom) said
> [2]:
> 
>    Insisting that this feature support pg_dump is a good way
>    of making sure that nothing useful will emerge at all.
> 
> Concrete patches began to appear around October and November 2025. I don't recall anyone coming along and saying "No, we don't want to do that." After they were committed there were various comments on the way they were done, and I addressed them.  Now, months later, we are more or less told that this whole enterprise has been misguided from the start. Is it any wonder that people often find the process of contributing to Postgres discouraging? And that would include people who have been working on more important members of this set for release 20, particularly the one that most people want, namely pg_get_table_ddl() that Akshay has been working on. I don't feel badly for myself, but I do feel badly for the contributors.

Going forward, feel free to add me to the To: line of a mailing list post and
explicitly ask me for my guess about the project's overall prognosis, likely
ways of failing, etc.  My guess may be brief and/or wrong, but I'll provide
one.

When it's four months after feature freeze and I find non-subtle, unreported
defects in the feature, the development process wasn't adequate for the
subject matter.  To be transparent, observing this outcome changed my view of
code duplication.  Duplication was always a smell, but it seemed like a
plausible compromise tactic in 2025.  Now I find the duplication gave wrong
code too much place to hide.

> I believe reverting now almost certainly means this proposal or anything like it is probably dead for the foreseeable future.

I'm prepared to accept that outcome.






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

* Re: pg_get_*_ddl() needs a redesign
  2026-08-27 01:52 pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 15:47 ` Re: pg_get_*_ddl() needs a redesign Melanie Plageman <melanieplageman@gmail.com>
  2026-09-09 16:24   ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-09 17:21     ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 17:34       ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-09 19:12         ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-10 03:59           ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
@ 2026-09-11 04:19             ` Robert Haas <robertmhaas@gmail.com>
  2026-09-11 04:55               ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-11 05:26               ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  0 siblings, 2 replies; 32+ messages in thread

From: Robert Haas @ 2026-09-11 04:19 UTC (permalink / raw)
  To: Noah Misch <noah@leadboat.com>; +Cc: Andrew Dunstan <andrew@dunslane.net>; Tom Lane <tgl@sss.pgh.pa.us>; Melanie Plageman <melanieplageman@gmail.com>; gonzalemario@gmail.com; dbryan.green@gmail.com; euler@eulerto.com; pgsql-hackers

On Thu, Sep 10, 2026 at 12:00 AM Noah Misch <noah@leadboat.com> wrote:
> Going forward, feel free to add me to the To: line of a mailing list post and
> explicitly ask me for my guess about the project's overall prognosis, likely
> ways of failing, etc.  My guess may be brief and/or wrong, but I'll provide
> one.

I don't think this is how this mailing list works. The volume is
overwhelming for me, too, but patch authors aren't obliged to cc
anyone specifially.

> When it's four months after feature freeze and I find non-subtle, unreported
> defects in the feature, the development process wasn't adequate for the
> subject matter.  To be transparent, observing this outcome changed my view of
> code duplication.  Duplication was always a smell, but it seemed like a
> plausible compromise tactic in 2025.  Now I find the duplication gave wrong
> code too much place to hide.

I think we would do well to confine all of our present conversations,
insofar as it is possible to do so, to whether any given feature
contains defects incompatible with shipping it. The desirability of
this particular feature is, as Andrew says, something that would have
been better litigated six or more months ago. Granted, we're all
overwhelmed, and that makes it more understandable that people who had
concerns about desirability did not raise them at the time, but we
will not succeed in producing awesome software by forcing last-minute
reverts because we've changed our mind about whether the feature is a
good idea in principle. There's more than enough to revert on the
basis of whatever is broken in practice.

That said, if this is coming out of v19 anyway, then IMHO it is fair
game to reopen the question of whether we want it in v20. But if we're
going to do that, we should hash that out now rather than in six
months from now or twelve months from now. Personally, I have mixed
feelings about this feature. On the one hand, I am sure it will get
some use, and I have wanted it myself. On the other hand, it will get
far less use, and far less testing, than the equivalent code in
pg_dump, so it's more likely to have bugs now and in the future, and
the fact that there's no reasonable way (at least, not that I can see)
to handle version skew within a facility like this is a major
disadvantage vs. pg_dump. Nevertheless, on balance, I'm unconvinced
that there's sufficient reason to categorically block a
sufficiently-well-implemented feature of this type. But not even the
most desirable feature should remain in tree if the implementation
isn't of sufficient quality.

-- 
Robert Haas





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

* Re: pg_get_*_ddl() needs a redesign
  2026-08-27 01:52 pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 15:47 ` Re: pg_get_*_ddl() needs a redesign Melanie Plageman <melanieplageman@gmail.com>
  2026-09-09 16:24   ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-09 17:21     ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 17:34       ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-09 19:12         ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-10 03:59           ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-11 04:19             ` Re: pg_get_*_ddl() needs a redesign Robert Haas <robertmhaas@gmail.com>
@ 2026-09-11 04:55               ` Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-11 14:23                 ` Re: pg_get_*_ddl() needs a redesign Andres Freund <andres@anarazel.de>
  2026-09-12 14:02                 ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  1 sibling, 2 replies; 32+ messages in thread

From: Tom Lane @ 2026-09-11 04:55 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; +Cc: Noah Misch <noah@leadboat.com>; Andrew Dunstan <andrew@dunslane.net>; Melanie Plageman <melanieplageman@gmail.com>; gonzalemario@gmail.com; dbryan.green@gmail.com; euler@eulerto.com; pgsql-hackers

Robert Haas <robertmhaas@gmail.com> writes:
> That said, if this is coming out of v19 anyway, then IMHO it is fair
> game to reopen the question of whether we want it in v20. But if we're
> going to do that, we should hash that out now rather than in six
> months from now or twelve months from now. Personally, I have mixed
> feelings about this feature. On the one hand, I am sure it will get
> some use, and I have wanted it myself. On the other hand, it will get
> far less use, and far less testing, than the equivalent code in
> pg_dump, so it's more likely to have bugs now and in the future, and
> the fact that there's no reasonable way (at least, not that I can see)
> to handle version skew within a facility like this is a major
> disadvantage vs. pg_dump.

I'm a bit confused why you say that.  To my mind, if we were going
to proceed in this direction, version skew would ideally be solved
like this:

1. Server-side DDL-reconstruction functions only need to work with
their particular server version; necessarily so, since that's the
only catalog data they'll ever see.

2. pg_dump just calls the source server's DDL-reconstruction functions
and doesn't have to worry about version skew.

The difficulty is how do we get to #2 from where we are.  Part of that
could be handled by saying "well, pg_dump calls the server functions
when source server version >= N, and otherwise does it locally",
and expecting that we could eventually retire the "locally" code.
Since the "locally" code would only need to work with frozen server
versions, that doesn't seem too unmaintainable.  The hard parts as
I see it are

(A) pg_dump is optimized to gather data across the entire database
at once.  Converting it to call functions that produce info about
a single object at a time would almost certainly be catastrophic
for performance on large databases.

(B) pg_dump slices and dices the data in ways that don't necessarily
make sense for standalone usage.  For example it doesn't want to
mention a primary key when creating a table, rather it wants to add
that constraint (and build the index) after loading data.

I do not feel that these problems are necessarily insoluble, but
they do require some hard work to define the server-side functionality
properly.

			regards, tom lane






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

* Re: pg_get_*_ddl() needs a redesign
  2026-08-27 01:52 pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 15:47 ` Re: pg_get_*_ddl() needs a redesign Melanie Plageman <melanieplageman@gmail.com>
  2026-09-09 16:24   ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-09 17:21     ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 17:34       ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-09 19:12         ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-10 03:59           ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-11 04:19             ` Re: pg_get_*_ddl() needs a redesign Robert Haas <robertmhaas@gmail.com>
  2026-09-11 04:55               ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
@ 2026-09-11 14:23                 ` Andres Freund <andres@anarazel.de>
  2026-09-11 15:14                   ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-11 15:14                   ` Re: pg_get_*_ddl() needs a redesign Robert Haas <robertmhaas@gmail.com>
  1 sibling, 2 replies; 32+ messages in thread

From: Andres Freund @ 2026-09-11 14:23 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Robert Haas <robertmhaas@gmail.com>; Noah Misch <noah@leadboat.com>; Andrew Dunstan <andrew@dunslane.net>; Melanie Plageman <melanieplageman@gmail.com>; gonzalemario@gmail.com; dbryan.green@gmail.com; euler@eulerto.com; pgsql-hackers

Hi,

On 2026-09-11 00:55:54 -0400, Tom Lane wrote:
> I'm a bit confused why you say that.  To my mind, if we were going
> to proceed in this direction, version skew would ideally be solved
> like this:
> 
> 1. Server-side DDL-reconstruction functions only need to work with
> their particular server version; necessarily so, since that's the
> only catalog data they'll ever see.
> 
> 2. pg_dump just calls the source server's DDL-reconstruction functions
> and doesn't have to worry about version skew.

Isn't the problem with that that we occasionally need to adapt the syntax
between versions to some degree? I think it has become less common, but I'm a
bit sceptical that it's wise to decide we won't ever again need that...

Binary upgrade mode is probably where we hit this most often these days.

I wonder if the right thing here would be to separate the "metadata
collection" aspect from the "SQL generation" aspect. I.e. have a small library
that can generate DDL statements from its inputs, without any catalog
accesses. We'd still end up - annoyingly - with two versions of the metadata
collection (one from syscaches for the get_ddl* SQL functions, one via queries
for pg_dump), but at least the SQL generation aspect would be deduplicated.

I think such a separation could be useful for other things as well,
e.g. logical replication of DDLs.


> (A) pg_dump is optimized to gather data across the entire database
> at once.  Converting it to call functions that produce info about
> a single object at a time would almost certainly be catastrophic
> for performance on large databases.

Hm. I don't think I really understand that:

From what I can see the main benefits of entire-database-at-once isn't catalog
lookup efficiency, it's the avoidance of per-object roundtrips and avoiding
osme serialization cost.

Sure, there's also some benefits of turning more things into sequential scans,
rather than index lookups (via sycaches), but there's also a lot of overhead
in using full blown joins for everything, and in doing redundant lookups for
data that's repeated in almost every query (e.g. pg_namespace, name of owner,
etc).

For comparable performance I think you'd obviously have to call the DDL
generating functions for all objects of a class in one go, but I don't think
that'd be hard.


> (B) pg_dump slices and dices the data in ways that don't necessarily
> make sense for standalone usage.  For example it doesn't want to
> mention a primary key when creating a table, rather it wants to add
> that constraint (and build the index) after loading data.

Yep, that seems nontrivial.

Greetings,

Andres Freund






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

* Re: pg_get_*_ddl() needs a redesign
  2026-08-27 01:52 pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 15:47 ` Re: pg_get_*_ddl() needs a redesign Melanie Plageman <melanieplageman@gmail.com>
  2026-09-09 16:24   ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-09 17:21     ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 17:34       ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-09 19:12         ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-10 03:59           ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-11 04:19             ` Re: pg_get_*_ddl() needs a redesign Robert Haas <robertmhaas@gmail.com>
  2026-09-11 04:55               ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-11 14:23                 ` Re: pg_get_*_ddl() needs a redesign Andres Freund <andres@anarazel.de>
@ 2026-09-11 15:14                   ` Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-11 15:24                     ` Re: pg_get_*_ddl() needs a redesign Robert Haas <robertmhaas@gmail.com>
  1 sibling, 1 reply; 32+ messages in thread

From: Tom Lane @ 2026-09-11 15:14 UTC (permalink / raw)
  To: Andres Freund <andres@anarazel.de>; +Cc: Robert Haas <robertmhaas@gmail.com>; Noah Misch <noah@leadboat.com>; Andrew Dunstan <andrew@dunslane.net>; Melanie Plageman <melanieplageman@gmail.com>; gonzalemario@gmail.com; dbryan.green@gmail.com; euler@eulerto.com; pgsql-hackers

Andres Freund <andres@anarazel.de> writes:
> On 2026-09-11 00:55:54 -0400, Tom Lane wrote:
>> I'm a bit confused why you say that.  To my mind, if we were going
>> to proceed in this direction, version skew would ideally be solved
>> like this:
>> 
>> 1. Server-side DDL-reconstruction functions only need to work with
>> their particular server version; necessarily so, since that's the
>> only catalog data they'll ever see.
>> 
>> 2. pg_dump just calls the source server's DDL-reconstruction functions
>> and doesn't have to worry about version skew.

> Isn't the problem with that that we occasionally need to adapt the syntax
> between versions to some degree? I think it has become less common, but I'm a
> bit sceptical that it's wise to decide we won't ever again need that...

I think we try very very hard to avoid making changes that would break
existing dump files.  There are certainly times where we change what
pg_dump prefers to output, but the server should continue to accept
what pg_dump used to output (at least for quite a few years).  Users
don't always have the luxury of being able to follow the advice to
"use the newest pg_dump to make your dump".

> I wonder if the right thing here would be to separate the "metadata
> collection" aspect from the "SQL generation" aspect. I.e. have a small library
> that can generate DDL statements from its inputs, without any catalog
> accesses. We'd still end up - annoyingly - with two versions of the metadata
> collection (one from syscaches for the get_ddl* SQL functions, one via queries
> for pg_dump), but at least the SQL generation aspect would be deduplicated.

Hmm...

			regards, tom lane





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

* Re: pg_get_*_ddl() needs a redesign
  2026-08-27 01:52 pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 15:47 ` Re: pg_get_*_ddl() needs a redesign Melanie Plageman <melanieplageman@gmail.com>
  2026-09-09 16:24   ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-09 17:21     ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 17:34       ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-09 19:12         ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-10 03:59           ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-11 04:19             ` Re: pg_get_*_ddl() needs a redesign Robert Haas <robertmhaas@gmail.com>
  2026-09-11 04:55               ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-11 14:23                 ` Re: pg_get_*_ddl() needs a redesign Andres Freund <andres@anarazel.de>
  2026-09-11 15:14                   ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
@ 2026-09-11 15:24                     ` Robert Haas <robertmhaas@gmail.com>
  2026-09-11 15:58                       ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 1 reply; 32+ messages in thread

From: Robert Haas @ 2026-09-11 15:24 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Andres Freund <andres@anarazel.de>; Noah Misch <noah@leadboat.com>; Andrew Dunstan <andrew@dunslane.net>; Melanie Plageman <melanieplageman@gmail.com>; gonzalemario@gmail.com; dbryan.green@gmail.com; euler@eulerto.com; pgsql-hackers

On Fri, Sep 11, 2026 at 11:14 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:
> Users
> don't always have the luxury of being able to follow the advice to
> "use the newest pg_dump to make your dump".

I completely agree with this. But when they don't, things break pretty
regularly. Just to take one example, adding a new parser keyword can
require quoting to be added to older dumps, which obviously won't work
if the list of identifiers needing quoting is taken from the target
system's tables rather than pg_dump's own knowledge. I one hundred
percent agree that we shouldn't cause that sort of breakage any more
often than necessary, but there is ample evidence that we find it
necessary on a pretty regular basis. If we put ourselves in a
situation where using the correct version of pg_dump is no longer
sufficient to deal with these sorts of situations, we are going to
have a lot of very sad users.

That's one of many reasons why I do not think this feature can share
code with pg_dump in any meaningful way. We either decide that we're
OK with having this feature for situations where people just want a
quick SQL representation of an existing object without worrying about
all the stuff pg_dump deals with, or we discard the feature. I don't
think there's an intermediate world where this feature can serve the
needs of pg_dump. I'd love to be wrong; if somebody has a great idea,
cool. But I don't see it.

-- 
Robert Haas





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

* Re: pg_get_*_ddl() needs a redesign
  2026-08-27 01:52 pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 15:47 ` Re: pg_get_*_ddl() needs a redesign Melanie Plageman <melanieplageman@gmail.com>
  2026-09-09 16:24   ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-09 17:21     ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 17:34       ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-09 19:12         ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-10 03:59           ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-11 04:19             ` Re: pg_get_*_ddl() needs a redesign Robert Haas <robertmhaas@gmail.com>
  2026-09-11 04:55               ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-11 14:23                 ` Re: pg_get_*_ddl() needs a redesign Andres Freund <andres@anarazel.de>
  2026-09-11 15:14                   ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-11 15:24                     ` Re: pg_get_*_ddl() needs a redesign Robert Haas <robertmhaas@gmail.com>
@ 2026-09-11 15:58                       ` Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-11 16:27                         ` Re: pg_get_*_ddl() needs a redesign Robert Haas <robertmhaas@gmail.com>
  2026-09-11 16:34                         ` Re: pg_get_*_ddl() needs a redesign Marcos Pegoraro <marcos@f10.com.br>
  0 siblings, 2 replies; 32+ messages in thread

From: Tom Lane @ 2026-09-11 15:58 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; +Cc: Andres Freund <andres@anarazel.de>; Noah Misch <noah@leadboat.com>; Andrew Dunstan <andrew@dunslane.net>; Melanie Plageman <melanieplageman@gmail.com>; gonzalemario@gmail.com; dbryan.green@gmail.com; euler@eulerto.com; pgsql-hackers

Robert Haas <robertmhaas@gmail.com> writes:
> On Fri, Sep 11, 2026 at 11:14 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:
>> Users
>> don't always have the luxury of being able to follow the advice to
>> "use the newest pg_dump to make your dump".

> I completely agree with this. But when they don't, things break pretty
> regularly. Just to take one example, adding a new parser keyword can
> require quoting to be added to older dumps, which obviously won't work
> if the list of identifiers needing quoting is taken from the target
> system's tables rather than pg_dump's own knowledge.

Maybe --quote-all-identifiers should be the default?  I don't think
that we break old syntax "pretty regularly" in any other way.
But that's a side point.

> That's one of many reasons why I do not think this feature can share
> code with pg_dump in any meaningful way. We either decide that we're
> OK with having this feature for situations where people just want a
> quick SQL representation of an existing object without worrying about
> all the stuff pg_dump deals with, or we discard the feature. I don't
> think there's an intermediate world where this feature can serve the
> needs of pg_dump. I'd love to be wrong; if somebody has a great idea,
> cool. But I don't see it.

I'm not quite convinced.  But if that's really the case, I'm voting
for "discard the feature".  It's not useful enough to justify doubling
the maintenance load associated with DDL reconstruction.

			regards, tom lane






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

* Re: pg_get_*_ddl() needs a redesign
  2026-08-27 01:52 pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 15:47 ` Re: pg_get_*_ddl() needs a redesign Melanie Plageman <melanieplageman@gmail.com>
  2026-09-09 16:24   ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-09 17:21     ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 17:34       ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-09 19:12         ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-10 03:59           ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-11 04:19             ` Re: pg_get_*_ddl() needs a redesign Robert Haas <robertmhaas@gmail.com>
  2026-09-11 04:55               ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-11 14:23                 ` Re: pg_get_*_ddl() needs a redesign Andres Freund <andres@anarazel.de>
  2026-09-11 15:14                   ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-11 15:24                     ` Re: pg_get_*_ddl() needs a redesign Robert Haas <robertmhaas@gmail.com>
  2026-09-11 15:58                       ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
@ 2026-09-11 16:27                         ` Robert Haas <robertmhaas@gmail.com>
  2026-10-19 16:03                           ` Re: pg_get_*_ddl() needs a redesign Mario González <gonzalemario@gmail.com>
  1 sibling, 1 reply; 32+ messages in thread

From: Robert Haas @ 2026-09-11 16:27 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Andres Freund <andres@anarazel.de>; Noah Misch <noah@leadboat.com>; Andrew Dunstan <andrew@dunslane.net>; Melanie Plageman <melanieplageman@gmail.com>; gonzalemario@gmail.com; dbryan.green@gmail.com; euler@eulerto.com; pgsql-hackers

On Fri, Sep 11, 2026 at 11:58 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:
> Maybe --quote-all-identifiers should be the default?  I don't think
> that we break old syntax "pretty regularly" in any other way.
> But that's a side point.

It's possible it's been less in recent years, but I feel like that's
just the most common way, like you know 50% of the total breakage or
something.

> I'm not quite convinced.  But if that's really the case, I'm voting
> for "discard the feature".  It's not useful enough to justify doubling
> the maintenance load associated with DDL reconstruction.

I think what really bothers me here is the chances of silent breakage,
which appear to be high. If it were somehow the case that adding a new
feature to some kind of DDL object, like a FLAVOR banana option to
CREATE TABLE, were likely to produce test failures until the
corresponding code was updated, I don't think that would be bad. It
would just be one more small step that everyone extending a DDL
command would have to do. But as it is, I don't think anything would
alert you to the oversight. That's likely to lead to a lot of future
headaches as we discover that things have been broken for years
without anybody noticing. Or maybe in the LLM era we'll just get a
flood of post-commit reports pointing out the problem. But that still
leads to us playing catch-up, which is not a good situation.

-- 
Robert Haas





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

* Re: pg_get_*_ddl() needs a redesign
  2026-08-27 01:52 pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 15:47 ` Re: pg_get_*_ddl() needs a redesign Melanie Plageman <melanieplageman@gmail.com>
  2026-09-09 16:24   ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-09 17:21     ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 17:34       ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-09 19:12         ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-10 03:59           ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-11 04:19             ` Re: pg_get_*_ddl() needs a redesign Robert Haas <robertmhaas@gmail.com>
  2026-09-11 04:55               ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-11 14:23                 ` Re: pg_get_*_ddl() needs a redesign Andres Freund <andres@anarazel.de>
  2026-09-11 15:14                   ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-11 15:24                     ` Re: pg_get_*_ddl() needs a redesign Robert Haas <robertmhaas@gmail.com>
  2026-09-11 15:58                       ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-11 16:27                         ` Re: pg_get_*_ddl() needs a redesign Robert Haas <robertmhaas@gmail.com>
@ 2026-10-19 16:03                           ` Mario González <gonzalemario@gmail.com>
  2026-10-20 17:16                             ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-11-04 13:53                             ` Re: pg_get_*_ddl() needs a redesign Robert Haas <robertmhaas@gmail.com>
  0 siblings, 2 replies; 32+ messages in thread

From: Mario González @ 2026-10-19 16:03 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Andres Freund <andres@anarazel.de>; Noah Misch <noah@leadboat.com>; Melanie Plageman <melanieplageman@gmail.com>; pgsql-hackers

Sorry for top-posting but I reckon I'm not replying to each statement
separately but as a whole.


Hello all,

As one of the authors of pg_get_role_ddl(), I've been reading this
thread *carefully*, and I took quite a long time to analise what and
how I'd address the concerns. I noticed that despite the fact that
I've put a lot of effort a) I may not be understanding all of the
objections correctly and b) before anyone (hopefully me) spends more
time on code for v20 or newer, I'd like to check my reading with you,
and ask whether a possible direction makes sense.  Please correct me
wherever I've got it wrong.

sorry.... It's a *very* long email.

How I'm reading the problems
----------------------------

If I understand correctly, the concerns fall into three groups:

1. Plain defects (passwords, "PG_DEFAULT", locking, permissions).  I
reckon Andrew and Euler's v6 patches [1] fix these, apart from two
loose ends: password defaults to true, so a default call still needs
pg_authid access, and permission errors name the target object rather
than the denied catalog. However, am I right in thinking these are not
the main concern? (please keep reading if possible)

2. Ordering.  Each function returns one object's script, but some of
its statements depend on other objects: IN DATABASE settings need the
database, and GRANT ... GRANTED BY g needs g to hold ADMIN OPTION
first, which comes from g's output.  I'm worried the cross-role case
can't be solved one role at a time, which I believe is why
dumpRoleMembership() makes repeated passes. Noah, is this the redesign
issue you meant?

3. Two independent implementations.  pg_dumpall builds the same DDL on
the client side, and nothing would tell us when the two drift apart,
which I understood to be Robert's main concern.

I believe that's a fair summary, so what I hope we could achieve:


* Users can get the definition of an existing object from SQL, for the
'give me something like this object so I can tweak it' case that
Andrew and Marcos described.
* There is one implementation of 'catalog state -> SQL' per object
type, ideally used by pg_dump/pg_dumpall too, so it gets tested all
the time.
* The backend functions describe one object at a time and make no
promise about the order in which their output can be run.  Working out
that order, across all objects, stays with pg_dump/pg_dumpall, which
already does it.

Does this match what others would want, or are some of these goals,
maybe not realistic?

A possible direction, for discussion
------------------------------------

a) Split pg_get_role_ddl() into smaller functions: one for the CREATE
ROLE, one for the role's settings, one for its memberships. None of
them tries to put statements in restore order; the caller decides when
to run each part.
(Meant to address Noah's ordering concern.)

b) pg_dumpall calls these functions instead of building the same SQL
itself, so there is only one copy of the code that turns catalog rows
into SQL.  For servers too old to have the functions, pg_dumpall keeps
its current code, which no longer needs to change because those
servers won't change either.  I reckon this is close to what Tom
sketched [2]. (Meant to address the 'two implementations' concern.)

c) Tests compare the functions' output with pg_dumpall's for the same
objects, as v6 begins to.  They'd need to be broader than v6's,
perhaps driven by pg_dump's own tests, to catch a newly added option.
(Meant to address Robert's silent-drift and Andres's cross-check concerns.)

Questions where I'd need confirmation
-------------------------------------

1. Noah, Tom: if pg_dumpall actually used these functions, would that
address the 'one implementation' concern?  If not, what would?

2. Would it be acceptable to keep the current client-side code for
older source servers, expecting to remove it eventually?

I'd rather not start on a patch until I know whether this direction is
reasonable.  If it is, I'd be happy to start with roles, since
that's the part I know best.

Thank you for your patience, and for the reviews so far.

Regards,
Mario Gonzalez

[1] https://postgr.es/m/88e205f5-f561-4a00-b6e6-ab070ea6400a@dunslane.net
[2] https://postgr.es/m/956966.1789102554@sss.pgh.pa.us




On Fri, 11 Sept 2026 at 13:28, Robert Haas <robertmhaas@gmail.com> wrote:
>
> On Fri, Sep 11, 2026 at 11:58 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:
> > Maybe --quote-all-identifiers should be the default?  I don't think
> > that we break old syntax "pretty regularly" in any other way.
> > But that's a side point.
>
> It's possible it's been less in recent years, but I feel like that's
> just the most common way, like you know 50% of the total breakage or
> something.
>
> > I'm not quite convinced.  But if that's really the case, I'm voting
> > for "discard the feature".  It's not useful enough to justify doubling
> > the maintenance load associated with DDL reconstruction.
>
> I think what really bothers me here is the chances of silent breakage,
> which appear to be high. If it were somehow the case that adding a new
> feature to some kind of DDL object, like a FLAVOR banana option to
> CREATE TABLE, were likely to produce test failures until the
> corresponding code was updated, I don't think that would be bad. It
> would just be one more small step that everyone extending a DDL
> command would have to do. But as it is, I don't think anything would
> alert you to the oversight. That's likely to lead to a lot of future
> headaches as we discover that things have been broken for years
> without anybody noticing. Or maybe in the LLM era we'll just get a
> flood of post-commit reports pointing out the problem. But that still
> leads to us playing catch-up, which is not a good situation.
>
> --
> Robert Haas



-- 
Mario Gonzalez






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

* Re: pg_get_*_ddl() needs a redesign
  2026-08-27 01:52 pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 15:47 ` Re: pg_get_*_ddl() needs a redesign Melanie Plageman <melanieplageman@gmail.com>
  2026-09-09 16:24   ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-09 17:21     ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 17:34       ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-09 19:12         ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-10 03:59           ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-11 04:19             ` Re: pg_get_*_ddl() needs a redesign Robert Haas <robertmhaas@gmail.com>
  2026-09-11 04:55               ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-11 14:23                 ` Re: pg_get_*_ddl() needs a redesign Andres Freund <andres@anarazel.de>
  2026-09-11 15:14                   ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-11 15:24                     ` Re: pg_get_*_ddl() needs a redesign Robert Haas <robertmhaas@gmail.com>
  2026-09-11 15:58                       ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-11 16:27                         ` Re: pg_get_*_ddl() needs a redesign Robert Haas <robertmhaas@gmail.com>
  2026-10-19 16:03                           ` Re: pg_get_*_ddl() needs a redesign Mario González <gonzalemario@gmail.com>
@ 2026-10-20 17:16                             ` Noah Misch <noah@leadboat.com>
  2026-10-21 13:35                               ` Re: pg_get_*_ddl() needs a redesign Mario González <gonzalemario@gmail.com>
  1 sibling, 1 reply; 32+ messages in thread

From: Noah Misch @ 2026-10-20 17:16 UTC (permalink / raw)
  To: Mario González <gonzalemario@gmail.com>; +Cc: Robert Haas <robertmhaas@gmail.com>; Tom Lane <tgl@sss.pgh.pa.us>; Andres Freund <andres@anarazel.de>; Melanie Plageman <melanieplageman@gmail.com>; pgsql-hackers

On Mon, Oct 19, 2026 at 01:03:59PM -0300, Mario González wrote:
> Questions where I'd need confirmation
> -------------------------------------

You've asked me some specific questions, but the larger problem is the email's
summary oversimplifying the upthread points from Tom, Andres, Robert, and me.
I wouldn't recommend proceeding.  A successful project for $SUBJECT needs
someone accountable for auditing each iteration against the feedback to date,
point by point.  I don't have capacity to take that role.






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

* Re: pg_get_*_ddl() needs a redesign
  2026-08-27 01:52 pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 15:47 ` Re: pg_get_*_ddl() needs a redesign Melanie Plageman <melanieplageman@gmail.com>
  2026-09-09 16:24   ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-09 17:21     ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 17:34       ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-09 19:12         ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-10 03:59           ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-11 04:19             ` Re: pg_get_*_ddl() needs a redesign Robert Haas <robertmhaas@gmail.com>
  2026-09-11 04:55               ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-11 14:23                 ` Re: pg_get_*_ddl() needs a redesign Andres Freund <andres@anarazel.de>
  2026-09-11 15:14                   ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-11 15:24                     ` Re: pg_get_*_ddl() needs a redesign Robert Haas <robertmhaas@gmail.com>
  2026-09-11 15:58                       ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-11 16:27                         ` Re: pg_get_*_ddl() needs a redesign Robert Haas <robertmhaas@gmail.com>
  2026-10-19 16:03                           ` Re: pg_get_*_ddl() needs a redesign Mario González <gonzalemario@gmail.com>
  2026-10-20 17:16                             ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
@ 2026-10-21 13:35                               ` Mario González <gonzalemario@gmail.com>
  0 siblings, 0 replies; 32+ messages in thread

From: Mario González @ 2026-10-21 13:35 UTC (permalink / raw)
  To: Noah Misch <noah@leadboat.com>; +Cc: Robert Haas <robertmhaas@gmail.com>; Tom Lane <tgl@sss.pgh.pa.us>; Andres Freund <andres@anarazel.de>; Melanie Plageman <melanieplageman@gmail.com>; pgsql-hackers

On Tue, 20 Oct 2026 at 14:17, Noah Misch <noah@leadboat.com> wrote:
>

Thanks for replying!

> On Mon, Oct 19, 2026 at 01:03:59PM -0300, Mario González wrote:
> > Questions where I'd need confirmation
> > -------------------------------------
>
> You've asked me some specific questions, but the larger problem is the email's
> summary oversimplifying the upthread points from Tom, Andres, Robert, and me.

I'm not sure I agree with that's the larger problem. Of course I
simplified the summary but you picked exactly what I reckon I'm trying
to do, bring someone accountable that lead any of the sub items.
Considering that you Noah were particularly involved with raising the
alarm of the functions would need a re-design, I believed you also
wanted to take part of re-routing any effort towards what could be a
final or an acceptable solution. Complaining sometimes is the easy
part but valuable. I just hoped you could do more helping me or
someone else. I understand if you can't.

> I wouldn't recommend proceeding.  A successful project for $SUBJECT needs
Of course again. I won't proceed, that's why I tried to make my words
as concise as possible and despite that I said I won't proceed in the
previous email, yet it seems I wasn't clear.

> someone accountable for auditing each iteration against the feedback to date,
> point by point.  I don't have capacity to take that role.

fair enough.

-- 
Mario Gonzalez






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

* Re: pg_get_*_ddl() needs a redesign
  2026-08-27 01:52 pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 15:47 ` Re: pg_get_*_ddl() needs a redesign Melanie Plageman <melanieplageman@gmail.com>
  2026-09-09 16:24   ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-09 17:21     ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 17:34       ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-09 19:12         ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-10 03:59           ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-11 04:19             ` Re: pg_get_*_ddl() needs a redesign Robert Haas <robertmhaas@gmail.com>
  2026-09-11 04:55               ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-11 14:23                 ` Re: pg_get_*_ddl() needs a redesign Andres Freund <andres@anarazel.de>
  2026-09-11 15:14                   ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-11 15:24                     ` Re: pg_get_*_ddl() needs a redesign Robert Haas <robertmhaas@gmail.com>
  2026-09-11 15:58                       ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-11 16:27                         ` Re: pg_get_*_ddl() needs a redesign Robert Haas <robertmhaas@gmail.com>
  2026-10-19 16:03                           ` Re: pg_get_*_ddl() needs a redesign Mario González <gonzalemario@gmail.com>
@ 2026-11-04 13:53                             ` Robert Haas <robertmhaas@gmail.com>
  1 sibling, 0 replies; 32+ messages in thread

From: Robert Haas @ 2026-11-04 13:53 UTC (permalink / raw)
  To: Mario González <gonzalemario@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Andres Freund <andres@anarazel.de>; Noah Misch <noah@leadboat.com>; Melanie Plageman <melanieplageman@gmail.com>; pgsql-hackers

On Mon, Oct 19, 2026 at 12:04 PM Mario González <gonzalemario@gmail.com> wrote:
> a) Split pg_get_role_ddl() into smaller functions: one for the CREATE
> ROLE, one for the role's settings, one for its memberships. None of
> them tries to put statements in restore order; the caller decides when
> to run each part.
> (Meant to address Noah's ordering concern.)
>
> b) pg_dumpall calls these functions instead of building the same SQL
> itself, so there is only one copy of the code that turns catalog rows
> into SQL.  For servers too old to have the functions, pg_dumpall keeps
> its current code, which no longer needs to change because those
> servers won't change either.  I reckon this is close to what Tom
> sketched [2]. (Meant to address the 'two implementations' concern.)
>
> c) Tests compare the functions' output with pg_dumpall's for the same
> objects, as v6 begins to.  They'd need to be broader than v6's,
> perhaps driven by pg_dump's own tests, to catch a newly added option.
> (Meant to address Robert's silent-drift and Andres's cross-check concerns.)

I think you're going to find it very difficult to make this work.
There are cases where pg_dump splits things up in different ways
depending on the situation. I'm not sure how many such cases remain
off-hand, but I wouldn't be surprised if it isn't enough to make (a) a
non-viable direction. But also, even if you did that, how would it
help? pg_dump builds DDL on the client side so that the DDL matches
the pg_dump version, not the server version. Tom seems to think that
quote_all_identifiers would solve most of that problem, but I don't
agree. I think if you go down the path you propose here, this is going
to get nowhere.

If I were working on this project, what I'd be thinking about is what
the test framework could look like. I don't think that needs to be
pg_dump or pg_dumpall; but I think it needs to be something. For
example, imagine that you take the regression database -- i.e. the
final state left behind by a run of the 'regress' suite -- which we
already use to test pg_upgrade. For each DDL object in the database,
you use pg_get...ddl(), then drop the object, then put the object back
by running the SQL, and then at the end you compare pg_dump output
before and after you did all that. Well, that's not going to be quite
good enough, because a lot of objects will probably have dependencies
and not be droppable, and some objects might have circular
dependencies which might be really complicated, but you could
experiment with creating a TAP test that can work out the dependency
ordering from pg_(sh)depend and drop objects in reverse dependency
order and then put them all back. Maybe it's not crazy complicated.

Another idea could be to actually run the main regression test suite
and have an event trigger that fires every time an object is created
or dropped and try to do DDL replication using this feature: you run
the get-ddl function and replay it in another database that has no
actual data. This kind of sucks because it's expensive and most of the
objects getting created and dropped are fairly boring, but it would
probably test more cases than the previous idea, so it might be worth
doing at least once just to flush bugs out of your implementation,
even if we don't ever commit the result. Another advantage of this is
that, if properly coded, it cannot fail to go kaboom if a new type of
DDL object is added and there's no matching get-ddl function.

(By the way, why are we talking about adding a separate get-ddl
function for every object type, instead of a single entrypoint that
takes an object type and a function OID as separate arguments? The
latter seems much more natural and more consistent with existing
practice.)

I'm not sure either of the above testing ideas are the right final
answer. Maybe there is no right final answer. But in this era of LLMs,
anybody can churn out an implementation of the functions themselves.
Someone could probably create an entire patch set from scratch in less
than a day, and somebody really good at LLM things could possibly do
the whole thing in a single prompt. So, just producing a bunch of code
isn't really adding a lot of value; anybody could do it. Where you add
value is in figuring out how to solve all the problems that your first
design idea creates. And that's where I would gently push back on your
email here a little bit: you're proposing a design which I'm fairly
sure is not going to actually solve those problems, but you seem to
think it will. So one of us is wrong. If it's me, you can demonstrate
that by making it work. If it's you, you could figure that out by
trying it, seeing what goes wrong, and then thinking about how to deal
with that. I'm not saying you shouldn't ask for advice here, but you
should solicit that advice at the point where you come to a real fork
in the road, and "will the design work" isn't that.

After writing this email, I asked Claude to read the thread using the
pg.ddx.io MCP connector and do a technical assessment of your last
proposal. Here's what it said:

>>>
On the technical merits, I'd still expect it to fail. Splitting
pg_get_role_ddl() into CREATE ROLE, settings and membership functions
is sound: each function describes one thing, and ordering moves to the
caller. That fixes the restore-ordering problem at the API level. The
cost is that the caller has to do the multi-pass grantor ordering
itself, which removes most of the convenience for anyone who isn't
pg_dumpall. The central idea, having pg_dumpall call the source
server's functions so there's only one implementation, doesn't hold
up. The client needs to control its output to deal with version skew:
quoting newly reserved keywords, syntax the target server no longer
accepts, binary-upgrade variants, and bugs in the generator.
Server-side output is frozen at whatever minor release the source
runs, so the client would need its own code for these cases anyway,
and you'd have two implementations again with a more complicated split
between them. The functions would also need dump-specific modes
(target version, binary-upgrade, quote-all, and so on), so they would
grow into a backend copy of pg_dump's option handling. Roles are the
easiest case because there are few objects, the syntax is simple, and
per-object calls don't hurt performance. That makes them a misleading
pilot. Tables, with constraints split out for data loading and
partitioning, plus per-object calls on large schemas, are where this
breaks. The proposed equivalence tests are worth having, but they only
catch drift for options someone has already exercised. A new DDL
option still passes silently unless a test happens to use it.
Something like a catalog-coverage check that fails when a column isn't
handled would be needed to make drift detection reliable. The version
that could work is narrower: standalone "show me this object"
functions that make no promise to replace pg_dump, backed by coverage
tests strong enough to catch new options automatically.
<<<

It took less than a minute to get that answer, and writing this email
has taken me a lot more than a minute, and while I venture to hope
that my email is clearer than Claude's output, it does pretty much
tell you why your idea isn't going to work. I think that for a project
like this, if the level of due diligence that you're going to do
before posting is less than "paste your proposal into an LLM and see
what it says," the project probably won't succeed. Lots of people (me
included) would like this feature to exist, so the fact that it
doesn't exist is evidence that coming up with something good is
difficult. Even before LLMs, writing the code was never the hard part.
The hard part has always been figuring out a design that can answer
the inevitable objections. If someone here already knew how to do
that, this would likely be done already. Until you've thought about
this problem than everyone on this thread and have better ideas than
we do, there's probably no point in proposing anything.

-- 
Robert Haas
Databricks






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

* Re: pg_get_*_ddl() needs a redesign
  2026-08-27 01:52 pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 15:47 ` Re: pg_get_*_ddl() needs a redesign Melanie Plageman <melanieplageman@gmail.com>
  2026-09-09 16:24   ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-09 17:21     ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 17:34       ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-09 19:12         ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-10 03:59           ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-11 04:19             ` Re: pg_get_*_ddl() needs a redesign Robert Haas <robertmhaas@gmail.com>
  2026-09-11 04:55               ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-11 14:23                 ` Re: pg_get_*_ddl() needs a redesign Andres Freund <andres@anarazel.de>
  2026-09-11 15:14                   ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-11 15:24                     ` Re: pg_get_*_ddl() needs a redesign Robert Haas <robertmhaas@gmail.com>
  2026-09-11 15:58                       ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
@ 2026-09-11 16:34                         ` Marcos Pegoraro <marcos@f10.com.br>
  1 sibling, 0 replies; 32+ messages in thread

From: Marcos Pegoraro @ 2026-09-11 16:34 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Robert Haas <robertmhaas@gmail.com>; Andres Freund <andres@anarazel.de>; Noah Misch <noah@leadboat.com>; Andrew Dunstan <andrew@dunslane.net>; Melanie Plageman <melanieplageman@gmail.com>; gonzalemario@gmail.com; dbryan.green@gmail.com; euler@eulerto.com; pgsql-hackers

Em sex., 11 de set. de 2026 às 12:58, Tom Lane <tgl@sss.pgh.pa.us> escreveu:

> I'm voting for "discard the feature".


It's a shame. I don't know how much work this duplication would entail and
whether it's the best way to do it or not, but from a user's point of view,
it's really a shame.
For everyone who works with multi-tenant, these are functions that would
really help to clone schemas, for example.
dump/sed/restore is today the only way to do that today
with that I could
select 'create schema new_schema;' union all
select 'set search_path to new_schema;' union all
select pg_get_table_ddl(oid,schema_qualified=>false) from pg_class where
relkind = 'r' and relnamespace::regclass::text = 'old_schema';

regards
Marcos

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

* Re: pg_get_*_ddl() needs a redesign
  2026-08-27 01:52 pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 15:47 ` Re: pg_get_*_ddl() needs a redesign Melanie Plageman <melanieplageman@gmail.com>
  2026-09-09 16:24   ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-09 17:21     ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 17:34       ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-09 19:12         ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-10 03:59           ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-11 04:19             ` Re: pg_get_*_ddl() needs a redesign Robert Haas <robertmhaas@gmail.com>
  2026-09-11 04:55               ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-11 14:23                 ` Re: pg_get_*_ddl() needs a redesign Andres Freund <andres@anarazel.de>
@ 2026-09-11 15:14                   ` Robert Haas <robertmhaas@gmail.com>
  1 sibling, 0 replies; 32+ messages in thread

From: Robert Haas @ 2026-09-11 15:14 UTC (permalink / raw)
  To: Andres Freund <andres@anarazel.de>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Noah Misch <noah@leadboat.com>; Andrew Dunstan <andrew@dunslane.net>; Melanie Plageman <melanieplageman@gmail.com>; gonzalemario@gmail.com; dbryan.green@gmail.com; euler@eulerto.com; pgsql-hackers

On Fri, Sep 11, 2026 at 10:23 AM Andres Freund <andres@anarazel.de> wrote:
> > 2. pg_dump just calls the source server's DDL-reconstruction functions
> > and doesn't have to worry about version skew.
>
> Isn't the problem with that that we occasionally need to adapt the syntax
> between versions to some degree? I think it has become less common, but I'm a
> bit sceptical that it's wise to decide we won't ever again need that...

+1.

> > (B) pg_dump slices and dices the data in ways that don't necessarily
> > make sense for standalone usage.  For example it doesn't want to
> > mention a primary key when creating a table, rather it wants to add
> > that constraint (and build the index) after loading data.
>
> Yep, that seems nontrivial.

The kind of scenario Tom mentions here is exactly why I'm unwilling to
take Noah's criticisms purely at face value. Dealing with dependencies
means splitting up the creation of single objects into multiple DDL
commands in weird ways. But if you just want the definition of one
single object expressed in the most straightforward way, you are going
to want the primary key as part of the object definition, not a
separate, broken-out statement. There are use cases for both things.
If we judge the facility that was built here as a substitute for
pg_dump, it's fatally flawed and should come straight out of the tree
and be deposited directly and permanently into the circular file,
which seems to be what Noah wants. But if we judge it as having a
separate purpose, then the question is how well it serves that
purpose. And the phrase Tom uses, "standalone usage," is at least
sketch of a purpose where dependency handling is irrelevant and
perhaps even undesirable.

-- 
Robert Haas





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

* Re: pg_get_*_ddl() needs a redesign
  2026-08-27 01:52 pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 15:47 ` Re: pg_get_*_ddl() needs a redesign Melanie Plageman <melanieplageman@gmail.com>
  2026-09-09 16:24   ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-09 17:21     ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 17:34       ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-09 19:12         ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-10 03:59           ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-11 04:19             ` Re: pg_get_*_ddl() needs a redesign Robert Haas <robertmhaas@gmail.com>
  2026-09-11 04:55               ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
@ 2026-09-12 14:02                 ` Andrew Dunstan <andrew@dunslane.net>
  1 sibling, 0 replies; 32+ messages in thread

From: Andrew Dunstan @ 2026-09-12 14:02 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; Robert Haas <robertmhaas@gmail.com>; +Cc: Noah Misch <noah@leadboat.com>; Melanie Plageman <melanieplageman@gmail.com>; gonzalemario@gmail.com; dbryan.green@gmail.com; euler@eulerto.com; pgsql-hackers


On 2026-09-11 Fr 12:55 AM, Tom Lane wrote:
> The hard parts as I see it are
>
> (A) pg_dump is optimized to gather data across the entire database
> at once.  Converting it to call functions that produce info about
> a single object at a time would almost certainly be catastrophic
> for performance on large databases.
>
> (B) pg_dump slices and dices the data in ways that don't necessarily
> make sense for standalone usage.  For example it doesn't want to
> mention a primary key when creating a table, rather it wants to add
> that constraint (and build the index) after loading data.
>
> I do not feel that these problems are necessarily insoluble, but
> they do require some hard work to define the server-side functionality
> properly.
>
> 			


I think you've put your finger on some of the main issues. The main use 
case in my mind from the get go was not "How do we make this work for 
pg_dump?" but "I want to create an object that's like this thing but a 
bit different. Give me the DDL for this thing so I can tinker with it." 
That's the use case that people just about always give me when I've 
talked to them about this.

Maybe point A is not insoluble, but I've thought all along that it was a 
pretty significant barrier, and I don't have a good solution for it. 
Making this feature contingent on solving that problem would sacrifice 
the originally intended use case, which would be very sad.

Your point B is also well taken. pg_dump formats and arranges the SQL to 
suit its purposes, but that should not be taken as the canonical 
arrangement for other uses. Perhaps these functions should have a "dump" 
flavor that produces output like pg_dump/all.


cheers


andrew

--
Andrew Dunstan
EDB: https://www.enterprisedb.com







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

* Re: pg_get_*_ddl() needs a redesign
  2026-08-27 01:52 pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 15:47 ` Re: pg_get_*_ddl() needs a redesign Melanie Plageman <melanieplageman@gmail.com>
  2026-09-09 16:24   ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-09 17:21     ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 17:34       ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-09 19:12         ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-10 03:59           ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-11 04:19             ` Re: pg_get_*_ddl() needs a redesign Robert Haas <robertmhaas@gmail.com>
@ 2026-09-11 05:26               ` Noah Misch <noah@leadboat.com>
  2026-09-11 12:24                 ` Re: pg_get_*_ddl() needs a redesign Robert Haas <robertmhaas@gmail.com>
  1 sibling, 1 reply; 32+ messages in thread

From: Noah Misch @ 2026-09-11 05:26 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; +Cc: Andrew Dunstan <andrew@dunslane.net>; Tom Lane <tgl@sss.pgh.pa.us>; Melanie Plageman <melanieplageman@gmail.com>; gonzalemario@gmail.com; dbryan.green@gmail.com; euler@eulerto.com; pgsql-hackers

On Fri, Sep 11, 2026 at 12:19:15AM -0400, Robert Haas wrote:
> On Thu, Sep 10, 2026 at 12:00 AM Noah Misch <noah@leadboat.com> wrote:
> > Going forward, feel free to add me to the To: line of a mailing list post and
> > explicitly ask me for my guess about the project's overall prognosis, likely
> > ways of failing, etc.  My guess may be brief and/or wrong, but I'll provide
> > one.
> 
> I don't think this is how this mailing list works. The volume is
> overwhelming for me, too, but patch authors aren't obliged to cc
> anyone specifially.

To clarify, that text was me offering Andrew a new option, not suggesting that
he has any new duty.

> > When it's four months after feature freeze and I find non-subtle, unreported
> > defects in the feature, the development process wasn't adequate for the
> > subject matter.  To be transparent, observing this outcome changed my view of
> > code duplication.  Duplication was always a smell, but it seemed like a
> > plausible compromise tactic in 2025.  Now I find the duplication gave wrong
> > code too much place to hide.
> 
> I think we would do well to confine all of our present conversations,
> insofar as it is possible to do so, to whether any given feature
> contains defects incompatible with shipping it.

The defects are the reason not to ship this implementation.  One of those
defects, the inability to restore in dependency order, cannot be fixed without
redesigning the current SQL-facing API.  That is the reason not to ship this
design.  See my original post of this thread for details.






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

* Re: pg_get_*_ddl() needs a redesign
  2026-08-27 01:52 pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 15:47 ` Re: pg_get_*_ddl() needs a redesign Melanie Plageman <melanieplageman@gmail.com>
  2026-09-09 16:24   ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-09 17:21     ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 17:34       ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-09 19:12         ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-10 03:59           ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-11 04:19             ` Re: pg_get_*_ddl() needs a redesign Robert Haas <robertmhaas@gmail.com>
  2026-09-11 05:26               ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
@ 2026-09-11 12:24                 ` Robert Haas <robertmhaas@gmail.com>
  2026-09-11 13:35                   ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  0 siblings, 1 reply; 32+ messages in thread

From: Robert Haas @ 2026-09-11 12:24 UTC (permalink / raw)
  To: Noah Misch <noah@leadboat.com>; +Cc: Andrew Dunstan <andrew@dunslane.net>; Tom Lane <tgl@sss.pgh.pa.us>; Melanie Plageman <melanieplageman@gmail.com>; gonzalemario@gmail.com; dbryan.green@gmail.com; euler@eulerto.com; pgsql-hackers

On Fri, Sep 11, 2026 at 1:27 AM Noah Misch <noah@leadboat.com> wrote:
> > I think we would do well to confine all of our present conversations,
> > insofar as it is possible to do so, to whether any given feature
> > contains defects incompatible with shipping it.
>
> The defects are the reason not to ship this implementation.  One of those
> defects, the inability to restore in dependency order, cannot be fixed without
> redesigning the current SQL-facing API.  That is the reason not to ship this
> design.  See my original post of this thread for details.

I saw that, but that seems like you're questioning the feature's
choice of scope as much as its actual merits. I suppose the idea was
that this feature is for getting the definition of an individual
object for possible cloning into this database or some other where the
prerequisites are already present. If the feature had the intention of
allowing for full-database restoration and failed to do so, that's a
code defect. Otherwise, it isn't. If the feature could reasonably have
been designed in such a way that it would allow for full-database
restoration but was not actually designed in such a way, that's a
design defect. It's not obvious to me that this is the case, but it
might be. If there's no reasonable way to make a feature of this type
suitable for that use case, this isn't a defect at all, just code that
does something that you may not find entirely worthwhile. Regardless,
I'm not saying that you have to like this feature -- I don't think
it's great either, although it seems I dislike it less than you -- but
I think fairness demands that we not label as code defects issues that
are properly categorized otherwise.

-- 
Robert Haas





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

* Re: pg_get_*_ddl() needs a redesign
  2026-08-27 01:52 pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 15:47 ` Re: pg_get_*_ddl() needs a redesign Melanie Plageman <melanieplageman@gmail.com>
  2026-09-09 16:24   ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-09 17:21     ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 17:34       ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-09 19:12         ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-10 03:59           ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-11 04:19             ` Re: pg_get_*_ddl() needs a redesign Robert Haas <robertmhaas@gmail.com>
  2026-09-11 05:26               ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-11 12:24                 ` Re: pg_get_*_ddl() needs a redesign Robert Haas <robertmhaas@gmail.com>
@ 2026-09-11 13:35                   ` Noah Misch <noah@leadboat.com>
  2026-09-11 14:08                     ` Re: pg_get_*_ddl() needs a redesign Robert Haas <robertmhaas@gmail.com>
  0 siblings, 1 reply; 32+ messages in thread

From: Noah Misch @ 2026-09-11 13:35 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; +Cc: Andrew Dunstan <andrew@dunslane.net>; Tom Lane <tgl@sss.pgh.pa.us>; Melanie Plageman <melanieplageman@gmail.com>; gonzalemario@gmail.com; dbryan.green@gmail.com; euler@eulerto.com; pgsql-hackers

On Fri, Sep 11, 2026 at 08:24:50AM -0400, Robert Haas wrote:
> On Fri, Sep 11, 2026 at 1:27 AM Noah Misch <noah@leadboat.com> wrote:
> > > I think we would do well to confine all of our present conversations,
> > > insofar as it is possible to do so, to whether any given feature
> > > contains defects incompatible with shipping it.
> >
> > The defects are the reason not to ship this implementation.  One of those
> > defects, the inability to restore in dependency order, cannot be fixed without
> > redesigning the current SQL-facing API.  That is the reason not to ship this
> > design.  See my original post of this thread for details.
> 
> I saw that, but that seems like you're questioning the feature's
> choice of scope as much as its actual merits.

That is not the case.

> I suppose the idea was
> that this feature is for getting the definition of an individual
> object for possible cloning into this database or some other where the
> prerequisites are already present. If the feature had the intention of
> allowing for full-database restoration and failed to do so, that's a
> code defect. Otherwise, it isn't.

The first discussion linked from the 76e514e commit message, [1], described
the "main use case" as "dumping role definitions for migration or backup
purposes without needing pg_dumpall".  My review findings are about failures
that arise when using the feature as part of a migration.

[1] https://postgr.es/m/4c5f895e-3281-48f8-b943-9228b7da6471@gmail.com






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

* Re: pg_get_*_ddl() needs a redesign
  2026-08-27 01:52 pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 15:47 ` Re: pg_get_*_ddl() needs a redesign Melanie Plageman <melanieplageman@gmail.com>
  2026-09-09 16:24   ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-09 17:21     ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-09 17:34       ` Re: pg_get_*_ddl() needs a redesign Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-09 19:12         ` Re: pg_get_*_ddl() needs a redesign Andrew Dunstan <andrew@dunslane.net>
  2026-09-10 03:59           ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-11 04:19             ` Re: pg_get_*_ddl() needs a redesign Robert Haas <robertmhaas@gmail.com>
  2026-09-11 05:26               ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
  2026-09-11 12:24                 ` Re: pg_get_*_ddl() needs a redesign Robert Haas <robertmhaas@gmail.com>
  2026-09-11 13:35                   ` Re: pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
@ 2026-09-11 14:08                     ` Robert Haas <robertmhaas@gmail.com>
  0 siblings, 0 replies; 32+ messages in thread

From: Robert Haas @ 2026-09-11 14:08 UTC (permalink / raw)
  To: Noah Misch <noah@leadboat.com>; +Cc: Andrew Dunstan <andrew@dunslane.net>; Tom Lane <tgl@sss.pgh.pa.us>; Melanie Plageman <melanieplageman@gmail.com>; gonzalemario@gmail.com; dbryan.green@gmail.com; euler@eulerto.com; pgsql-hackers

On Fri, Sep 11, 2026 at 9:35 AM Noah Misch <noah@leadboat.com> wrote:
> The first discussion linked from the 76e514e commit message, [1], described
> the "main use case" as "dumping role definitions for migration or backup
> purposes without needing pg_dumpall".  My review findings are about failures
> that arise when using the feature as part of a migration.
>
> [1] https://postgr.es/m/4c5f895e-3281-48f8-b943-9228b7da6471@gmail.com

I think you're absolutizing this to a greater degree than seems fair
to me. I agree with you that the justification for not including
passwords in the output doesn't make sense; IMHO, not including them
is just incorrect behavior. The dependency handling thing I do not
find so black-and-white. I think that point merits discussion, rather
than conclusory statements.

-- 
Robert Haas





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


end of thread, other threads:[~2026-11-04 13:53 UTC | newest]

Thread overview: 32+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2026-08-27 01:52 pg_get_*_ddl() needs a redesign Noah Misch <noah@leadboat.com>
2026-09-09 15:47 ` Melanie Plageman <melanieplageman@gmail.com>
2026-09-09 16:24   ` Andrew Dunstan <andrew@dunslane.net>
2026-09-09 17:21     ` Noah Misch <noah@leadboat.com>
2026-09-09 17:34       ` Tom Lane <tgl@sss.pgh.pa.us>
2026-09-09 18:05         ` Nathan Bossart <nathandbossart@gmail.com>
2026-09-09 19:12         ` Andrew Dunstan <andrew@dunslane.net>
2026-09-09 20:12           ` Andres Freund <andres@anarazel.de>
2026-09-09 22:25             ` Andrew Dunstan <andrew@dunslane.net>
2026-09-10 23:59               ` Andrew Dunstan <andrew@dunslane.net>
2026-09-13 18:28                 ` Andrew Dunstan <andrew@dunslane.net>
2026-09-14 02:21                   ` Michael Paquier <michael@paquier.xyz>
2026-09-14 04:02                     ` Andrew Dunstan <andrew@dunslane.net>
2026-09-10 03:59           ` Noah Misch <noah@leadboat.com>
2026-09-11 04:19             ` Robert Haas <robertmhaas@gmail.com>
2026-09-11 04:55               ` Tom Lane <tgl@sss.pgh.pa.us>
2026-09-11 14:23                 ` Andres Freund <andres@anarazel.de>
2026-09-11 15:14                   ` Tom Lane <tgl@sss.pgh.pa.us>
2026-09-11 15:24                     ` Robert Haas <robertmhaas@gmail.com>
2026-09-11 15:58                       ` Tom Lane <tgl@sss.pgh.pa.us>
2026-09-11 16:27                         ` Robert Haas <robertmhaas@gmail.com>
2026-10-19 16:03                           ` Mario González <gonzalemario@gmail.com>
2026-10-20 17:16                             ` Noah Misch <noah@leadboat.com>
2026-10-21 13:35                               ` Mario González <gonzalemario@gmail.com>
2026-11-04 13:53                             ` Robert Haas <robertmhaas@gmail.com>
2026-09-11 16:34                         ` Marcos Pegoraro <marcos@f10.com.br>
2026-09-11 15:14                   ` Robert Haas <robertmhaas@gmail.com>
2026-09-12 14:02                 ` Andrew Dunstan <andrew@dunslane.net>
2026-09-11 05:26               ` Noah Misch <noah@leadboat.com>
2026-09-11 12:24                 ` Robert Haas <robertmhaas@gmail.com>
2026-09-11 13:35                   ` Noah Misch <noah@leadboat.com>
2026-09-11 14:08                     ` Robert Haas <robertmhaas@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