ALTER COLUMN SET EXPRESSION on partitions not work in case of constraint dependencies

Started by jian he4 months ago7 messageshackers
Jump to latest
#1jian he
jian.universality@gmail.com

Hi.

Reproducer:

drop table if exists t;
CREATE TABLE t (
a int,
b int GENERATED ALWAYS AS (NULLIF(a, 1)) STORED NOT NULL,
constraint cc check (b > 0)) PARTITION BY RANGE (a);
CREATE TABLE tp_0_1 PARTITION OF t FOR VALUES FROM (10) TO (20);
ALTER TABLE tp_0_1 ALTER COLUMN b SET EXPRESSION AS (a);

-- expect two row, now nothing
select conname, contype from pg_constraint where conrelid = 'tp_0_1'::regclass;

This issue has existed since PG17.

ATPostAlterTypeCleanup only generates the ALTER TABLE ADD CONSTRAINT command for
the root (parent) table, not for the partitions themselves.
For a partition table, it only drops the old constraint without
rebuilding it: because a partition's pg_constraint.conislocal is false.

See the comments in ATPostAlterTypeCleanup below:
/*
* If the constraint is inherited (only), we don't want to inject a
* new definition here; it'll get recreated when
* ATAddCheckNNConstraint recurses from adding the parent table's
* constraint. But we had to carry the info this far so that we can
* drop the constraint below.
*/

I don't have a clear idea how to solve this issue other than by erroring out.
It seems non-trivial to drop an inherited constraint, recreate it and
correctly integrate it into the constraint inheritance hierarchy.
I checked src/test/regress/sql/generated_stored.sql, no related tests for it.

--
jian
https://www.enterprisedb.com/

#2jian he
jian.universality@gmail.com
In reply to: jian he (#1)
Re: ALTER COLUMN SET EXPRESSION on partitions not work in case of constraint dependencies

Hi.

ALTER TABLE ONLY ALTER COLUMN SET EXPRESSION is not working in some
corner case too:

drop table if exists t, pk cascade;
create table pk(a int primary key);
insert into pk select g from generate_series(1, 10) g;
CREATE TABLE t (a int, b int GENERATED ALWAYS AS (NULLIF(a, 1)) STORED
NOT NULL , constraint cc check (b > 0)) PARTITION BY RANGE (a);
CREATE TABLE tp1 PARTITION OF t FOR VALUES FROM (1) TO (20);
insert into t values (2), (3);
create index on t(b);
CREATE STATISTICS t_stat_only ON (b is not null) FROM t;
alter table t add foreign key (b) references pk;

ALTER TABLE ONLY t ALTER COLUMN b SET EXPRESSION AS (a + 1);
NOTICE: merging constraint "cc" with inherited definition
ERROR: could not read blocks 0..0 in file "base/5/18933": read only 0
of 8192 bytes
CONTEXT: SQL statement "SELECT fk."b" FROM ONLY "public"."tp1" fk
LEFT OUTER JOIN ONLY "public"."pk" pk ON ( pk."a"
OPERATOR(pg_catalog.=) fk."b") WHERE pk."a" IS NULL AND (fk."b" IS NOT
NULL)"
---------------------------------
If I remove the above ``create index on t(b);``, then the above ALTER
TABLE ONLY SET EXPRESSION
works.
I suspect this is because the transient index is dropped and rebuilt,
making it unusable during the SPI SELECT query while we are still
using it.
(This part I didn't dig deeper).

It appears to be only index dependency and no constraint dependency, ALTER TABLE
ONLY ... SET EXPRESSION may still work. However, this could contradict
the word "ONLY" somehow because we still rebuild the child table's indexes. And
there may be other unknown complications. To avoid unexpected behavior, it would
be better to disallow this case (ALTER TABLE ONLY with only index
dependency) as well.

Summary:
ALTER TABLE ONLY ... SET EXPRESSION should fail if the generated
column has dependencies, because rebuilding dependent objects
contradicts the word "ONLY" and may lead to unintended errors.
Directly using ALTER TABLE ... SET EXPRESSION on a child table should
fail because rebuilding dependent objects while preserving the
inheritance hierarchy would be very difficult.

--
jian
https://www.enterprisedb.com/

Attachments:

t253271_2
v1-0001-Disallow-ALTER-TABLE-SET-EXPRESSION-if-dependent-cannot-rebuilt.patchtext/x-patch; charset=US-ASCII; name=v1-0001-Disallow-ALTER-TABLE-SET-EXPRESSION-if-dependent-cannot-rebuilt.patchDownload+246-7
#3Alberto Piai
alberto.piai@gmail.com
In reply to: jian he (#1)
Re: ALTER COLUMN SET EXPRESSION on partitions not work in case of constraint dependencies

On Sat Aug 1, 2026 at 7:57 AM CEST, jian he wrote:

Hi.

Reproducer:

drop table if exists t;
CREATE TABLE t (
a int,
b int GENERATED ALWAYS AS (NULLIF(a, 1)) STORED NOT NULL,
constraint cc check (b > 0)) PARTITION BY RANGE (a);
CREATE TABLE tp_0_1 PARTITION OF t FOR VALUES FROM (10) TO (20);
ALTER TABLE tp_0_1 ALTER COLUMN b SET EXPRESSION AS (a);

-- expect two row, now nothing
select conname, contype from pg_constraint where conrelid = 'tp_0_1'::regclass;

It's admittedly a long shot, since I'm still studying all of this, but:
what if, when we RememberConstraintForRebuilding() a constraint with
conislocal=false, we also RememberConstraintForRebuilding() its
corresponding parent constraint?

I have not fully considered the implications of this and I'm only
thinking about CHECK and NN constraints.

The attached patch is not meant for code-review, but just to illustrate
the idea and get the conversation started. What do you think?

Regards,

Alberto

--
Alberto Piai
Sensational AG
Zürich, Switzerland

Attachments:

nocfbot-v1-0001-WIP-fix-ATPostAlterTypeCleanup-dropping-constrain.patchtext/plain; charset=utf-8Download+127-4
#4jian he
jian.universality@gmail.com
In reply to: Alberto Piai (#3)
Re: ALTER COLUMN SET EXPRESSION on partitions not work in case of constraint dependencies

On Fri, Aug 7, 2026 at 9:35 PM Alberto Piai <alberto.piai@gmail.com> wrote:

It's admittedly a long shot, since I'm still studying all of this, but:
what if, when we RememberConstraintForRebuilding() a constraint with
conislocal=false, we also RememberConstraintForRebuilding() its
corresponding parent constraint?

I have not fully considered the implications of this and I'm only
thinking about CHECK and NN constraints.

That will make the entire hierarchy take an AccessExclusiveLock,
which is not ideal and may require consensus.
I think if the partition's generated column has an index on it, then
directly changing its generation expression will not work.

Please check the two attached patches:
v3-0001-Disallow-directly-ALTER-TABLE-SET-EXPRESSION-on-child-table-if-de.patch
is for disallow directly running ALTER TABLE SET EXPRESSION on child table if
dependencies (indexes, constraints) exist.

v3-0001-Fix-dependency-issue-when-directly-ALTER-TABLE-SET-EXPRESSION-o.nocfbot
It allows directly running ALTER TABLE SET EXPRESSION on a partition, if that
partition only has constraint dependencies, not index dependencies. This is a
POC with extensive tests.
Rationale: changing the generation expression only affects the underlying column
data, not its type. So instead of rebuilding these constraints, we can just
re-validate them against the newly computed data. This avoids unnecessary
constraint rebuilds and gets rid of the ACCESS EXCLUSIVE lock requirement on the
whole partition hierarchy when we're only touching one partition.

We may or may not error out if a generated column has index or
constraint dependencies, so we need
to call RememberAllDependentForRebuilding earlier, so I moved it from
ATExecSetExpression to ATPrepCmd.
Looking for generated column dependencies in phase 1 should be fine.
See ATPrepSetExpression.

Given the complexity of the whole thing, we should error out in the back branch.

--
jian
https://www.enterprisedb.com/

Attachments:

t253271_4
v3-0001-Disallow-directly-ALTER-TABLE-SET-EXPRESSION-on-child-table-if-de.patchtext/x-patch; charset=US-ASCII; name=v3-0001-Disallow-directly-ALTER-TABLE-SET-EXPRESSION-on-child-table-if-de.patchDownload+206-14
v3-0001-Fix-dependency-issue-when-directly-ALTER-TABLE-SET-EXPRESSION-o.nocfbotapplication/octet-stream; name=v3-0001-Fix-dependency-issue-when-directly-ALTER-TABLE-SET-EXPRESSION-o.nocfbotDownload+421-14
#5Alberto Piai
alberto.piai@gmail.com
In reply to: jian he (#4)
Re: ALTER COLUMN SET EXPRESSION on partitions not work in case of constraint dependencies

On Mon Aug 10, 2026 at 10:28 AM CEST, jian he wrote:

On Fri, Aug 7, 2026 at 9:35 PM Alberto Piai <alberto.piai@gmail.com> wrote:

It's admittedly a long shot, since I'm still studying all of this, but:
what if, when we RememberConstraintForRebuilding() a constraint with
conislocal=false, we also RememberConstraintForRebuilding() its
corresponding parent constraint?

I have not fully considered the implications of this and I'm only
thinking about CHECK and NN constraints.

That will make the entire hierarchy take an AccessExclusiveLock,
which is not ideal and may require consensus.
I think if the partition's generated column has an index on it, then
directly changing its generation expression will not work.

You're right, please disregard my suggestion.

Please check the two attached patches:
v3-0001-Disallow-directly-ALTER-TABLE-SET-EXPRESSION-on-child-table-if-de.patch
is for disallow directly running ALTER TABLE SET EXPRESSION on child table if
dependencies (indexes, constraints) exist.

v3-0001-Fix-dependency-issue-when-directly-ALTER-TABLE-SET-EXPRESSION-o.nocfbot
It allows directly running ALTER TABLE SET EXPRESSION on a partition, if that
partition only has constraint dependencies, not index dependencies. This is a
POC with extensive tests.
Rationale: changing the generation expression only affects the underlying column
data, not its type. So instead of rebuilding these constraints, we can just
re-validate them against the newly computed data. This avoids unnecessary
constraint rebuilds and gets rid of the ACCESS EXCLUSIVE lock requirement on the
whole partition hierarchy when we're only touching one partition.

Thanks for the new patches, I spent some time thinking about these
problems and the situation is clearer now.

You found several corner cases, and it's quite hard to deal with them at
once. Please allow me to focus on one case at first: constraints (let's
leave indexes aside for now). We might get to a patch that is easier to
reason about and maybe even backpatch.

I think your observation that we don't need to rebuild the constraints
but only verify them is the key here.

If you go this route, based on your second patch
(v3-0001-Fix-dependency-issue...):

- we wouldn't need to add the function ATPrepSetExpression (for now at
least)

- this also avoids the problem that with your current patch marking the
table with tab->rewrite |= AT_REWRITE_DEFAULT_VAL is done twice, once
in your new ATPrepSetExpression and then again in ATExecSetExpression

- rather than removing the constraints from the tab->changedConstraints*
lists, maybe it would be possible to change the Remember*ForRebuilding
functions to do the right thing in this case? They already know that
subtype=AT_SetExpression, after all

What do you think?

As a user, I would find it very surprising if ALTER TABLE ONLY ... SET
EXPRESSION failed sometimes, depending on how dependencies are set up.
It would be great if we'd manage to get this working.

Thanks for working on this!

Alberto

--
Alberto Piai
Sensational AG
Zürich, Switzerland

#6jian he
jian.universality@gmail.com
In reply to: Alberto Piai (#5)
Re: ALTER COLUMN SET EXPRESSION on partitions not work in case of constraint dependencies

On Tue, Aug 25, 2026 at 2:57 AM Alberto Piai <alberto.piai@gmail.com> wrote:

What do you think?

As a user, I would find it very surprising if ALTER TABLE ONLY ... SET
EXPRESSION failed sometimes, depending on how dependencies are set up.
It would be great if we'd manage to get this working.

The previous patch v3 is incorrect.

ATExecCmd->ATExecSetExpression.
In ATRewriteCatalogs, we have
```
foreach(lcmd, subcmds)
ATExecCmd(wqueue, tab,
lfirst_node(AlterTableCmd, lcmd),
lockmode, pass, context);

/*
* After the ALTER TYPE or SET EXPRESSION pass, do cleanup work
* (this is not done in ATExecAlterColumnType since it should be
* done only once if multiple columns of a table are altered).
*/
if (pass == AT_PASS_ALTER_TYPE || pass == AT_PASS_SET_EXPRESSION)
ATPostAlterTypeCleanup(wqueue, tab, lockmode);
`````

Consider ALTER TABLE on a partitioned table with SET EXPRESSION.
It will drop and recreate the dependent objects (such as indexes and
constraints) of the partitioned table first, and then process each partition.

If we call RememberAllDependentForRebuilding and
RememberWholeRowDependentForRebuilding only in Phase 1 (ATPrepCmd) for
each partition,
the dependent objects of the partitions may already have been dropped
as part of the cascading drop of the corresponding dependent objects
on the partitioned table in ATPostAlterTypeCleanup.

As a result, by the time we reach ATPostAlterTypeCleanup for the partition,
AlteredTableInfo->changedConstraintOids and AlteredTableInfo->changedIndexOids
may refer to dropped objects.

Therefore, RememberAllDependentForRebuilding and
RememberWholeRowDependentForRebuilding need to remain within
ATExecSetExpression.

But we want ALTER TABLE partitionX SET EXPRESSION to succeed when partitionX
itself does not have any index dependencies or other dependencies.
(partitionX is a partition, not a partitioned table).

So, during Phase 1 (ATPrepCmd), call RememberAllDependentForRebuilding
and RememberWholeRowDependentForRebuilding to detect unsupported dependencies
and report error if necessary. After the check, reset the corresponding lists
to NIL so that the dependencies are not actually queued for rebuilding.

In v4-0001-Fix-dependency-issue-when-directly-ALTER-TABLE-SET-EXPRESSION-o.nocfbot
We transform tab->changedConstraintOids to tab->constraints and delete
unncessary
tab->changedConstraintOids logic inside ATPostAlterTypeCleanup, seems
more intuitive IMHO.

In v4-0001-Disallow-directly-ALTER-TABLE-SET-EXPRESSION-on-child-table-if-de.patch
Disallow directly applying ALTER TABLE SET EXPRESSION on a child
table if dependencies exist;
Disallow ALTER TABLE ONLY SET EXPRESSION on a table if dependencies exist;

--
jian
https://www.enterprisedb.com/

Attachments:

t253271_6
v4-0001-Fix-dependency-issue-when-directly-ALTER-TABLE-SET-EXPRESSION-o.nocfbotapplication/octet-stream; name=v4-0001-Fix-dependency-issue-when-directly-ALTER-TABLE-SET-EXPRESSION-o.nocfbotDownload+454-1
v4-0001-Disallow-directly-ALTER-TABLE-SET-EXPRESSION-on-child-table-if-de.patchtext/x-patch; charset=US-ASCII; name=v4-0001-Disallow-directly-ALTER-TABLE-SET-EXPRESSION-on-child-table-if-de.patchDownload+213-1
#7Nitin Motiani
nitinmotiani@google.com
In reply to: jian he (#6)
Re: ALTER COLUMN SET EXPRESSION on partitions not work in case of constraint dependencies

Hi,

I looked at this as was mentioned on the bug fix for #19773 [1]/messages/by-id/CAH5HC97y7PFE6rJh8kVDUszPxGQE030nZvyHu=wZT7FBkOV3qA@mail.gmail.com. The
pg_dump fix for that bug restores a child's differing generation
expression with ALTER TABLE ONLY ... SET EXPRESSION. With either of
the v4 patches here, that restore fails when the child has a
constraint on the column, e.g.:

CREATE TABLE p (v int, g int GENERATED ALWAYS AS (v * 2) STORED,
CONSTRAINT p_g_pos CHECK (g > 0));
CREATE TABLE c () INHERITS (p);
ALTER TABLE ONLY c ALTER COLUMN g SET EXPRESSION AS (v * 5);
ERROR: ALTER TABLE ONLY ... SET EXPRESSION is not supported for
generated columns with dependent objects on a parent table

On master, the same ALTER succeeds but c loses the inherited CHECK.

Could the re-validate approach also cover inheritance children and
ONLY, so that such dumps restore correctly?

[1]: /messages/by-id/CAH5HC97y7PFE6rJh8kVDUszPxGQE030nZvyHu=wZT7FBkOV3qA@mail.gmail.com

Thanks & Regards,
Nitin Motiani
Google