Thanks for testing the patch!

On Mon Nov 23, 2026 at 6:59 PM -03, Zsolt Parragi wrote:
> The following shape still doesn't work properly with v5:
>
> create type ct as (i int);
> create function ct_mk(int) returns ct language sql as 'select row($1)::ct';
> create table t2 (x int check ((ct_mk(x)).i > 0));
> insert into t2 values (1);
> create domain d as int constraint d_check check ((ct_mk(value)).i > 0);
> comment on constraint d_check on domain d is 'bob comment';
>
> s1: begin; select count(*) from t2;
> s2: alter type ct alter attribute i type bigint; (waits for t2)
> s3: alter domain d rename to d_old; create domain d as int;
> s1: commit;
>
> -- master: s2 fails
> ERROR:  could not identify relation associated with constraint 16408
>
> -- v5: s2 succeeds, and
> select t.typname, c.conname, obj_description(c.oid,'pg_constraint')
>   from pg_constraint c join pg_type t on t.oid = c.contypid;
>  d       | d_check | bob comment
> select (-1)::d_old;
>  d_old
> -------
>     -1
>
>> We may try to capture the domain oid above AlterDomainAddConstraint,
>> while the old constraint still exists and re-add the constraint to that
>> OID instead of resolving the name again.
>
> That doesn't seem that complicated to me, and it would fix the above issue?
>

Yes, you're right, it wasn't that complicated, and I think any fix for
your case that doesn't capture the OID would be more complicated. v6
attached does this.

The re-add now takes the domain's OID from the old constraint in
ATPostAlterTypeParse(), while it still exists, and re-adds the
constraint to that OID instead of resolving the name from the deparsed
definition again.

Changes in v6, all in 0003:

- AT_ReAddDomainConstraint now carries a new ad-hoc node,
  ATReAddDomainConstraint, with the domain OID, the constraint and its
  comment, instead of the AlterDomainStmt.

- The domain is locked with AccessShareLock when its OID is captured, so
  a concurrent DROP DOMAIN after that point waits for the ALTER instead
  of removing the domain before the constraint is re-added.

- Since the OID now comes from the old constraint, I think that the "is
  not a domain" check can't be reached from SQL anymore, so it's an
  elog() now.

- The comment on a domain constraint is restored right after the re-add,
  using the new constraint's OID, so it can't end up on another domain
  either. RebuildConstraintComment() now handles only table constraints.

- Added your scenario as an isolation test. With v5 it shows d_check and
  its comment on the new d; with v6 they stay on d_old and (-1)::d_old
  fails again.

Regarding back-patching, I think that we will need a different 0003
patch for older versions because of the new node type. Another option is
to keep the OIDs in a list in AlteredTableInfo instead of adding a new
node, which I think could then be back-patched as is. But I'm not sure
this issue is common enough to justify that approach (I'm not a big fan
of it, but I'm OK with it if we decide that we need to back-patch).
Thoughts?

--
Matheus Alcantara
EDB: https://www.enterprisedb.com
From 317b77aa63fd56bf92a46040ec53cb165e22e2b5 Mon Sep 17 00:00:00 2001
From: Nitin Motiani <[email protected]>
Date: Mon, 28 Sep 2026 12:49:33 +0000
Subject: [PATCH v6 1/3] Fix ALTER ... TYPE failure with dependent domain
 constraints.

When ALTER TYPE ... ALTER ATTRIBUTE ... TYPE or ALTER TABLE ... ALTER
COLUMN ... TYPE changes a column that a domain's CHECK constraint
depends on, ATPostAlterTypeCleanup() arranges for the constraint to be
dropped and re-created.  Since commit af20e2d72, it chose the relation
to attach the re-creation step to by calling
get_typ_typrelid(getBaseType(con->contypid)), which only works if the
domain's base type is composite.  For a domain whose base type isn't
composite (for example int, float8 or int[], possibly via another
domain) but whose CHECK expression references a composite type or a
table's row type, that returned InvalidOid, and the command failed
with "could not identify relation associated with constraint".

For a domain constraint, that relation OID only decides whether
another relation gets locked and which work queue entry receives the
AT_ReAddDomainConstraint command; the command itself identifies the
domain by name.  So just use the relation being altered (tab->relid),
which is already locked.

A side effect is that for a domain over a composite type other than
the one being altered, we no longer lock that other type's relation or
add a work queue entry for it, neither of which was needed.

Since commit ac460a144ac, find_composite_type_dependencies() rejects
the ALTER up front when the CHECK expression references the composite
type directly, e.g. via ROW(value)::rt, so the originally reported case
now fails with a proper "cannot alter type" error.  The problem is still
reachable when the expression only depends on a column of the type, for
example by applying a field selection to a function returning it, so
the tests use that form.

Bug: #19724
Reported-by: Alexander Lakhin <[email protected]>
Author: Nitin Motiani <[email protected]>
Reviewed-by: Ayush Tiwari <[email protected]>
Reviewed-by: Rahul Yadav <[email protected]>
Reviewed-by: Matheus Alcantara <[email protected]>
---
 src/backend/commands/tablecmds.c     | 12 ++--
 src/test/regress/expected/domain.out | 95 ++++++++++++++++++++++++++++
 src/test/regress/sql/domain.sql      | 68 ++++++++++++++++++++
 3 files changed, 171 insertions(+), 4 deletions(-)

diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c
index 9786a5af58a..591a0c9528c 100644
--- a/src/backend/commands/tablecmds.c
+++ b/src/backend/commands/tablecmds.c
@@ -16833,10 +16833,14 @@ ATPostAlterTypeCleanup(List **wqueue, 
AlteredTableInfo *tab, LOCKMODE lockmode)
                        relid = con->conrelid;
                else
                {
-                       /* must be a domain constraint */
-                       relid = get_typ_typrelid(getBaseType(con->contypid));
-                       if (!OidIsValid(relid))
-                               elog(ERROR, "could not identify relation 
associated with constraint %u", oldId);
+                       /*
+                        * Must be a domain constraint.  The domain's base type 
need not
+                        * be composite, so there may be no relation associated 
with it.
+                        * Since the relid is only used to determine which work 
queue
+                        * entry the command is attached to, we can use the 
relation which
+                        * is being altered and which we already hold a lock on.
+                        */
+                       relid = tab->relid;
                }
                confrelid = con->confrelid;
                conislocal = con->conislocal;
diff --git a/src/test/regress/expected/domain.out 
b/src/test/regress/expected/domain.out
index 62a48a523a2..1caa96cdee2 100644
--- a/src/test/regress/expected/domain.out
+++ b/src/test/regress/expected/domain.out
@@ -432,6 +432,101 @@ select conname, obj_description(oid, 'pg_constraint') 
from pg_constraint
 
 drop type comptype cascade;
 NOTICE:  drop cascades to type dcomptype
+-- check altering columns used by constraints of domains whose base type
+-- isn't composite (bug #19724).  A direct reference to the composite type
+-- in the CHECK expression makes find_composite_type_dependencies() reject
+-- the ALTER, so reach it through a function returning the type instead;
+-- that leaves only a dependency on the referenced column.
+create type rt as (i int);
+create domain dt as int check ((row(value)::rt).i > 0);
+alter type rt alter attribute i type bigint;  -- fail
+ERROR:  cannot alter type "rt" because constraint dt_check uses it
+drop domain dt;
+create function rt_mk(int) returns rt language sql as 'select row($1)::rt';
+create domain dt as int check ((rt_mk(value)).i > 0);
+alter type rt alter attribute i type text;  -- fail
+ERROR:  operator does not exist: text > integer
+DETAIL:  No operator of that name accepts the given argument types.
+HINT:  You might need to add explicit type casts.
+alter type rt alter attribute i type bigint;
+select 1::dt;
+ dt 
+----
+  1
+(1 row)
+
+select (-1)::dt;  -- fail
+ERROR:  value for domain dt violates check constraint "dt_check"
+drop domain dt;
+drop function rt_mk(int);
+drop type rt;
+-- same for a domain over float8 that uses one field of a two-field type
+create type comptype as (r float8, i float8);
+create function comptype_mk(float8) returns comptype language sql
+  as 'select row($1, 0)::comptype';
+create domain silly as float8 check ((comptype_mk(value)).r > 0);
+alter type comptype alter attribute r type bigint;
+select 1.0::silly;
+ silly 
+-------
+     1
+(1 row)
+
+select (-1.0)::silly;  -- fail
+ERROR:  value for domain silly violates check constraint "silly_check"
+drop domain silly;
+drop function comptype_mk(float8);
+drop type comptype;
+-- rebuilding a constraint for one type it depends on must preserve its
+-- dependency on another
+create type r1 as (a int);
+create type r2 as (b int);
+create function r1_mk(int) returns r1 language sql as 'select row($1)::r1';
+create function r2_mk(int) returns r2 language sql as 'select row($1)::r2';
+create domain dt_multi as int
+  check ((r1_mk(value)).a > 0 and (r2_mk(value)).b > 0);
+alter type r1 alter attribute a type bigint;
+alter type r2 alter attribute b type text;  -- fail
+ERROR:  operator does not exist: text > integer
+DETAIL:  No operator of that name accepts the given argument types.
+HINT:  You might need to add explicit type casts.
+alter type r2 alter attribute b type bigint;
+select 1::dt_multi;
+ dt_multi 
+----------
+        1
+(1 row)
+
+select (-1)::dt_multi;  -- fail
+ERROR:  value for domain dt_multi violates check constraint "dt_multi_check"
+drop domain dt_multi;
+drop function r1_mk(int);
+drop function r2_mk(int);
+drop type r1;
+drop type r2;
+-- same via ALTER TABLE, with the constraint depending on both the parent's
+-- and the inheritance child's row types
+create table dp (a int);
+create table dc (b int) inherits (dp);
+create function dp_mk(int) returns dp language sql as 'select row($1)::dp';
+create function dc_mk(int) returns dc language sql
+  as 'select row($1, $1)::dc';
+create domain dt_inh as int
+  check ((dp_mk(value)).a > 0 and (dc_mk(value)).a > 0);
+alter table dp alter column a type bigint;
+select 1::dt_inh;
+ dt_inh 
+--------
+      1
+(1 row)
+
+select (-1)::dt_inh;  -- fail
+ERROR:  value for domain dt_inh violates check constraint "dt_inh_check"
+drop domain dt_inh;
+drop function dp_mk(int);
+drop function dc_mk(int);
+drop table dc;
+drop table dp;
 -- Test domains over arrays of composite
 create type comptype as (r float8, i float8);
 create domain dcomptypea as comptype[];
diff --git a/src/test/regress/sql/domain.sql b/src/test/regress/sql/domain.sql
index b8f5a639712..0f874a365e3 100644
--- a/src/test/regress/sql/domain.sql
+++ b/src/test/regress/sql/domain.sql
@@ -219,6 +219,74 @@ select conname, obj_description(oid, 'pg_constraint') from 
pg_constraint
 
 drop type comptype cascade;
 
+-- check altering columns used by constraints of domains whose base type
+-- isn't composite (bug #19724).  A direct reference to the composite type
+-- in the CHECK expression makes find_composite_type_dependencies() reject
+-- the ALTER, so reach it through a function returning the type instead;
+-- that leaves only a dependency on the referenced column.
+create type rt as (i int);
+create domain dt as int check ((row(value)::rt).i > 0);
+alter type rt alter attribute i type bigint;  -- fail
+drop domain dt;
+create function rt_mk(int) returns rt language sql as 'select row($1)::rt';
+create domain dt as int check ((rt_mk(value)).i > 0);
+alter type rt alter attribute i type text;  -- fail
+alter type rt alter attribute i type bigint;
+select 1::dt;
+select (-1)::dt;  -- fail
+drop domain dt;
+drop function rt_mk(int);
+drop type rt;
+
+-- same for a domain over float8 that uses one field of a two-field type
+create type comptype as (r float8, i float8);
+create function comptype_mk(float8) returns comptype language sql
+  as 'select row($1, 0)::comptype';
+create domain silly as float8 check ((comptype_mk(value)).r > 0);
+alter type comptype alter attribute r type bigint;
+select 1.0::silly;
+select (-1.0)::silly;  -- fail
+drop domain silly;
+drop function comptype_mk(float8);
+drop type comptype;
+
+-- rebuilding a constraint for one type it depends on must preserve its
+-- dependency on another
+create type r1 as (a int);
+create type r2 as (b int);
+create function r1_mk(int) returns r1 language sql as 'select row($1)::r1';
+create function r2_mk(int) returns r2 language sql as 'select row($1)::r2';
+create domain dt_multi as int
+  check ((r1_mk(value)).a > 0 and (r2_mk(value)).b > 0);
+alter type r1 alter attribute a type bigint;
+alter type r2 alter attribute b type text;  -- fail
+alter type r2 alter attribute b type bigint;
+select 1::dt_multi;
+select (-1)::dt_multi;  -- fail
+drop domain dt_multi;
+drop function r1_mk(int);
+drop function r2_mk(int);
+drop type r1;
+drop type r2;
+
+-- same via ALTER TABLE, with the constraint depending on both the parent's
+-- and the inheritance child's row types
+create table dp (a int);
+create table dc (b int) inherits (dp);
+create function dp_mk(int) returns dp language sql as 'select row($1)::dp';
+create function dc_mk(int) returns dc language sql
+  as 'select row($1, $1)::dc';
+create domain dt_inh as int
+  check ((dp_mk(value)).a > 0 and (dc_mk(value)).a > 0);
+alter table dp alter column a type bigint;
+select 1::dt_inh;
+select (-1)::dt_inh;  -- fail
+drop domain dt_inh;
+drop function dp_mk(int);
+drop function dc_mk(int);
+drop table dc;
+drop table dp;
+
 
 -- Test domains over arrays of composite
 
-- 
2.50.1 (Apple Git-155)

From aa520706429d39c27b9fce0e2da0090e09a8234c Mon Sep 17 00:00:00 2001
From: Matheus Alcantara <[email protected]>
Date: Mon, 28 Sep 2026 15:05:36 -0300
Subject: [PATCH v6 2/3] Validate re-added domain constraints after ALTER TABLE
 rewrites

When ALTER TABLE ... ALTER COLUMN TYPE (or ALTER TYPE ... ALTER
ATTRIBUTE) rebuilds a domain CHECK constraint whose expression depends
on the altered column, the constraint was re-added through
AlterDomainAddConstraint(), which validates it immediately against all
columns of the domain. That happens during Phase 2, before Phase 3 has
rewritten the affected tables, so any table that is pending a rewrite
and has a column of the domain was scanned using its new tuple
descriptor over its old heap. This could produce garbage values,
spurious "contains values that violate the new constraint" errors, or
worse, e.g. "type with OID 4294967295 does not exist" when the domain is
over a composite type.

Fix by skipping validation in AlterDomainAddConstraint() when re-adding
a constraint, and instead having ATExecCmd() remember the rebuilt
constraint so that ATRewriteTables() validates it once all tables have
been rewritten. Constraints that were NOT VALID are not validated, as
before.

This problem dates back to af20e2d72, which added rebuilding of domain
constraints, but was previously only reachable with domains over
composite types, since other domains hit the "could not identify
relation associated with constraint" error instead.
---
 src/backend/commands/tablecmds.c     |  59 ++++++++++++--
 src/backend/commands/typecmds.c      |  11 ++-
 src/include/commands/typecmds.h      |   1 +
 src/test/regress/expected/domain.out | 112 +++++++++++++++++++++++++++
 src/test/regress/sql/domain.sql      |  76 ++++++++++++++++++
 5 files changed, 250 insertions(+), 9 deletions(-)

diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c
index 591a0c9528c..13e3177961b 100644
--- a/src/backend/commands/tablecmds.c
+++ b/src/backend/commands/tablecmds.c
@@ -201,6 +201,8 @@ typedef struct AlteredTableInfo
        bool            chgPersistence; /* T if SET LOGGED/UNLOGGED is used */
        char            newrelpersistence;      /* if above is true */
        Expr       *partition_constraint;       /* for attach partition 
validation */
+       /* OIDs of re-added domain CHECK constraints to validate in Phase 3 */
+       List       *domain_constraints;
        /* true, if validating default due to some other attach/detach */
        bool            validate_default;
        /* Objects to rebuild after ALTER TYPE or SET EXPRESSION operations */
@@ -5560,11 +5562,28 @@ ATExecCmd(List **wqueue, AlteredTableInfo *tab,
                        break;
                case AT_ReAddDomainConstraint:  /* Re-add pre-existing domain 
check
                                                                                
 * constraint */
-                       address =
-                               AlterDomainAddConstraint(((AlterDomainStmt *) 
cmd->def)->typeName,
-                                                                               
 ((AlterDomainStmt *) cmd->def)->def,
-                                                                               
 NULL, true);
-                       break;
+                       {
+                               AlterDomainStmt *stmt = (AlterDomainStmt *) 
cmd->def;
+                               Constraint *con = castNode(Constraint, 
stmt->def);
+                               ObjectAddress constrAddr = InvalidObjectAddress;
+
+                               /* only CHECK constraints can depend on a 
column */
+                               Assert(con->contype == CONSTR_CHECK);
+
+                               address = 
AlterDomainAddConstraint(stmt->typeName, stmt->def,
+                                                                               
                   &constrAddr, true);
+
+                               /*
+                                * AlterDomainAddConstraint doesn't validate 
re-added
+                                * constraints, since tables using the domain 
may not have
+                                * been rewritten yet. Tell Phase 3 to do it.
+                                */
+                               if (!con->skip_validation)
+                                       tab->domain_constraints =
+                                               
lappend_oid(tab->domain_constraints,
+                                                                       
constrAddr.objectId);
+                               break;
+                       }
                case AT_ReAddComment:   /* Re-add existing comment */
                        address = CommentObject((CommentStmt *) cmd->def);
                        break;
@@ -6187,6 +6206,36 @@ ATRewriteTables(AlterTableStmt *parsetree, List 
**wqueue, LOCKMODE lockmode,
                        table_close(rel, NoLock);
        }
 
+       /*
+        * Validate re-added domain CHECK constraints.  This must wait until all
+        * tables have been rewritten, since any of them might contain columns 
of
+        * the domain. Don't skip relations without storage since the work queue
+        * entry might be for a standalone composite type.
+        */
+       foreach(ltab, *wqueue)
+       {
+               AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
+
+               foreach_oid(conoid, tab->domain_constraints)
+               {
+                       HeapTuple       tup;
+                       Form_pg_constraint con;
+                       Datum           conbin;
+
+                       tup = SearchSysCache1(CONSTROID, 
ObjectIdGetDatum(conoid));
+                       if (!HeapTupleIsValid(tup))
+                               elog(ERROR, "cache lookup failed for constraint 
%u", conoid);
+                       con = (Form_pg_constraint) GETSTRUCT(tup);
+
+                       conbin = SysCacheGetAttrNotNull(CONSTROID, tup,
+                                                                               
        Anum_pg_constraint_conbin);
+                       validateDomainCheckConstraint(con->contypid,
+                                                                               
  TextDatumGetCString(conbin));
+
+                       ReleaseSysCache(tup);
+               }
+       }
+
        /* Finally, run any afterStmts that were queued up */
        foreach(ltab, *wqueue)
        {
diff --git a/src/backend/commands/typecmds.c b/src/backend/commands/typecmds.c
index 9f57728129f..8d76dc6c579 100644
--- a/src/backend/commands/typecmds.c
+++ b/src/backend/commands/typecmds.c
@@ -128,7 +128,6 @@ static Oid  findTypeSubscriptingFunction(List *procname, 
Oid typeOid);
 static Oid     findRangeSubOpclass(List *opcname, Oid subtype);
 static Oid     findRangeCanonicalFunction(List *procname, Oid typeOid);
 static Oid     findRangeSubtypeDiffFunction(List *procname, Oid subtype);
-static void validateDomainCheckConstraint(Oid domainoid, const char *ccbin);
 static void validateDomainNotNullConstraint(Oid domainoid);
 static List *get_rels_with_domain(Oid domainOid, LOCKMODE lockmode);
 static void checkEnumOwner(HeapTuple tup);
@@ -3053,13 +3052,17 @@ AlterDomainAddConstraint(List *names, Node 
*newConstraint,
                                                                                
 constr, NameStr(typTup->typname), constrAddr,
                                                                                
 is_readd);
 
-
                /*
                 * If requested to validate the constraint, test all values 
stored in
                 * the attributes based on the domain the constraint is being 
added
                 * to.
+                *
+                * When re-adding a constraint during ALTER TABLE, the tables 
using
+                * the domain might not have been rewritten to match their new
+                * catalog definitions yet, so the caller must do the 
validation after
+                * its rewrite phase instead.
                 */
-               if (!constr->skip_validation)
+               if (!constr->skip_validation && !is_readd)
                        validateDomainCheckConstraint(domainoid, ccbin);
 
                /*
@@ -3273,7 +3276,7 @@ validateDomainNotNullConstraint(Oid domainoid)
  * Verify that all columns currently using the domain satisfy the given check
  * constraint expression.
  */
-static void
+void
 validateDomainCheckConstraint(Oid domainoid, const char *ccbin)
 {
        Expr       *expr = (Expr *) stringToNode(ccbin);
diff --git a/src/include/commands/typecmds.h b/src/include/commands/typecmds.h
index 2112b4addd2..a067651f6f9 100644
--- a/src/include/commands/typecmds.h
+++ b/src/include/commands/typecmds.h
@@ -38,6 +38,7 @@ extern ObjectAddress AlterDomainAddConstraint(List *names, 
Node *newConstraint,
                                                                                
          ObjectAddress *constrAddr,
                                                                                
          bool is_readd);
 extern ObjectAddress AlterDomainValidateConstraint(List *names, const char 
*constrName);
+extern void validateDomainCheckConstraint(Oid domainoid, const char *ccbin);
 extern ObjectAddress AlterDomainDropConstraint(List *names, const char 
*constrName,
                                                                                
           DropBehavior behavior, bool missing_ok);
 
diff --git a/src/test/regress/expected/domain.out 
b/src/test/regress/expected/domain.out
index 1caa96cdee2..2eeb33b513a 100644
--- a/src/test/regress/expected/domain.out
+++ b/src/test/regress/expected/domain.out
@@ -527,6 +527,118 @@ drop function dp_mk(int);
 drop function dc_mk(int);
 drop table dc;
 drop table dp;
+-- A domain constraint rebuilt by ALTER COLUMN TYPE must not be validated
+-- until tables using the domain have been rewritten.  As above, the
+-- composite types are only referenced through functions returning them.
+-- (These tests avoid ROW(value)::domrw_t, since the rebuilt expression
+-- would then contain a NULL coerced to the domain itself.)
+create function domrw_show(int) returns bool language plpgsql as
+  $$ begin raise notice 'domain check sees value %', $1; return true; end $$;
+create table domrw_t (c int);
+create function domrw_t_null() returns domrw_t language sql
+  as 'select null::domrw_t';
+create domain domrw_dt as int
+  check (domrw_show(value) and (domrw_t_null()).c is null);
+alter table domrw_t add column d domrw_dt;
+insert into domrw_t values (1, 5), (2, 7);
+NOTICE:  domain check sees value 5
+NOTICE:  domain check sees value 7
+alter table domrw_t alter column c type bigint;  -- should see 5 and 7
+NOTICE:  domain check sees value 5
+NOTICE:  domain check sees value 7
+select * from domrw_t;
+ c | d 
+---+---
+ 1 | 5
+ 2 | 7
+(2 rows)
+
+select convalidated from pg_constraint where contypid = 'domrw_dt'::regtype;
+ convalidated 
+--------------
+ t
+(1 row)
+
+drop domain domrw_dt cascade;
+NOTICE:  drop cascades to column d of table domrw_t
+drop function domrw_t_null();
+drop table domrw_t;
+-- same, domain over composite
+create type domrw_ct as (j int);
+create table domrw_t (c int);
+create function domrw_t_null() returns domrw_t language sql
+  as 'select null::domrw_t';
+create domain domrw_dt as domrw_ct
+  check (domrw_show((value).j) and (domrw_t_null()).c is null);
+alter table domrw_t add column d domrw_dt;
+insert into domrw_t values (1, row(5)), (2, row(7));
+NOTICE:  domain check sees value 5
+NOTICE:  domain check sees value 7
+alter table domrw_t alter column c type bigint;  -- should see 5 and 7
+NOTICE:  domain check sees value 5
+NOTICE:  domain check sees value 7
+select * from domrw_t;
+ c |  d  
+---+-----
+ 1 | (5)
+ 2 | (7)
+(2 rows)
+
+drop domain domrw_dt cascade;
+NOTICE:  drop cascades to column d of table domrw_t
+drop function domrw_t_null();
+drop table domrw_t;
+drop type domrw_ct;
+drop function domrw_show(int);
+-- domain column in an inheritance child that is rewritten by recursion
+create table domrw_p (c int);
+create function domrw_p_mk(int) returns domrw_p language sql
+  as 'select row($1)::domrw_p';
+create domain domrw_dt as int check ((domrw_p_mk(value)).c > 0);
+create table domrw_ch (d domrw_dt) inherits (domrw_p);
+insert into domrw_ch values (1, 5), (2, 7);
+alter table domrw_p alter column c type bigint;
+select * from domrw_ch;
+ c | d 
+---+---
+ 1 | 5
+ 2 | 7
+(2 rows)
+
+drop domain domrw_dt cascade;
+NOTICE:  drop cascades to column d of table domrw_ch
+drop function domrw_p_mk(int);
+drop table domrw_p cascade;
+NOTICE:  drop cascades to table domrw_ch
+-- a rebuilt constraint that rejects stored values must still be enforced,
+-- even when the altered object is a standalone composite type
+create type domrw_rt as (i int);
+create function domrw_rt_mk(int) returns domrw_rt language sql
+  as 'select row($1)::domrw_rt';
+create domain domrw_dt as int check ((domrw_rt_mk(value)).i is not null);
+create table domrw_u (x domrw_dt);
+insert into domrw_u values (40000);
+alter type domrw_rt alter attribute i type smallint;  -- fail
+ERROR:  smallint out of range
+drop table domrw_u;
+-- a NOT VALID constraint is not validated and stays NOT VALID
+alter domain domrw_dt drop constraint domrw_dt_check;
+create table domrw_u (x domrw_dt);
+insert into domrw_u values (40000);
+alter domain domrw_dt add constraint domrw_nv
+  check ((domrw_rt_mk(value)).i is not null) not valid;
+alter type domrw_rt alter attribute i type smallint;
+select pg_get_constraintdef(oid), convalidated from pg_constraint
+  where contypid = 'domrw_dt'::regtype;
+                  pg_get_constraintdef                  | convalidated 
+--------------------------------------------------------+--------------
+ CHECK (((domrw_rt_mk(VALUE)).i IS NOT NULL)) NOT VALID | f
+(1 row)
+
+drop table domrw_u;
+drop domain domrw_dt;
+drop function domrw_rt_mk(int);
+drop type domrw_rt;
 -- Test domains over arrays of composite
 create type comptype as (r float8, i float8);
 create domain dcomptypea as comptype[];
diff --git a/src/test/regress/sql/domain.sql b/src/test/regress/sql/domain.sql
index 0f874a365e3..a814857d7c1 100644
--- a/src/test/regress/sql/domain.sql
+++ b/src/test/regress/sql/domain.sql
@@ -287,6 +287,82 @@ drop function dc_mk(int);
 drop table dc;
 drop table dp;
 
+-- A domain constraint rebuilt by ALTER COLUMN TYPE must not be validated
+-- until tables using the domain have been rewritten.  As above, the
+-- composite types are only referenced through functions returning them.
+-- (These tests avoid ROW(value)::domrw_t, since the rebuilt expression
+-- would then contain a NULL coerced to the domain itself.)
+create function domrw_show(int) returns bool language plpgsql as
+  $$ begin raise notice 'domain check sees value %', $1; return true; end $$;
+create table domrw_t (c int);
+create function domrw_t_null() returns domrw_t language sql
+  as 'select null::domrw_t';
+create domain domrw_dt as int
+  check (domrw_show(value) and (domrw_t_null()).c is null);
+alter table domrw_t add column d domrw_dt;
+insert into domrw_t values (1, 5), (2, 7);
+alter table domrw_t alter column c type bigint;  -- should see 5 and 7
+select * from domrw_t;
+select convalidated from pg_constraint where contypid = 'domrw_dt'::regtype;
+drop domain domrw_dt cascade;
+drop function domrw_t_null();
+drop table domrw_t;
+
+-- same, domain over composite
+create type domrw_ct as (j int);
+create table domrw_t (c int);
+create function domrw_t_null() returns domrw_t language sql
+  as 'select null::domrw_t';
+create domain domrw_dt as domrw_ct
+  check (domrw_show((value).j) and (domrw_t_null()).c is null);
+alter table domrw_t add column d domrw_dt;
+insert into domrw_t values (1, row(5)), (2, row(7));
+alter table domrw_t alter column c type bigint;  -- should see 5 and 7
+select * from domrw_t;
+drop domain domrw_dt cascade;
+drop function domrw_t_null();
+drop table domrw_t;
+drop type domrw_ct;
+drop function domrw_show(int);
+
+-- domain column in an inheritance child that is rewritten by recursion
+create table domrw_p (c int);
+create function domrw_p_mk(int) returns domrw_p language sql
+  as 'select row($1)::domrw_p';
+create domain domrw_dt as int check ((domrw_p_mk(value)).c > 0);
+create table domrw_ch (d domrw_dt) inherits (domrw_p);
+insert into domrw_ch values (1, 5), (2, 7);
+alter table domrw_p alter column c type bigint;
+select * from domrw_ch;
+drop domain domrw_dt cascade;
+drop function domrw_p_mk(int);
+drop table domrw_p cascade;
+
+-- a rebuilt constraint that rejects stored values must still be enforced,
+-- even when the altered object is a standalone composite type
+create type domrw_rt as (i int);
+create function domrw_rt_mk(int) returns domrw_rt language sql
+  as 'select row($1)::domrw_rt';
+create domain domrw_dt as int check ((domrw_rt_mk(value)).i is not null);
+create table domrw_u (x domrw_dt);
+insert into domrw_u values (40000);
+alter type domrw_rt alter attribute i type smallint;  -- fail
+drop table domrw_u;
+
+-- a NOT VALID constraint is not validated and stays NOT VALID
+alter domain domrw_dt drop constraint domrw_dt_check;
+create table domrw_u (x domrw_dt);
+insert into domrw_u values (40000);
+alter domain domrw_dt add constraint domrw_nv
+  check ((domrw_rt_mk(value)).i is not null) not valid;
+alter type domrw_rt alter attribute i type smallint;
+select pg_get_constraintdef(oid), convalidated from pg_constraint
+  where contypid = 'domrw_dt'::regtype;
+drop table domrw_u;
+drop domain domrw_dt;
+drop function domrw_rt_mk(int);
+drop type domrw_rt;
+
 
 -- Test domains over arrays of composite
 
-- 
2.50.1 (Apple Git-155)

From 349f47cddc594444e38975231b95120d021dbebe Mon Sep 17 00:00:00 2001
From: Matheus Alcantara <[email protected]>
Date: Mon, 28 Sep 2026 15:18:56 -0300
Subject: [PATCH v6 3/3] Don't require ownership when rebuilding constraints in
 ALTER TABLE

When ALTER TABLE ... ALTER COLUMN TYPE (or ALTER TYPE ... ALTER
ATTRIBUTE) rebuilds a constraint that depends on the altered column,
it drops the constraint and re-creates it from its saved definition.
For domain CHECK constraints the re-creation goes through
AlterDomainAddConstraint(), which calls checkDomainOwner(), and any
comment on a table or domain constraint is restored with
CommentObject(), which requires ownership of the constraint's table or
domain.  So a user altering a type or table they own would fail with
"must be owner of type ..." or "must be owner of relation ..." if
another user's domain or table has a constraint that depends on it.
Since types grant USAGE to PUBLIC by default, any user could create
such a dependency and block the owner from altering their own type.

These checks don't make sense here: the user isn't choosing to add a
constraint or comment, just restoring ones that already existed, and
the matching drop is already done without any permission checks.
Rebuilding a table constraint without a comment also doesn't check
ownership.

Fix by re-adding domain constraints through a new function,
AlterDomainReAddConstraint(), which skips the ownership check, as we
already do for the USAGE check on types used by the expression, and
by restoring comments directly with CreateComments() instead of
CommentObject().

Also, the re-add used to look the domain up by the name in the
deparsed constraint definition.  If the domain was renamed, and
another domain created with its old name, while the ALTER was waiting
for a lock, the constraint and its comment were silently attached to
the new domain, and the original one lost them.  Skipping the
ownership check would have made that work even for a domain owned by
someone else.  To fix, take the domain's OID from the old constraint
while it still exists, lock the domain so it can't be dropped
concurrently, and re-add the constraint and its comment using that
OID.  The OID is carried in a new ad-hoc node,
ATReAddDomainConstraint, which replaces the AlterDomainStmt used
before.

The domain part of this, including the name lookup, dates back to
af20e2d72, which added rebuilding of domain constraints.
---
 src/backend/commands/tablecmds.c              | 117 +++++++++++-------
 src/backend/commands/typecmds.c               |  62 ++++++++--
 src/include/commands/typecmds.h               |   3 +
 src/include/nodes/parsenodes.h                |  15 +++
 .../expected/alter-type-domain-readd.out      |  25 ++++
 src/test/isolation/isolation_schedule         |   1 +
 .../specs/alter-type-domain-readd.spec        |  41 ++++++
 src/test/regress/expected/domain.out          |  41 ++++++
 src/test/regress/sql/domain.sql               |  34 +++++
 src/tools/pgindent/typedefs.list              |   1 +
 10 files changed, 289 insertions(+), 51 deletions(-)
 create mode 100644 src/test/isolation/expected/alter-type-domain-readd.out
 create mode 100644 src/test/isolation/specs/alter-type-domain-readd.spec

diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c
index 13e3177961b..d59ea77dd48 100644
--- a/src/backend/commands/tablecmds.c
+++ b/src/backend/commands/tablecmds.c
@@ -690,7 +690,7 @@ static void ATPostAlterTypeParse(Oid oldId, Oid oldRelId, 
Oid refRelId, Oid owne
                                                                 const char 
*cmdstring, List **wqueue,
                                                                 LOCKMODE 
lockmode, bool rewrite);
 static void RebuildConstraintComment(AlteredTableInfo *tab, AlterTablePass 
pass,
-                                                                        Oid 
objid, Relation rel, List *domname,
+                                                                        Oid 
objid, Relation rel,
                                                                         const 
char *conname);
 static void TryReuseIndex(Oid oldId, IndexStmt *stmt);
 static void TryReuseForeignKey(Oid oldId, Constraint *con);
@@ -5563,20 +5563,32 @@ ATExecCmd(List **wqueue, AlteredTableInfo *tab,
                case AT_ReAddDomainConstraint:  /* Re-add pre-existing domain 
check
                                                                                
 * constraint */
                        {
-                               AlterDomainStmt *stmt = (AlterDomainStmt *) 
cmd->def;
-                               Constraint *con = castNode(Constraint, 
stmt->def);
+                               ATReAddDomainConstraint *readd =
+                                       castNode(ATReAddDomainConstraint, 
cmd->def);
+                               Constraint *con = readd->constr;
                                ObjectAddress constrAddr = InvalidObjectAddress;
 
                                /* only CHECK constraints can depend on a 
column */
                                Assert(con->contype == CONSTR_CHECK);
 
-                               address = 
AlterDomainAddConstraint(stmt->typeName, stmt->def,
-                                                                               
                   &constrAddr, true);
+                               address = 
AlterDomainReAddConstraint(readd->domainoid, con,
+                                                                               
                         &constrAddr);
 
                                /*
-                                * AlterDomainAddConstraint doesn't validate 
re-added
-                                * constraints, since tables using the domain 
may not have
-                                * been rewritten yet. Tell Phase 3 to do it.
+                                * Restore any comment on the constraint. Don't 
use
+                                * CommentObject(), since that requires 
ownership of the
+                                * domain, which the user altering a column the 
constraint
+                                * depends on need not have, and since it would 
look up the
+                                * domain by name again.
+                                */
+                               if (readd->comment)
+                                       CreateComments(constrAddr.objectId, 
ConstraintRelationId,
+                                                                  0, 
readd->comment);
+
+                               /*
+                                * AlterDomainReAddConstraint doesn't validate 
the constraint,
+                                * since tables using the domain may not have 
been rewritten
+                                * yet. Tell Phase 3 to do it.
                                 */
                                if (!con->skip_validation)
                                        tab->domain_constraints =
@@ -5585,7 +5597,28 @@ ATExecCmd(List **wqueue, AlteredTableInfo *tab,
                                break;
                        }
                case AT_ReAddComment:   /* Re-add existing comment */
-                       address = CommentObject((CommentStmt *) cmd->def);
+                       {
+                               CommentStmt *stmt = (CommentStmt *) cmd->def;
+                               Relation        comrel;
+
+                               /*
+                                * Don't use CommentObject(), since that 
requires ownership of
+                                * the constraint's table, which the user 
altering a column
+                                * the constraint depends on need not have. 
We're just
+                                * restoring a comment that already existed.  
(Comments on
+                                * domain constraints are restored by 
AT_ReAddDomainConstraint
+                                * instead.)
+                                */
+                               Assert(stmt->objtype == OBJECT_TABCONSTRAINT);
+                               address = get_object_address(stmt->objtype, 
stmt->object,
+                                                                               
         &comrel,
+                                                                               
         ShareUpdateExclusiveLock,
+                                                                               
         false);
+                               CreateComments(address.objectId, 
address.classId,
+                                                          address.objectSubId, 
stmt->comment);
+                               if (comrel != NULL)
+                                       relation_close(comrel, NoLock);
+                       }
                        break;
                case AT_AddIndexConstraint: /* ADD CONSTRAINT USING INDEX */
                        address = ATExecAddIndexConstraint(tab, rel, (IndexStmt 
*) cmd->def,
@@ -17153,7 +17186,6 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid 
refRelId, Oid ownerId,
                                                                                
         AT_PASS_OLD_INDEX,
                                                                                
         oldId,
                                                                                
         rel,
-                                                                               
         NIL,
                                                                                
         indstmt->idxname);
                                }
                                else if (cmd->subtype == AT_AddConstraint)
@@ -17181,7 +17213,6 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid 
refRelId, Oid ownerId,
                                                                                
                 AT_PASS_OLD_CONSTR,
                                                                                
                 oldId,
                                                                                
                 rel,
-                                                                               
                 NIL,
                                                                                
                 con->conname);
                                        else
                                                Assert(con->contype == 
CONSTR_NOTNULL);
@@ -17197,21 +17228,35 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid 
refRelId, Oid ownerId,
 
                        if (stmt->subtype == AD_AddConstraint)
                        {
-                               Constraint *con = castNode(Constraint, 
stmt->def);
+                               ATReAddDomainConstraint *readd = 
makeNode(ATReAddDomainConstraint);
                                AlterTableCmd *cmd = makeNode(AlterTableCmd);
+                               HeapTuple       tup;
+
+                               /*
+                                * Don't trust the domain name in the deparsed 
command, since
+                                * the domain might have been renamed, and 
another type
+                                * created with its old name, concurrently. 
Instead, take the
+                                * domain's OID from the old constraint, which 
still exists.
+                                * Lock the domain to make sure it doesn't go 
away before we
+                                * re-add the constraint.
+                                */
+                               tup = SearchSysCache1(CONSTROID, 
ObjectIdGetDatum(oldId));
+                               if (!HeapTupleIsValid(tup)) /* should not 
happen */
+                                       elog(ERROR, "cache lookup failed for 
constraint %u", oldId);
+                               readd->domainoid = ((Form_pg_constraint) 
GETSTRUCT(tup))->contypid;
+                               ReleaseSysCache(tup);
+                               Assert(OidIsValid(readd->domainoid));
+                               LockDatabaseObject(TypeRelationId, 
readd->domainoid, 0,
+                                                                  
AccessShareLock);
+
+                               readd->constr = castNode(Constraint, stmt->def);
+                               /* keep any comment on the constraint */
+                               readd->comment = GetComment(oldId, 
ConstraintRelationId, 0);
 
                                cmd->subtype = AT_ReAddDomainConstraint;
-                               cmd->def = (Node *) stmt;
+                               cmd->def = (Node *) readd;
                                tab->subcmds[AT_PASS_OLD_CONSTR] =
                                        
lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
-
-                               /* recreate any comment on the constraint */
-                               RebuildConstraintComment(tab,
-                                                                               
 AT_PASS_OLD_CONSTR,
-                                                                               
 oldId,
-                                                                               
 NULL,
-                                                                               
 stmt->typeName,
-                                                                               
 con->conname);
                        }
                        else
                                elog(ERROR, "unexpected statement subtype: %d",
@@ -17241,18 +17286,16 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid 
refRelId, Oid ownerId,
 
 /*
  * Subroutine for ATPostAlterTypeParse() to recreate any existing comment
- * for a table or domain constraint that is being rebuilt.
+ * for a table constraint that is being rebuilt.  (Comments on domain
+ * constraints are handled by AT_ReAddDomainConstraint.)
  *
- * objid is the OID of the constraint.
- * Pass "rel" for a table constraint, or "domname" (domain's qualified name
- * as a string list) for a domain constraint.
+ * objid is the OID of the constraint, and rel is its table.
  * (We could dig that info, as well as the conname, out of the pg_constraint
  * entry; but callers already have them so might as well pass them.)
  */
 static void
 RebuildConstraintComment(AlteredTableInfo *tab, AlterTablePass pass, Oid objid,
-                                                Relation rel, List *domname,
-                                                const char *conname)
+                                                Relation rel, const char 
*conname)
 {
        CommentStmt *cmd;
        char       *comment_str;
@@ -17265,21 +17308,11 @@ RebuildConstraintComment(AlteredTableInfo *tab, 
AlterTablePass pass, Oid objid,
 
        /* Build CommentStmt node, copying all input data for safety */
        cmd = makeNode(CommentStmt);
-       if (rel)
-       {
-               cmd->objtype = OBJECT_TABCONSTRAINT;
-               cmd->object = (Node *)
-                       
list_make3(makeString(get_namespace_name(RelationGetNamespace(rel))),
-                                          
makeString(pstrdup(RelationGetRelationName(rel))),
-                                          makeString(pstrdup(conname)));
-       }
-       else
-       {
-               cmd->objtype = OBJECT_DOMCONSTRAINT;
-               cmd->object = (Node *)
-                       
list_make2(makeTypeNameFromNameList(copyObject(domname)),
-                                          makeString(pstrdup(conname)));
-       }
+       cmd->objtype = OBJECT_TABCONSTRAINT;
+       cmd->object = (Node *)
+               
list_make3(makeString(get_namespace_name(RelationGetNamespace(rel))),
+                                  
makeString(pstrdup(RelationGetRelationName(rel))),
+                                  makeString(pstrdup(conname)));
        cmd->comment = comment_str;
 
        /* Append it to list of commands */
diff --git a/src/backend/commands/typecmds.c b/src/backend/commands/typecmds.c
index 8d76dc6c579..ece0257965a 100644
--- a/src/backend/commands/typecmds.c
+++ b/src/backend/commands/typecmds.c
@@ -131,6 +131,10 @@ static Oid findRangeSubtypeDiffFunction(List *procname, 
Oid subtype);
 static void validateDomainNotNullConstraint(Oid domainoid);
 static List *get_rels_with_domain(Oid domainOid, LOCKMODE lockmode);
 static void checkEnumOwner(HeapTuple tup);
+static ObjectAddress domainAddConstraintInternal(Oid domainoid,
+                                                                               
                 Node *newConstraint,
+                                                                               
                 ObjectAddress *constrAddr,
+                                                                               
                 bool is_readd);
 static char *domainAddCheckConstraint(Oid domainOid, Oid domainNamespace,
                                                                          Oid 
baseTypeOid,
                                                                          int 
typMod, Constraint *constr,
@@ -3009,6 +3013,38 @@ AlterDomainAddConstraint(List *names, Node 
*newConstraint,
 {
        TypeName   *typename;
        Oid                     domainoid;
+
+       /* Make a TypeName so we can use standard type lookup machinery */
+       typename = makeTypeNameFromNameList(names);
+       domainoid = typenameTypeId(NULL, typename);
+
+       return domainAddConstraintInternal(domainoid, newConstraint, constrAddr,
+                                                                          
is_readd);
+}
+
+/*
+ * AlterDomainReAddConstraint
+ *
+ * Re-add a domain CHECK constraint that ALTER TABLE dropped because it
+ * depends on a column being altered.  The domain is identified by OID rather
+ * than by name, since the name might have been changed to refer to a
+ * different type by the time the constraint is re-added.
+ */
+ObjectAddress
+AlterDomainReAddConstraint(Oid domainoid, Constraint *constr,
+                                                  ObjectAddress *constrAddr)
+{
+       return domainAddConstraintInternal(domainoid, (Node *) constr, 
constrAddr,
+                                                                          
true);
+}
+
+/*
+ * Workhorse for AlterDomainAddConstraint and AlterDomainReAddConstraint.
+ */
+static ObjectAddress
+domainAddConstraintInternal(Oid domainoid, Node *newConstraint,
+                                                       ObjectAddress 
*constrAddr, bool is_readd)
+{
        Relation        typrel;
        HeapTuple       tup;
        Form_pg_type typTup;
@@ -3016,10 +3052,6 @@ AlterDomainAddConstraint(List *names, Node 
*newConstraint,
        char       *ccbin;
        ObjectAddress address = InvalidObjectAddress;
 
-       /* Make a TypeName so we can use standard type lookup machinery */
-       typename = makeTypeNameFromNameList(names);
-       domainoid = typenameTypeId(NULL, typename);
-
        /* Look up the domain in the type table */
        typrel = table_open(TypeRelationId, RowExclusiveLock);
 
@@ -3028,8 +3060,20 @@ AlterDomainAddConstraint(List *names, Node 
*newConstraint,
                elog(ERROR, "cache lookup failed for type %u", domainoid);
        typTup = (Form_pg_type) GETSTRUCT(tup);
 
-       /* Check it's a domain and check user has permission for ALTER DOMAIN */
-       checkDomainOwner(tup);
+       /*
+        * Check it's a domain and check user has permission for ALTER DOMAIN.
+        * When re-adding a constraint during ALTER TABLE, skip the permission
+        * check since the constraint already existed, and the user altering a
+        * column it depends on need not own the domain.  The caller got the OID
+        * from the old constraint, so it must be a domain.
+        */
+       if (is_readd)
+       {
+               if (typTup->typtype != TYPTYPE_DOMAIN)
+                       elog(ERROR, "type %u is not a domain", domainoid);
+       }
+       else
+               checkDomainOwner(tup);
 
        if (!IsA(newConstraint, Constraint))
                elog(ERROR, "unrecognized node type: %d",
@@ -3058,9 +3102,9 @@ AlterDomainAddConstraint(List *names, Node *newConstraint,
                 * to.
                 *
                 * When re-adding a constraint during ALTER TABLE, the tables 
using
-                * the domain might not have been rewritten to match their new
-                * catalog definitions yet, so the caller must do the 
validation after
-                * its rewrite phase instead.
+                * the domain might not have been rewritten to match their new 
catalog
+                * definitions yet, so the caller must do the validation after 
its
+                * rewrite phase instead.
                 */
                if (!constr->skip_validation && !is_readd)
                        validateDomainCheckConstraint(domainoid, ccbin);
diff --git a/src/include/commands/typecmds.h b/src/include/commands/typecmds.h
index a067651f6f9..d993f3f9b51 100644
--- a/src/include/commands/typecmds.h
+++ b/src/include/commands/typecmds.h
@@ -37,6 +37,9 @@ extern ObjectAddress AlterDomainNotNull(List *names, bool 
notNull);
 extern ObjectAddress AlterDomainAddConstraint(List *names, Node *newConstraint,
                                                                                
          ObjectAddress *constrAddr,
                                                                                
          bool is_readd);
+extern ObjectAddress AlterDomainReAddConstraint(Oid domainoid,
+                                                                               
                Constraint *constr,
+                                                                               
                ObjectAddress *constrAddr);
 extern ObjectAddress AlterDomainValidateConstraint(List *names, const char 
*constrName);
 extern void validateDomainCheckConstraint(Oid domainoid, const char *ccbin);
 extern ObjectAddress AlterDomainDropConstraint(List *names, const char 
*constrName,
diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h
index 5be1d4a944b..1af09646f7f 100644
--- a/src/include/nodes/parsenodes.h
+++ b/src/include/nodes/parsenodes.h
@@ -2559,6 +2559,21 @@ typedef struct ATAlterConstraint
        bool            noinherit;
 } ATAlterConstraint;
 
+/*
+ * Ad-hoc node for AT_ReAddDomainConstraint
+ *
+ * The domain is identified by OID, not by name: the constraint is re-added
+ * after the old one is dropped, and by then the name might refer to a
+ * different type.
+ */
+typedef struct ATReAddDomainConstraint
+{
+       NodeTag         type;
+       Oid                     domainoid;              /* domain the 
constraint belongs to */
+       struct Constraint *constr;      /* CHECK constraint to re-add */
+       char       *comment;            /* comment on the constraint, or NULL */
+} ATReAddDomainConstraint;
+
 /* Ad-hoc node for AT_ReplicaIdentity */
 typedef struct ReplicaIdentityStmt
 {
diff --git a/src/test/isolation/expected/alter-type-domain-readd.out 
b/src/test/isolation/expected/alter-type-domain-readd.out
new file mode 100644
index 00000000000..4898f63df42
--- /dev/null
+++ b/src/test/isolation/expected/alter-type-domain-readd.out
@@ -0,0 +1,25 @@
+Parsed test spec with 3 sessions
+
+starting permutation: s1_begin s2_alter s3_swap s1_commit s3_check s3_cast
+step s1_begin: BEGIN; SELECT count(*) FROM t2;
+count
+-----
+    1
+(1 row)
+
+step s2_alter: ALTER TYPE ct ALTER ATTRIBUTE i TYPE bigint; <waiting ...>
+step s3_swap: ALTER DOMAIN d RENAME TO d_old; CREATE DOMAIN d AS int;
+step s1_commit: COMMIT;
+step s2_alter: <... completed>
+step s3_check: 
+       SELECT t.typname, c.conname, obj_description(c.oid, 'pg_constraint')
+         FROM pg_constraint c JOIN pg_type t ON t.oid = c.contypid
+        WHERE t.typname IN ('d', 'd_old');
+
+typname|conname|obj_description
+-------+-------+---------------
+d_old  |d_check|d comment      
+(1 row)
+
+step s3_cast: SELECT (-1)::d_old;
+ERROR:  value for domain d_old violates check constraint "d_check"
diff --git a/src/test/isolation/isolation_schedule 
b/src/test/isolation/isolation_schedule
index 3831004b74d..a9d2e8f7f1f 100644
--- a/src/test/isolation/isolation_schedule
+++ b/src/test/isolation/isolation_schedule
@@ -99,6 +99,7 @@ test: skip-locked-4
 test: drop-index-concurrently-1
 test: multiple-cic
 test: alter-domain-validate
+test: alter-type-domain-readd
 test: alter-table-1
 test: alter-table-2
 test: alter-table-3
diff --git a/src/test/isolation/specs/alter-type-domain-readd.spec 
b/src/test/isolation/specs/alter-type-domain-readd.spec
new file mode 100644
index 00000000000..0d2ad313dae
--- /dev/null
+++ b/src/test/isolation/specs/alter-type-domain-readd.spec
@@ -0,0 +1,41 @@
+# Test that ALTER TYPE ... ALTER ATTRIBUTE ... TYPE re-adds a dependent
+# domain constraint (and its comment) to the domain it belonged to, even if
+# that domain is renamed and another one takes its name while the ALTER is
+# waiting for a lock.
+
+setup
+{
+       CREATE TYPE ct AS (i int);
+       CREATE FUNCTION ct_mk(int) RETURNS ct LANGUAGE sql AS 'select 
row($1)::ct';
+       CREATE TABLE t2 (x int CHECK ((ct_mk(x)).i > 0));
+       INSERT INTO t2 VALUES (1);
+       CREATE DOMAIN d AS int CONSTRAINT d_check CHECK ((ct_mk(value)).i > 0);
+       COMMENT ON CONSTRAINT d_check ON DOMAIN d IS 'd comment';
+}
+
+teardown
+{
+       DROP TABLE t2;
+       DROP DOMAIN IF EXISTS d;
+       DROP DOMAIN IF EXISTS d_old;
+       DROP FUNCTION ct_mk(int);
+       DROP TYPE ct;
+}
+
+session s1
+step s1_begin  { BEGIN; SELECT count(*) FROM t2; }
+step s1_commit { COMMIT; }
+
+session s2
+step s2_alter  { ALTER TYPE ct ALTER ATTRIBUTE i TYPE bigint; }
+
+session s3
+step s3_swap   { ALTER DOMAIN d RENAME TO d_old; CREATE DOMAIN d AS int; }
+step s3_check  {
+       SELECT t.typname, c.conname, obj_description(c.oid, 'pg_constraint')
+         FROM pg_constraint c JOIN pg_type t ON t.oid = c.contypid
+        WHERE t.typname IN ('d', 'd_old');
+}
+step s3_cast   { SELECT (-1)::d_old; }
+
+permutation s1_begin s2_alter s3_swap s1_commit s3_check s3_cast
diff --git a/src/test/regress/expected/domain.out 
b/src/test/regress/expected/domain.out
index 2eeb33b513a..95b62eed115 100644
--- a/src/test/regress/expected/domain.out
+++ b/src/test/regress/expected/domain.out
@@ -639,6 +639,47 @@ drop table domrw_u;
 drop domain domrw_dt;
 drop function domrw_rt_mk(int);
 drop type domrw_rt;
+-- Rebuilding a constraint (and its comment) owned by someone else must not
+-- require ownership of the constraint's domain or table
+create role regress_domrw_typeowner;
+create role regress_domrw_conowner;
+grant create on schema public to regress_domrw_typeowner, 
regress_domrw_conowner;
+set role regress_domrw_typeowner;
+create type domrw_rt as (i int);
+set role regress_domrw_conowner;
+create function domrw_rt_mk(int) returns domrw_rt language sql
+  as 'select row($1)::domrw_rt';
+create domain domrw_dt1 as int
+  constraint domrw_dt1_check check ((domrw_rt_mk(value)).i > 0);
+comment on constraint domrw_dt1_check on domain domrw_dt1 is 'domain over int';
+create domain domrw_dt2 as domrw_rt
+  constraint domrw_dt2_check check ((value).i > 0);
+comment on constraint domrw_dt2_check on domain domrw_dt2 is 'domain over 
composite';
+create table domrw_t (x int
+  constraint domrw_t_check check ((domrw_rt_mk(x)).i > 0));
+comment on constraint domrw_t_check on domrw_t is 'table constraint';
+set role regress_domrw_typeowner;
+alter type domrw_rt alter attribute i type bigint;
+reset role;
+select conname, pg_get_constraintdef(oid), obj_description(oid, 
'pg_constraint')
+  from pg_constraint where conname like 'domrw\_%' order by conname;
+     conname     |         pg_get_constraintdef         |    obj_description   
 
+-----------------+--------------------------------------+-----------------------
+ domrw_dt1_check | CHECK (((domrw_rt_mk(VALUE)).i > 0)) | domain over int
+ domrw_dt2_check | CHECK (((VALUE).i > 0))              | domain over composite
+ domrw_t_check   | CHECK (((domrw_rt_mk(x)).i > 0))     | table constraint
+(3 rows)
+
+select (-1)::domrw_dt1;  -- fail
+ERROR:  value for domain domrw_dt1 violates check constraint "domrw_dt1_check"
+drop table domrw_t;
+drop domain domrw_dt1;
+drop domain domrw_dt2;
+drop function domrw_rt_mk(int);
+drop type domrw_rt;
+revoke create on schema public from regress_domrw_typeowner, 
regress_domrw_conowner;
+drop role regress_domrw_typeowner;
+drop role regress_domrw_conowner;
 -- Test domains over arrays of composite
 create type comptype as (r float8, i float8);
 create domain dcomptypea as comptype[];
diff --git a/src/test/regress/sql/domain.sql b/src/test/regress/sql/domain.sql
index a814857d7c1..57509a899de 100644
--- a/src/test/regress/sql/domain.sql
+++ b/src/test/regress/sql/domain.sql
@@ -363,6 +363,40 @@ drop domain domrw_dt;
 drop function domrw_rt_mk(int);
 drop type domrw_rt;
 
+-- Rebuilding a constraint (and its comment) owned by someone else must not
+-- require ownership of the constraint's domain or table
+create role regress_domrw_typeowner;
+create role regress_domrw_conowner;
+grant create on schema public to regress_domrw_typeowner, 
regress_domrw_conowner;
+set role regress_domrw_typeowner;
+create type domrw_rt as (i int);
+set role regress_domrw_conowner;
+create function domrw_rt_mk(int) returns domrw_rt language sql
+  as 'select row($1)::domrw_rt';
+create domain domrw_dt1 as int
+  constraint domrw_dt1_check check ((domrw_rt_mk(value)).i > 0);
+comment on constraint domrw_dt1_check on domain domrw_dt1 is 'domain over int';
+create domain domrw_dt2 as domrw_rt
+  constraint domrw_dt2_check check ((value).i > 0);
+comment on constraint domrw_dt2_check on domain domrw_dt2 is 'domain over 
composite';
+create table domrw_t (x int
+  constraint domrw_t_check check ((domrw_rt_mk(x)).i > 0));
+comment on constraint domrw_t_check on domrw_t is 'table constraint';
+set role regress_domrw_typeowner;
+alter type domrw_rt alter attribute i type bigint;
+reset role;
+select conname, pg_get_constraintdef(oid), obj_description(oid, 
'pg_constraint')
+  from pg_constraint where conname like 'domrw\_%' order by conname;
+select (-1)::domrw_dt1;  -- fail
+drop table domrw_t;
+drop domain domrw_dt1;
+drop domain domrw_dt2;
+drop function domrw_rt_mk(int);
+drop type domrw_rt;
+revoke create on schema public from regress_domrw_typeowner, 
regress_domrw_conowner;
+drop role regress_domrw_typeowner;
+drop role regress_domrw_conowner;
+
 
 -- Test domains over arrays of composite
 
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index f10eb469266..9bf6cbc0988 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -7,6 +7,7 @@ ASN1_OBJECT
 ASN1_OCTET_STRING
 ASN1_STRING
 ATAlterConstraint
+ATReAddDomainConstraint
 AV
 A_ArrayExpr
 A_Const
-- 
2.50.1 (Apple Git-155)

Reply via email to