Adding a stored generated column without long-lived locks
Adding a stored generated column without long-lived locks
Hi, I recently needed to add a stored generated column to a table of nontrivial size, and realized that currently there is no way to do that without rewriting the table under an AccessExclusiveLock. One way I think this could be achieved: - allow turning an existing column into a stored generated column, by default doing a table rewrite using the new stored column expression - when doing the above, try to detect the presence of a check constraint which proves that the contents of the column already match its defined expression, and in that case skip the rewrite This would open up a path to add such a column (GENERATED ALWAYS AS (expr) STORED) without long-lived locks: - add column c, nullable - add trigger to set c = expr for new/updated rows - add constraint check (c = expr) NOT VALID - backfill the table at the appropriate pace - VALIDATE the constraint - alter the column c to be GENERATED ALWAYS AS (expr) STORED, which would skip the rewrite because of the valid check constraint on c - clean up the trigger and the constraint To this effect, I started prototyping an alter table command ALTER TABLE t ALTER COLUMN c ADD GENERATED ALWAYS AS (expr) STORED The syntax seemed like a good fit because it's similar to the command to change a column to be GENERATED AS IDENTITY, but I didn't spend a whole lot of thought on the exact syntax yet. The attached patches are a first prototype for discussion: - patch v1-0001: add the command - patch v1-0002: detect the check constraint and skip the rewrite The check constraint must be of the form (c = ) where `=` is a mergejoinable operator for the type c. The in the constraint and in the column definition are matched structurally, so they must match exactly. Before spending more time on this, I wanted to bring this up for discussion and to gauge interest in the idea. Looking forward to your feedback! Alberto -- Alberto Piai Sensational AG Zürich, Switzerland
Re: Adding a stored generated column without long-lived locks
On Tue Mar 17, 2026 at 5:31 PM +07, Alberto Piai wrote:
> I recently needed to add a stored generated column to a table of
> nontrivial size, and realized that currently there is no way to do
> that without rewriting the table under an AccessExclusiveLock.
[...]
> To this effect, I started prototyping an alter table command
We currently have a way to change the expression of generated columns
(SET EXPRESSION) and a way to turn a generated column into a regular one
(DROP EXPRESSION). The new command would fit nicely and provide the
missing piece of functionality: turning an existing column into a
generated column.
A few thoughts:
- since this is specifically useful for *stored* generated columns (to
have a way to avoid a rewrite while the table is locked), I would
stick to my first proposal and require that STORED is specified
explicitly. It would still be possible to remove this requirement and
expand to virtual generated columns, should the need for this arise in
the future (I just don't see the use case right now).
- realizing that this is the opposite operation of DROP EXPRESSION gave
me a clue about how to support partitioning/inheritance.
AT_DropExpression can be applied only to the whole inheritance tree at
once (see 8bf6ec3ba3a44448817af47a080587f3b71bee08 and the associated
discussion at https://postgr.es/m/2793383.1672944799@sss.pgh.pa.us),
it refuses to be applied to either the parent table ONLY, or directly
to partitions. This new command should work the same way.
- while researching the above, I stumbled upon a restriction of current
DROP EXPRESSION: it doesn't seem to be possible to apply it to
partition trees deeper than just one level (parent / child tables).
This is probably an oversight, but to avoid feature-creeping this
patch, I made the new command act the same way (see test case). I'll
try to address this separately.
- I added some note in the commit message to clarify why I added the new
command to AT_PASS_SET_EXPRESSION, since this wasn't clear enough in
my first mail/patch.
- I am not particularly attached to the syntax. Alternatives that would
come to mind would be:
SET GENERATED ALWAYS AS (expr) STORED
or to match the two existing commands:
ADD EXPRESSION (expr) STORED
As I said above, I think the explicit STORED is necessary. It would be
nice if the command would make it crystal clear to the user that it
implies rewriting the table, i.e. overwriting existing data. (To me,
all three forms are clear enough, especially considering that by this
point I would have already typed ALTER twice :-))
The attached v2 patches take care of the points above. They are again
split in two commits for ease of review.
Looking forward to any comment / feedback!
Alberto
PS: A note about the timing of this mail, as I am just getting
acquainted with all of this. I am aware that we're super short of a
feature freeze, and this thread is by no means an attempt to push for
this to go in now, nor to steal brain bandwidth from more important
active threads. I just thought it's OK to put the patches and the mails
out there as I make progress, even if it's just to bring this up and
revisit at a later point in time. Let me know if instead it would be
better to sit on my thoughts until a more appropriate time in the
release cycle.
--
Alberto Piai
Sensational AG
Zürich, Switzerland
Re: Adding a stored generated column without long-lived locks
On Tue Apr 7, 2026 at 5:02 PM +08, Alberto Piai wrote: > On Tue Mar 17, 2026 at 5:31 PM +07, Alberto Piai wrote: > >> I recently needed to add a stored generated column to a table of >> nontrivial size, and realized that currently there is no way to do >> that without rewriting the table under an AccessExclusiveLock. Attached v3, just a rebase onto current master. Regards, Alberto -- Alberto Piai Sensational AG Zürich, Switzerland
Re: Adding a stored generated column without long-lived locks
От:
Laurenz Albe <laurenz.albe@cybertec.at>
Дата:
On Thu, 2026-05-14 at 15:46 -0700, Alberto Piai wrote:
> > > On Tue Mar 17, 2026 at 5:31 PM +07, Alberto Piai wrote:
> > >
> > > > I recently needed to add a stored generated column to a table of
> > > > nontrivial size, and realized that currently there is no way to do
> > > > that without rewriting the table under an AccessExclusiveLock.
>
> The attached v4 is a rebase against current master
I understand the need that the patch fulfills, and I agree that it would be a
nice feature.
I have a few thoughts about this that don't concern the implementation:
1) The SQL standard knows ALTER TABLE ... ADD ... GENERATED ALWAYS AS (...)
and ALTER TABLE ... ALTER ... DROP EXPRESSION, but there is no provision
for ALTER TABLE ... ADD GENERATED ALWAYS AS (...).
So this patch adds non-standard syntax that may one day conflict with
a new version of the standard. I think we can still do it, and the
proposed syntax looks right, but I thought I should mention it.
2) We currently have ALTER TABLE ... ALTER ... SET EXPRESSION AS (...) to
change the generation expression of a column. This command always
rewrites the table, according to the documentation.
I think that if the present patch adds support to skip rewriting the table
when a generation expression is added and the expression matches a check
constraint, changing the generation expression should also be possible
without a rewrite. If not, I would consider that a violation of the
principle of least astonishment.
Would it be difficult to extend the patch to support that?
3) We already have a couple of tricks to avoid blocking for a long time:
- ALTER TABLE ... ALTER ... SET NOT NULL can skip the table scan if there
is a check constraint that makes sure that the column is NOT NULL
- ALTER TABLE ... ATTACH PARTITION can skip the scan of the new partition
if there is a check constraint matching the partition constraint
It would be great to document these little tricks in the documentation,
probably on the ALTER TABLE page. This is not necessarily the job of
this patch, but it would also not be off-topic for the patch.
Comments on the patch:
----------------------
The patch applies and builds cleanly and passes the regression tests.
Missing parts:
- There is no documentation. At least ALTER TABLE needs a description of the
new syntax, and would ideally mention the trick with the check constraint.
- There should be support for command line completion for the new syntax.
Bugs:
- The patch doesn't test if the column is an identity column:
CREATE TABLE tab (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY);
INSERT INTO tab VALUES (DEFAULT);
ALTER TABLE tab ALTER id ADD GENERATED ALWAYS AS (1) STORED;
The ALTER TABLE should fail, but doesn't.
- Strange behavior with sequences owned by the column:
CREATE TABLE tab (id bigserial);
INSERT INTO tab VALUES (DEFAULT);
ALTER TABLE tab ALTER id ADD GENERATED ALWAYS AS (1) STORED;
\ds tab_id_seq
List of sequences
Schema | Name | Type | Owner
--------+------------+----------+----------
public | tab_id_seq | sequence | postgres
(1 row)
I think that any sequence owned by the column should be dropped.
Alternatively, you could throw an error.
- Incorrect handling of NULL values:
CREATE TABLE tab (col1 integer, col2 integer);
INSERT INTO tab VALUES (2, NULL);
-- works, because NULL results from the check are accepted
ALTER TABLE tab ADD CHECK (col2 = col1);
SELECT pg_relation_filenode('tab');
pg_relation_filenode
----------------------
19920
(1 row)
ALTER TABLE tab ALTER col2 ADD GENERATED ALWAYS AS (col1) STORED;
SELECT pg_relation_filenode('tab');
pg_relation_filenode
----------------------
19920
(1 row)
TABLE tab;
col1 | col2
------+------
2 | ∅
(1 row)
I am not sure what the correct approach would be. The simple approach would be
to only skip the rewrite if the column has a NOT NULL constraint or an equivalent
check constraint, but perhaps you can think of a way to do better.
Comments on the code:
> --- a/src/backend/commands/tablecmds.c
> +++ b/src/backend/commands/tablecmds.c
> @@ -5093,6 +5102,13 @@ ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
> ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context);
> pass = AT_PASS_SET_EXPRESSION;
> break;
> + case AT_AddGeneratedAsExprStored:
You should add a comment, same as for the other branches.
> @@ -6695,6 +6717,8 @@ alter_table_type_to_string(AlterTableType cmdtype)
> return "ALTER COLUMN ... SET NOT NULL";
> case AT_SetExpression:
> return "ALTER COLUMN ... SET EXPRESSION";
> + case AT_AddGeneratedAsExprStored:
> + return "ALTER COLUMN ... ADD GENERATED ALWAYS AS (...) STORED";
Keep it short, like "ALTER COLUMN ... ADD GENERATED".
> --- a/src/test/modules/test_ddl_deparse/test_ddl_deparse.c
> +++ b/src/test/modules/test_ddl_deparse/test_ddl_deparse.c
> @@ -129,6 +129,9 @@ get_altertable_subcmdinfo(PG_FUNCTION_ARGS)
> case AT_SetNotNull:
> strtype = "SET NOT NULL";
> break;
> + case AT_AddGeneratedAsExprStored:
> + strtype = "ADD GENERATED ALWAYS AS (...) STORED";
> + break;
I suggest "ALTER COLUMN ADD GENERATED ALWAYS AS", but I won't insist.
Yours,
Laurenz Albe
Re: Adding a stored generated column without long-lived locks
От:
Laurenz Albe <laurenz.albe@cybertec.at>
Дата:
On Wed, 2026-05-27 at 19:43 +0200, Alberto Piai wrote: > I'd like to take his point, together with the question from Tom and the > suggestion by Álvaro, and make a new proposal for the design of this > command. > > Design iteration 2 > ------------------ > > Syntax: > > ALTER TABLE t ALTER COLUMN c > ADD GENERATED ALWAYS AS (expr) STORED USING CONSTRAINT check_name > > check_name must be a valid constraint of the form > > CHECK (c IS NOT DISTINCT FROM (expr)) > > This fails if: > > - a check constraint named check_name is not found for table c > - the constraint is not valid > - the constraint does not match exactly the expr the user intends to use > as a stored default expression > > On success, the table c is now a stored generated column with the given > default expression, and the check_name constraint has been removed. > > This addresses Tom's remark, we can now fail instead of just rewriting > the column. I like this proposal. It avoids the question "to rewrite or not to rewrite" by just outright failing if there is no suitable constraint. The idea to avoid the problem with NULL by forcing IS NOT DISTINCT FROM in the constraint is a good solution. Perhaps you could also allow the equality operator if the column in question is defined NOT NULL. > It improves slightly upon the issue of a potential conflict with a > future edition of the SQL standard, by being more specific. I don't see > a way to be completely sure we won't have conflicts. We could improve > more by making the syntax more "alien" and very unlinkely to be picked > up by the standard, but at a usability cost for Postgres. I'm open to > suggestions. I don't think that the new proposal makes it less likely to get in conflict with later additions to the standard. But I don't think that inventing unlikely syntax to avoid such conflicts is a good idea. First, the standard committee itself seems (or seemed) to have a strong predilection for alien, verbose syntax. Second, if we end up with weird, unwieldy syntax, that would be bad. No, the syntax you are proposing sounds reasonable to me. > It improves upon another question raised by Álvaro: does the user have > to clean up the constraint? In v1 I felt it was better to have the user > remove it after the migration. Since here it's explicitly mentioned as > the constraint to use to migrate the column, I think it's OK to remove > it. We are conceptually moving it from being a constraint to being the > new default expression. > > The implementation should also be simpler, since there will never be a > table rewrite. > > Any thoughts about this? Yes. I think that you should not drop the constraint. That's what I'd expect, similar to how we don't drop the check constraint that allows to skip the table scan in ALTER TABLE ... ALTER COLUMN ... SET NOT NULL or ALTER TABLE ... ATTACK PARTITION. I feel that automatically dropping the constraint is a bit too much black magic, but it is more a feeling than a conviction. Yours, Laurenz Albe
Re: Adding a stored generated column without long-lived locks
От:
Laurenz Albe <laurenz.albe@cybertec.at>
Дата:
On Wed, 2026-05-27 at 19:44 +0200, Alberto Piai wrote: > On Tue May 26, 2026 at 5:23 PM CEST, Laurenz Albe wrote: > > > > 2) We currently have ALTER TABLE ... ALTER ... SET EXPRESSION AS (...) to > > change the generation expression of a column. This command always > > rewrites the table, according to the documentation. > > I think that if the present patch adds support to skip rewriting the table > > when a generation expression is added and the expression matches a check > > constraint, changing the generation expression should also be possible > > without a rewrite. If not, I would consider that a violation of the > > principle of least astonishment. > > Would it be difficult to extend the patch to support that? > > Yes, I don't see a way to make that work. Since we're talking only about > stored values, a rewrite will always be necessary. However, using this > new command, a user could add a column with the new expression, then > atomically drop the old one and rename. All without holding onto an > AccessExclusiveLock for a long time :) With your new proposal to never rewrite the table, but fail instead if there is no constraint, my objection loses its point, so I withdraw it. > > 3) We already have a couple of tricks to avoid blocking for a long time: > > > > - ALTER TABLE ... ALTER ... SET NOT NULL can skip the table scan if there > > is a check constraint that makes sure that the column is NOT NULL > > > > - ALTER TABLE ... ATTACH PARTITION can skip the scan of the new partition > > if there is a check constraint matching the partition constraint > > > > It would be great to document these little tricks in the documentation, > > probably on the ALTER TABLE page. This is not necessarily the job of > > this patch, but it would also not be off-topic for the patch. > > The SET NOT NULL one and the ATTACH PARTITION one are documented in the > section specific to the command. However > > or, if an equivalent index already exists, it will be attached to the > target table's index, as if ALTER INDEX ATTACH PARTITION had been > executed > > is not very explicit about the advantages this has for online > migrations. > > In the NOTES section of the ALTER TABLE page, there is a paragraph about > NOT VALID / VALIDATE, which is another operation in the same spirit as > this. > > Maybe we could group them all in a new section dedicated to online > schema migrations? You are right, the existing shortcuts are documented. Your new proposal makes the proposed feature different from these existing cases, so I don't think lumping them together is a good idea now. > Agreed, will fix all these in the next version of the patch. Great; I'm looking forward to it. Yours, Laurenz Albe
Re: Adding a stored generated column without long-lived locks
v5 had a rather brittle test that was relying on a DEBUG message being emitted when phase 3 verifies or rewrites a table (via client_min_messages). That was failing on the CI because the output depends on any other setting that might affect logging (in this case it was log_statement). The attached v6 replaces it with an injection_point test. If adding new injection points to detect scans/rewrites is considered too much, I can back it out and set/reset log_statement too. But I do prefer the injection_point test. If the new injection point is good, there are also a couple more tests which might be updated to use it. Regards, Alberto -- Alberto Piai Sensational AG Zürich, Switzerland
Re: Adding a stored generated column without long-lived locks
От:
Laurenz Albe <laurenz.albe@cybertec.at>
Дата:
On Fri, 2026-07-10 at 02:10 +0200, Alberto Piai wrote:
> > The syntax you ended up with (ADD GENERATED ALWAYS STORED USING CONSTRAINT)
> > is ugly as hell. I see your point in having ALWAYS and STORED, but perhaps
> > ADD GENERATED ALWAYS USING CONSTRAINT ... STORED would be better, as it is
> > syntactically more like GENERATED ALWAYS AS (...) STORED, which would make
> > it easier to remember.
> >
> > Or perhaps ADD GENERATED USING CONSTRAINT would be enough, since ALWAYS and
> > STORED are the only possible choice anyway. I am a bit uncertain on what
> > is best here.
>
> Your point about moving STORED at the end is good, I feel bad about
> dropping it completely though, because in the ADD COLUMN subcommand the
> default is VIRTUAL when omitted. Maybe we could drop the ALWAYS, since
> that is only relevant when talking about identity columns. That would
> result in:
>
> ... ADD GENERATED USING CONSTRAINT constr_name STORED
>
> Another option would be to be consistent with SET|DROP EXPRESSION:
>
> ... ADD EXPRESSION USING CONSTRAINT constr_name STORED
>
> I would not omit STORED here either, because SET|DROP EXPRESSION act on
> what's already a generated column (so they don't need to specify the
> type at all), but this one does need to know.
>
> The ALTER TABLE page of the manual already groups these 3 together:
>
> ADD GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY
> SET GENERATED { ALWAYS | BY DEFAULT }
> DROP IDENTITY [ IF EXISTS ]
>
> These forms change whether a column is an identity column...
>
> Using EXPRESSION for this new command would result in a similar group:
>
> ADD EXPRESSION USING CONSTRAINT constr_name STORED
> SET EXPRESSION AS
> DROP EXPRESSION [ IF EXISTS ]
>
> the three forms change whether a column is a generated column or change
> the generator expression. The first and the third only work with stored
> generated columns.
>
> But at this point we are just debating whether to say GENERATED or
> EXPRESSION. Personally I find both OK with a slight preference for the
> latter.
I take your point about keeping the STORED. If VIRTUAL is the default
when creating a generated column, then keeping the explicit STORED makes
sense.
About GENERATED vs. EXPRESSION: my feelings go the other way. If I read
ALTER TABLE tab ALTER col ADD EXPRESSION ...
then it is not clear to me *what* expression is added. After all, there
are not only generation expressions, but also column default expressions,
and I think it is good to make clear that this is about generated columns.
I think I understand your preference: after all, we are not ADDing a
GENERATED column, but only an EXPRESSION that turns a regular column
into a generated column. Perhaps I can convince you by showing the
similar
ALTER TABLE tab ALTER col ADD GENERATED ALWAYS AS IDENTITY;
Here, too, we are not adding a new generated column, only turning a
regular column into a generated one. I think it is good to stay as
close to that already established syntax as possible.
> > >
> > There is a weird asymmetry in that the order in which you write the check
> > constraint matters:
> >
> > CREATE TABLE tab (a integer PRIMARY KEY, b integer NOT NULL);
> > INSERT INTO tab VALUES (1, 2);
> >
> > -- this fails
> > ALTER TABLE tab ADD CONSTRAINT c CHECK (2 * a = b);
> > ALTER TABLE tab ALTER b ADD GENERATED ALWAYS STORED USING CONSTRAINT c;
> > ERROR: cannot convert a column into a stored generated column without a constraint to prove that the values are consistent
> > DETAIL: could not find a valid constraint "c" CHECK ("b" = expr) or CHECK ("b" IS NOT DISTINCT FROM (expr))
> >
> > -- but this works
> > ALTER TABLE tab DROP CONSTRAINT c;
> > ALTER TABLE tab ADD CONSTRAINT c CHECK (b = 2 * a);
> > ALTER TABLE tab ALTER b ADD GENERATED ALWAYS STORED USING CONSTRAINT c;
> >
> > I think that both variants should be accepted, but I am not certain.
>
> My original approach here was to be as literal as possible with the
> shape of the constraint required to perform this operation. It is after
> all an extremely ad-hoc constraint, added just for the purpose of doing
> this online migration. But just checking both directions for the
> equalities seems simple enough, I'll try to do this in the next version
> of the patch.
Right; I thought that it was no big deal. And this would be the only case
in the PostgreSQL SQL dialect that I know where the order of the operands
for an equality condition matters.
> > > + /*
> > > + * Ignore the column's own default expression. We
> > > + * handle sequences above, and for a column which is
> > > + * already a generated column we should never get
> > > + * here.
> > > + */
> >
> > It's not strictly required, but it would be great if you could run pgindent
> > to get comments and other parts of the code formatted properly.
>
> This is strange, I did run pgindent. Which part seems formatted
> incorrectly to you? I'll try to see if we're hitting some edge case that
> makes pgindent skip the code.
I had not tested it, but the lines seemed to be shorter than the 80 columns
to which pgindent formats comments.
If you already ran pgindent, please ignore my comment.
Yours,
Laurenz Albe
Re: Adding a stored generated column without long-lived locks
От:
Laurenz Albe <laurenz.albe@cybertec.at>
Дата:
On Thu, 2026-08-06 at 14:36 +0200, Alberto Piai wrote:
> PFA v7, implementing this version of the command:
>
> ... ALTER col ADD GENERATED USING CONSTRAINT constr_name STORED
Great! I think this is pretty much good to go.
> In particular, all the error messages now follow the guidelines for
> error reporting. I tried to use a consistent error message everywhere,
> adding details and hints where appropriate.
Much better!
I was wondering about this hint:
Use this command on the root table/partition without ONLY.
You can never turn a column of a partition into a generated column, right?
How about
Use the command on the partition root without specifying ONLY.
This detail message is longer than 80 characters:
Converting a column to a stored generated column can only be done on the whole hierarchy at once.
How about
Converting only part of a partitioning/inheritance hierarchy is not supported.
> A note about this one:
>
> > The following error message is not very helpful:
> >
> >
> > CREATE TABLE tab (
> > a integer DEFAULT 2,
> > b integer
> > CONSTRAINT con CHECK (b IS NOT DISTINCT FROM 2 + random())
> > );
> >
> >
> > ALTER TABLE tab ALTER b ADD GENERATED ALWAYS STORED USING CONSTRAINT con;
> > ERROR: cannot convert a column into a stored generated column without a constraint to prove that the values are consistent
> > DETAIL: could not find a valid constraint "con" CHECK ("b" IS NOT DISTINCT FROM (expr))
>
> This was interesting. What's going on here is that since random()
> returns a float, the whole expression returns a float. The column b is
> an int, so since there is an implicit cast from int to float, the
> resulting expression for the CHECK constraint is
>
> b::float IS NOT DISTINCT FROM 2 + random()
>
> I think in cases like this there's not much I can do: the constraint
> isn't an equality to b anymore, but an equality to f(b) where f is
> the function defined for the cast. The constraint is simply not usable
> for our purpose.
>
> For this reason, I think it doesn't make too much sense in this case to
> look at the other operand, hunt down the random() and complain about the
> function being volatile: the core problem here is the return type, and
> the same situation can happen with an immutable function.
>
> I tried detecting implicit casts though, because I think this is a
> mistake that's quite easy to make, so it's worth trying to give a hint
> to the user about what's going on and what to do.
>
> This is now reported in this way (from the regress test suite):
>
> alter table tgen.t1 add constraint chk_gen check (b is not distinct from (a + random()));
> -- the hint should inform about the type cast
> alter table tgen.t1 alter column b add generated using constraint chk_gen stored;
> ERROR: cannot convert column "b" to generated
> DETAIL: Could not find a valid constraint "chk_gen" CHECK ("b" IS NOT DISTINCT FROM expr).
> HINT: Ensure that the type of the expression matches the type of the column.
>
> In this situation, \d would show the constraint being
>
> CHECK (b::double precision = (.... expr with random())
>
> instead of b = ...expr, which makes me think the hint is clear enough.
> But I'm curious to hear what you think about it.
>
> Independently from the problem with casts, the immutability of the
> generation expression is of course also checked:
>
> alter table tgen.t2 add constraint chk_gen check (b is not distinct from (a + random()::int));
> alter table tgen.t2 alter column b
> add generated using constraint chk_gen stored;
> ERROR: generation expression is not immutable
I agree with your assessment; thanks for the additional hint!
There is one sentence in the documentation that sounds wrong to me:
+
+ After this command is run, column_name will be a stored
+ generated column with expr as its generation
+ expression.
+
Shouldn't it be "after this command has been run"? Or perhaps "has completed"?
Yours,
Laurenz Albe
Re: Adding a stored generated column without long-lived locks
От:
"Alberto Piai" <alberto.piai@gmail.com>
Дата:
On Tue Aug 25, 2026 at 10:46 AM CEST, Laurenz Albe wrote: > On Mon, 2026-08-24 at 22:03 +0200, Alberto Piai wrote: >> > I was wondering about this hint: >> > >> > Use this command on the root table/partition without ONLY. >> > >> > You can never turn a column of a partition into a generated column, right? >> > How about >> > >> > Use the command on the partition root without specifying ONLY. >> >> Since this is also taking care of classic inheritance, it seems strange >> to only mention partitions. But I see that this way it's confusing (and >> I do concede that partitioning might be the more widely used of the two) >> so I switched it around to "on the root partition/table without >> specifying ONLY". Does that make more sense? > > My problem is that there is no "root partition". Ah, I see what you mean now. I agree, "root partition" makes no sense. So, removing the slash, it would look like: ERROR: cannot convert column "c" to generated DETAIL: Converting only part of a partitioning or inheritance hierarchy is not supported. HINT: Use this command on the partitioning or inheritance root without specifying ONLY. Maybe a bit heavy on the eye? Since the root of the hierarchy is in both cases just a table (partitoned or not), what about just calling it a table? ERROR: cannot convert column "c" to generated DETAIL: Converting only part of a partitioning or inheritance hierarchy is not supported. HINT: Use this command on the root table without specifying ONLY. Regards, Alberto -- Alberto Piai Sensational AG Zürich, Switzerland
Re: Adding a stored generated column without long-lived locks
От:
Laurenz Albe <laurenz.albe@cybertec.at>
Дата:
On Tue, 2026-08-25 at 18:13 +0200, Alberto Piai wrote: > Ah, I see what you mean now. I agree, "root partition" makes no sense. > > So, removing the slash, it would look like: > > ERROR: cannot convert column "c" to generated > DETAIL: Converting only part of a partitioning or inheritance hierarchy is not supported. > HINT: Use this command on the partitioning or inheritance root without specifying ONLY. > > Maybe a bit heavy on the eye? > > Since the root of the hierarchy is in both cases just a table > (partitoned or not), what about just calling it a table? > > ERROR: cannot convert column "c" to generated > DETAIL: Converting only part of a partitioning or inheritance hierarchy is not supported. > HINT: Use this command on the root table without specifying ONLY. Both variants look fine to me. Pick the one you prefer. Yours, Laurenz Albe
Re: Adding a stored generated column without long-lived locks
От:
solai v <solai.cdac@gmail.com>
Дата:
Hi, I tested v10 of the patch on the latest PostgreSQL master. The patch applied cleanly, and PostgreSQL built successfully. git diff --check completed without any issues. I also ran: make check and all regression tests passed. For the main functionality, I created a table with 100,000 existing rows, backfilled the column, and added the required CHECK constraint: CHECK (generated_value IS NOT DISTINCT FROM id * 2) The following command then completed successfully: ALTER TABLE test_gen_v10 ALTER COLUMN generated_value ADD GENERATED USING CONSTRAINT test_gen_v10_check STORED; The column was confirmed as: generated always as (id * 2) stored I also tested the conversion with a table containing 1,000,000 rows. The relation file path and size remained unchanged before and after the conversion: Before: filepath: base/5/16393 size: 44,285,952 bytes (42 MB) After: filepath: base/5/16393 size: 44,285,952 bytes (42 MB) This indicates that the table was not physically rewritten during the conversion. Overall, the v10 patch worked as expected in my testing. Regards, solai
Re: Adding a stored generated column without long-lived locks
CFBot alerted me that a rebase was needed, so here it is in the attached v11. I also fixed a couple broken / duplicated tests that had eluded me in my last pass over this, and shortened the wording in this error message a bit: ERROR: cannot convert column "b" to generated -DETAIL: Column "b" of relation "t2" is a serial column (depends on sequence "sequence tgen.t2_b_seq"). +DETAIL: Column "b" of relation "t2" is a serial column (depends on "sequence tgen.t2_b_seq"). Kind regards, Alberto -- Alberto Piai Sensational AG Zürich, Switzerland
Re: Adding a stored generated column without long-lived locks
От:
"Alberto Piai" <alberto.piai@gmail.com>
Дата:
Hi all,
in an attempt to avoid wasting committer time, I decided to use an
LLM-based tool to analyze this patch and try to come up with
counterexamples to break my usage of IS NOT DISTINCT FROM.
It produced an example showing how IS NOT DISTINCT FROM isn't good
enough either for my purpose.
The problem is types where some values are evaluated as equal (according
to =), but don't have the same representation. In conjuction with a
unique index, they could be used to put a database in an invalid state
where rewriting operations (update ... set a = a or pg_dump/pg_restore)
fail.
Repro:
create table tgen.t_repro_1 (a numeric, b numeric);
insert into tgen.t_repro_1 values ('1.0', '1.00'), ('1.0', '1.0');
create unique index on tgen.t_repro_1 ((b::text));
alter table tgen.t_repro_1
add constraint chk_gen check (b is not distinct from a);
alter table tgen.t_repro_1
alter b add generated using constraint chk_gen stored;
update tgen.t_repro_1 set a = a;
ERROR: duplicate key value violates unique constraint "t_repro_1_b_idx"
DETAIL: Key ((b::text))=(1.0) already exists.
I will have to re-think this quite a bit. In general it's clear that I
need to use an operator which proves that the value is identical bit by
bit to what evaluating the expression would produce. The question will
be how to make this accessible and usable enough, and at which cost in
complexity.
I won't have time to work on this for at least a few days, so in the
meantime I will remove the "ready for committer" tag to avoid luring
anyone into looking at this (at least with the committer hat on). Any
feedback | thought | idea would of course be very welcome! :)
Kind regards,
Alberto
--
Alberto Piai
Sensational AG
Zürich, Switzerland
Re: Adding a stored generated column without long-lived locks
От:
Laurenz Albe <laurenz.albe@cybertec.at>
Дата:
On Mon, 2026-09-21 at 23:48 +0200, Alberto Piai wrote:
> in an attempt to avoid wasting committer time, I decided to use an
> LLM-based tool to analyze this patch and try to come up with
> counterexamples to break my usage of IS NOT DISTINCT FROM.
>
> It produced an example showing how IS NOT DISTINCT FROM isn't good
> enough either for my purpose.
>
> The problem is types where some values are evaluated as equal (according
> to =), but don't have the same representation. In conjuction with a
> unique index, they could be used to put a database in an invalid state
> where rewriting operations (update ... set a = a or pg_dump/pg_restore)
> fail.
>
> Repro:
>
> create table tgen.t_repro_1 (a numeric, b numeric);
> insert into tgen.t_repro_1 values ('1.0', '1.00'), ('1.0', '1.0');
> create unique index on tgen.t_repro_1 ((b::text));
> alter table tgen.t_repro_1
> add constraint chk_gen check (b is not distinct from a);
>
> alter table tgen.t_repro_1
> alter b add generated using constraint chk_gen stored;
>
> update tgen.t_repro_1 set a = a;
> ERROR: duplicate key value violates unique constraint "t_repro_1_b_idx"
> DETAIL: Key ((b::text))=(1.0) already exists.
>
>
> I will have to re-think this quite a bit.
Ho, hum. Case insensitive collations would be another example.
There is no way to write "is binary identical to" in SQL, as far as
I can tell.
Perhaps a solution would be to force the use of the data type's send
function in the check constraint:
ALTER TABLE t_repro_1 ADD CHECK
(numeric_send(b) IS NOT DISTINCT FROM numeric_send(a));
That would exclude data types that don't have a send function
(which is probably no big loss), and I am not certain if the send
function is required to represent the binary data exactly (it does
for the system data types, as far as I know).
Yours,
Laurenz Albe
Re: Adding a stored generated column without long-lived locks
От:
Matthias van de Meent <boekewurm+postgres@gmail.com>
Дата:
On Tue, 22 Sept 2026 at 15:02, Laurenz Albe wrote:
>
> On Mon, 2026-09-21 at 23:48 +0200, Alberto Piai wrote:
> > in an attempt to avoid wasting committer time, I decided to use an
> > LLM-based tool to analyze this patch and try to come up with
> > counterexamples to break my usage of IS NOT DISTINCT FROM.
> >
> > It produced an example showing how IS NOT DISTINCT FROM isn't good
> > enough either for my purpose.
> >
> > The problem is types where some values are evaluated as equal (according
> > to =), but don't have the same representation. In conjuction with a
> > unique index, they could be used to put a database in an invalid state
> > where rewriting operations (update ... set a = a or pg_dump/pg_restore)
> > fail.
> >
> > Repro:
> >
> > create table tgen.t_repro_1 (a numeric, b numeric);
> > insert into tgen.t_repro_1 values ('1.0', '1.00'), ('1.0', '1.0');
> > create unique index on tgen.t_repro_1 ((b::text));
> > alter table tgen.t_repro_1
> > add constraint chk_gen check (b is not distinct from a);
> >
> > alter table tgen.t_repro_1
> > alter b add generated using constraint chk_gen stored;
> >
> > update tgen.t_repro_1 set a = a;
> > ERROR: duplicate key value violates unique constraint "t_repro_1_b_idx"
> > DETAIL: Key ((b::text))=(1.0) already exists.
> >
> >
> > I will have to re-think this quite a bit.
>
> Ho, hum. Case insensitive collations would be another example.
>
> There is no way to write "is binary identical to" in SQL, as far as
> I can tell.
None yet: [0] is a patch that adds a pg_datum_image_equal(a, b)
function that should allow users to detect binary differences in all
types of values. It won't detect differences in the way data is
stored (it only checks detoasted datum differences, so toast ID or
compression types are not tested), but I think the function added in
that patch is sufficient for this use case, too.
> Perhaps a solution would be to force the use of the data type's send
> function in the check constraint:
Going through sendfn can be rather expensive (even compared to
detoasting), which is why I started the work on [0]: At databricks we
had a comparable use case of needing to detect exactly equal input
data, as cheap as possible.
Note that "is not distinct from" will work correctly when the
underlying = operator is part of a btree opfamily whose equalimage()
support function returns true; this is something that you can use to
make sure the selected constraint in ADD GENERATED can safely be used
even if some other types won't work. The equalimage() support
function's result indicates whether the type has a strict total
ordering (when true), or whether there are values which have different
representations but are considered equal in this opclass' sort
ordering (when false). This same support function also indicates
whether deduplication can be used for the indexed data (when true) or
not (when false).
Kind regards,
Matthias van de Meent
Databricks (https://www.databricks.com)
[0] https://commitfest.postgresql.org/patch/6309/
Re: Adding a stored generated column without long-lived locks
От:
Álvaro Herrera <alvherre@kurilemu.de>
Дата:
On 2026-Sep-21, Alberto Piai wrote:
> Repro:
>
> create table tgen.t_repro_1 (a numeric, b numeric);
> insert into tgen.t_repro_1 values ('1.0', '1.00'), ('1.0', '1.0');
> create unique index on tgen.t_repro_1 ((b::text));
> alter table tgen.t_repro_1
> add constraint chk_gen check (b is not distinct from a);
>
> alter table tgen.t_repro_1
> alter b add generated using constraint chk_gen stored;
>
> update tgen.t_repro_1 set a = a;
> ERROR: duplicate key value violates unique constraint "t_repro_1_b_idx"
> DETAIL: Key ((b::text))=(1.0) already exists.
Does this _matter_?
Does anybody want to have a generated numeric column that's identical to
the base column except it has more zeroes in the decimal part? Or to
generate a text column that's not binary identical to another text
column but compares equal when viewed through an nondeterministic
collation?
I think the answer is no.
I'm pretty okay with saying that if you want to add a new column that's
generated in such a way, then you have to go the normal route of using
the blocking command.
--
Álvaro Herrera Breisgau, Deutschland — https://www.EnterpriseDB.com/
"La experiencia nos dice que el hombre peló millones de veces las patatas,
pero era forzoso admitir la posibilidad de que en un caso entre millones,
las patatas pelarían al hombre" (Ijon Tichy)
Re: Adding a stored generated column without long-lived locks
От:
Matthias van de Meent <boekewurm+postgres@gmail.com>
Дата:
On Tue, 22 Sept 2026 at 17:17, Álvaro Herrera wrote:
>
> On 2026-Sep-21, Alberto Piai wrote:
>
> > Repro:
> >
> > create table tgen.t_repro_1 (a numeric, b numeric);
> > insert into tgen.t_repro_1 values ('1.0', '1.00'), ('1.0', '1.0');
> > create unique index on tgen.t_repro_1 ((b::text));
> > alter table tgen.t_repro_1
> > add constraint chk_gen check (b is not distinct from a);
> >
> > alter table tgen.t_repro_1
> > alter b add generated using constraint chk_gen stored;
> >
> > update tgen.t_repro_1 set a = a;
> > ERROR: duplicate key value violates unique constraint "t_repro_1_b_idx"
> > DETAIL: Key ((b::text))=(1.0) already exists.
>
> Does this _matter_?
Yes, this does matter. We can't start ignoring and tossing
significant zeroes in numeric types, because they have meaning in
scientific calculations, and have different outputs for various
operations, including casts to text, but also functions like scale.
Generated columns should (must) respect that, and produce the same
result between SELECT (gen_col_expr) and SELECT gen_col.
> Does anybody want to have a generated numeric column that's identical to
> the base column except it has more zeroes in the decimal part? Or to
> generate a text column that's not binary identical to another text
> column but compares equal when viewed through an nondeterministic
> collation?
I don't think anyone wants that specifically, but if the database
state contains that numeric column that's identical to the first, but
with more zeroes, or a text column with different encoding, then that
must be detected before we go ahead and fully consider the target
column to be a generated version of the source column; the outputs
must be identical even if the default = operator thinks they have the
same value.
Note that this issue extends to at least jsonb, which uses textual and
numeric comparators internally for the sorting operations; it's
certainly possible to remove or add a few zeroes here and there in
projection steps if you're not careful when you populate the
not-yet-GENERATED column's data.
Kind regards,
Matthias van de Meent
Databricks (https://www.databricks.com)
Re: Adding a stored generated column without long-lived locks
От:
Laurenz Albe <laurenz.albe@cybertec.at>
Дата:
On Wed, 2026-09-23 at 12:07 +0200, Matthias van de Meent wrote:
> On Tue, 22 Sept 2026 at 17:17, Álvaro Herrera wrote:
> > On 2026-Sep-21, Alberto Piai wrote:
> >
> > > Repro:
> > >
> > > create table tgen.t_repro_1 (a numeric, b numeric);
> > > insert into tgen.t_repro_1 values ('1.0', '1.00'), ('1.0', '1.0');
> > > create unique index on tgen.t_repro_1 ((b::text));
> > > alter table tgen.t_repro_1
> > > add constraint chk_gen check (b is not distinct from a);
> > >
> > > alter table tgen.t_repro_1
> > > alter b add generated using constraint chk_gen stored;
> > >
> > > update tgen.t_repro_1 set a = a;
> > > ERROR: duplicate key value violates unique constraint "t_repro_1_b_idx"
> > > DETAIL: Key ((b::text))=(1.0) already exists.
> >
> > Does this _matter_?
>
> Yes, this does matter.
I tend to agree.
Rather than just documenting this problem, I'd say that your idea with
the equalimage() support function has appeal. We can simply reject the
operation if the function returns FALSE.
Yours,
Laurenz Albe
Re: Adding a stored generated column without long-lived locks
От:
"Alberto Piai" <alberto.piai@gmail.com>
Дата:
On Wed Sep 23, 2026 at 12:26 PM CEST, Laurenz Albe wrote:
> On Wed, 2026-09-23 at 12:07 +0200, Matthias van de Meent wrote:
>> On Tue, 22 Sept 2026 at 17:17, Álvaro Herrera wrote:
>> > On 2026-Sep-21, Alberto Piai wrote:
>> >
>> > > Repro:
>> > >
>> > > create table tgen.t_repro_1 (a numeric, b numeric);
>> > > insert into tgen.t_repro_1 values ('1.0', '1.00'), ('1.0', '1.0');
>> > > create unique index on tgen.t_repro_1 ((b::text));
>> > > alter table tgen.t_repro_1
>> > > add constraint chk_gen check (b is not distinct from a);
>> > >
>> > > alter table tgen.t_repro_1
>> > > alter b add generated using constraint chk_gen stored;
>> > >
>> > > update tgen.t_repro_1 set a = a;
>> > > ERROR: duplicate key value violates unique constraint "t_repro_1_b_idx"
>> > > DETAIL: Key ((b::text))=(1.0) already exists.
>> >
>> > Does this _matter_?
>>
>> Yes, this does matter.
>
> I tend to agree.
I too think this matters. The main arugment is IMHO the catastrophic
failure mode: successful ALTER TABLE command, broken pg_restore... I
would hate to put anyone in that situation.
I find Matthias' proposal of exposing a function to check image equality
very compelling for the purpose of this patch: besides fixing this
problem, it would also make the command usable for data types which
don't define = (json), as well as those which don't (can't?) define
equalimage()... jsonb, numeric but also tsvector and PostGIS geometry.
I'll take some time to study/review the patch and the discussion around
it.
Kind regards,
Alberto
--
Alberto Piai
Sensational AG
Zürich, Switzerland
Re: Adding a stored generated column without long-lived locks
От:
Laurenz Albe <laurenz.albe@cybertec.at>
Дата:
On Thu, 2026-09-24 at 00:19 +0200, Alberto Piai wrote: > I find Matthias' proposal of exposing a function to check image equality > very compelling for the purpose of this patch: besides fixing this > problem, it would also make the command usable for data types which > don't define = (json), as well as those which don't (can't?) define > equalimage()... jsonb, numeric but also tsvector and PostGIS geometry. True, "tsvector" is limiting; I can see people wanting that for generated columns. Yours, Laurenz Albe
Re: Adding a stored generated column without long-lived locks
От:
"Alberto Piai" <alberto.piai@gmail.com>
Дата:
On Thu Sep 24, 2026 at 12:47 PM CEST, Laurenz Albe wrote: > On Thu, 2026-09-24 at 00:19 +0200, Alberto Piai wrote: >> I find Matthias' proposal of exposing a function to check image equality >> very compelling for the purpose of this patch: besides fixing this >> problem, it would also make the command usable for data types which >> don't define = (json), as well as those which don't (can't?) define >> equalimage()... jsonb, numeric but also tsvector and PostGIS geometry. > > True, "tsvector" is limiting; I can see people wanting that for > generated columns. I spent some time thinking about the situation, especially about whether the incoherence between the backfilled value and the result of thegenerator expression actually matters in practice. I am acutely aware that the example I reported earlier is somewhat... artificial. However, the fact that any rewrite operation which causes the expression to be recomputed would silently change the stored value (update a = a) really makes me want to treat this like a soundness issue in my patch. (Not to mention the broken pg_restore). So I see only a few ways forward: - drop this patch, which would be too bad because it does address an operational pain point - continue with IS NOT DISTINCT FROM, but restrict it to work with types which implement BTEQUALIMAGE_PROC. This would exclude useful types like jsonb, tsvector and geometry. (Aside regarding geometry: I never had the chance to work with PostGIS, but at a quick glance it seems to store a lot of information in typmod. It would definitely be wrong to implement equalimage. But there seems to be so much in there that I wonder whether it would not be very difficult for a user trying to backfill the column to do so in a way that it would satisfy a stricter image-equality constraint. I might very well be misreading all of this, though.) - work on exposing image equality as proposed by Matthias' pg_datum_image_equal(), and require that for the constraint (we could optionally allow IS NOT DISTINCT FROM for types which implement equalimage, but I find the function as simple to use. Since this is an extremely ad-hoc constraint created just for the purpose of a migration, I'd go for function-only) The notion of image equality already is somewhat exposed to the user through *= (record_image_eq). I wonder what could be the downsides of also exposing it for a single Datum. For the purpose of this alter table command, one concern could be that it's "too difficult" to produce values satisfying the stricter constraint when backfilling (see concerns about gemoetry above). But for the use cases I would use it for, I'd write the backfilling code to derive the value from the row, using the exact same expression I just used for the constraint. And if I failed to do so, then I'd get a pretty clear constraint failure. I'll add my review and this use case to the other thread, but in the meantime I thought I could already post this, even if it contains more open thoughts and questions than a concrete proposal. Regards, Alberto -- Alberto Piai Sensational AG Zürich, Switzerland
Re: Adding a stored generated column without long-lived locks
От:
Laurenz Albe <laurenz.albe@cybertec.at>
Дата:
On Fri, 2026-10-02 at 01:30 +0200, Alberto Piai wrote: > On Thu Sep 24, 2026 at 12:47 PM CEST, Laurenz Albe wrote: > > On Thu, 2026-09-24 at 00:19 +0200, Alberto Piai wrote: > > > I find Matthias' proposal of exposing a function to check image equality > > > very compelling for the purpose of this patch: besides fixing this > > > problem, it would also make the command usable for data types which > > > don't define = (json), as well as those which don't (can't?) define > > > equalimage()... jsonb, numeric but also tsvector and PostGIS geometry. > > > > True, "tsvector" is limiting; I can see people wanting that for > > generated columns. > > I spent some time thinking about the situation [...] > > The notion of image equality already is somewhat exposed to the user > through *= (record_image_eq). I wonder what could be the downsides of > also exposing it for a single Datum. You could simply require the constraint to be ROW(col)::record *= ROW(expression)::record That would also behave as desired for NULL values. True, it looks hacky, but as you said, it is a constraint created for this special purpose. Yours, Laurenz Albe
Re: Adding a stored generated column without long-lived locks
От:
Matthias van de Meent <boekewurm+postgres@gmail.com>
Дата:
On Fri, 2 Oct 2026 at 09:30, Laurenz Albe wrote: > > You could simply require the constraint to be > > ROW(col)::record *= ROW(expression)::record > > That would also behave as desired for NULL values. > > True, it looks hacky, but as you said, it is a constraint created > for this special purpose. I don't think that's a good solution: Whilst it may work, it also adds significant and potentially unnecessary overhead to the execution of the CHECK constraint. The added complexity in the expression itself also increases the chance of a user defining the constraint incorrectly. Kind regards, Matthias van de Meent Databricks (https://www.databricks.com)
Re: Adding a stored generated column without long-lived locks
От:
Laurenz Albe <laurenz.albe@cybertec.at>
Дата:
On Fri, 2026-10-02 at 18:58 +0200, Matthias van de Meent wrote: > On Fri, 2 Oct 2026 at 09:30, Laurenz Albe wrote: > > > > You could simply require the constraint to be > > > > ROW(col)::record *= ROW(expression)::record > > > > That would also behave as desired for NULL values. > > > > True, it looks hacky, but as you said, it is a constraint created > > for this special purpose. > > I don't think that's a good solution: Whilst it may work, it also > adds significant and potentially unnecessary overhead to the execution > of the CHECK constraint. The added complexity in the expression > itself also increases the chance of a user defining the constraint > incorrectly. All of that is correct, but the constraint is not permanent, so you don't have to pay the slight overhead for the more complicated expression permanently. If the user defines the constraint wrongly, nothing bad can happen: ALTER TABLE will complain that there is no appropriate constraint. Probably annoying, but no damage done. Yours, Laurenz Albe
Re: Adding a stored generated column without long-lived locks
On Fri Oct 2, 2026 at 1:30 AM CEST, Alberto Piai wrote: > On Thu Sep 24, 2026 at 12:47 PM CEST, Laurenz Albe wrote: >> On Thu, 2026-09-24 at 00:19 +0200, Alberto Piai wrote: >>> I find Matthias' proposal of exposing a function to check image equality >>> very compelling for the purpose of this patch: besides fixing this >>> problem, it would also make the command usable for data types which >>> don't define = (json), as well as those which don't (can't?) define >>> equalimage()... jsonb, numeric but also tsvector and PostGIS geometry. >> >> True, "tsvector" is limiting; I can see people wanting that for >> generated columns. I propose to move forward with pg_datum_image_equal() as the contract for the check constraint. It is simpler for the user. We can always reconsider the ROW()::record indirection in case the datum image equality patch cannot be committed for some reason. So here's v12, rebased on top of master + Matthias' pg_datum_image_equal() patch from [0]. It changes the implementation to require the new constraint shape, and updates all the documentation, tests and error messages. Besides that, I made a few more changes since v11: - bail if the column is part of a FK with on delete/update actions: adding the column directly in CREATE TABLE and ALTER TABLE ADD COLUMN also rejects that. - clear atthasmissing and attmissingval for consistency with CREATE TABLE: a column that was GENERATED since the beginning can't have those set, so let's be consistent. - remove support for foreign tables: I don't see the point of supporting this, since adding a stored generated column on a foreign table does not involve a rewrite nor a scan. The actual data migration would have to be done on the remote anyway. - fix wrong type for a pg_depend.refobjsubid lookup. - release AccessShareLock after scanning pg_depend: it's inconsequential since the target rel is already under AccessExclusiveLock, so no concurrent DDL involving it would happen. But it makes the function more self contained. - fix detection of trivial constraint col1=col2 (two Vars, but in swapped order). - add a tsvector test, also for dump/restore. - a few minor fixes, such as an incorrect use of errmsg instead of errmsg_internal and an incorrect comment. Looking forward to your thoughts on this! Regards, Alberto [0] https://postgr.es/m/CAEze2WhW41mVDMKRcpLaj_NMLVp4jtQLZjtG3M8RXNNbhZmCcw@mail.gmail.com -- Alberto Piai Sensational AG Zürich, Switzerland
Re: Adding a stored generated column without long-lived locks
От:
Xiaoxuan Li <xiaoxuan.li.dev@gmail.com>
Дата:
Hi Alberto,
v12 (on e405a46c45b, Linux/aarch64, gcc 11, cassert) builds cleanly
and passes the regression tests, but this new change loses data:
> - clear atthasmissing and attmissingval for consistency with CREATE
> TABLE: a column that was GENERATED since the beginning can't have
> those set, so let's be consistent.
A column added with a constant default has no stored value in the rows
that existed before; they read attmissingval. The constraint is
validated against those values, and then the command removes them:
CREATE TABLE fd (a int);
INSERT INTO fd SELECT g FROM generate_series(1, 5) g;
ALTER TABLE fd ADD COLUMN c int DEFAULT 5;
INSERT INTO fd (a) VALUES (6);
ALTER TABLE fd ADD CONSTRAINT fd_ck
CHECK (pg_datum_image_equal(c, 5));
ALTER TABLE fd ALTER COLUMN c
ADD GENERATED USING CONSTRAINT fd_ck STORED;
SELECT a, c FROM fd ORDER BY a;
a | c
---+---
1 |
2 |
3 |
4 |
5 |
6 | 5
(Same with DEFAULT 0 and an expression such as a * 0.) Afterwards
fd_ck is still convalidated, VACUUM FULL keeps the NULLs, and
"UPDATE fd SET a = a WHERE a = 1" fails with a violation of fd_ck.
ATExecAlterColumnType() and ATExecSetExpression() also clear the
missing value, but only together with a table rewrite. There is none
here. v11 left both fields alone and returns 5 for every row above;
removing the two repl_repl[] assignments from v12 does the same, and
VACUUM FULL or SET EXPRESSION later resets atthasmissing as usual.
A test with ALTER TABLE ... ADD COLUMN ... DEFAULT would be good.
I have only looked at this part of the patch. I'll set the entry to
Waiting on Author.
--
Xiaoxuan Li
Amazon Web Services
v12 (on e405a46c45b, Linux/aarch64, gcc 11, cassert) builds cleanly
and passes the regression tests, but this new change loses data:
> - clear atthasmissing and attmissingval for consistency with CREATE
> TABLE: a column that was GENERATED since the beginning can't have
> those set, so let's be consistent.
A column added with a constant default has no stored value in the rows
that existed before; they read attmissingval. The constraint is
validated against those values, and then the command removes them:
CREATE TABLE fd (a int);
INSERT INTO fd SELECT g FROM generate_series(1, 5) g;
ALTER TABLE fd ADD COLUMN c int DEFAULT 5;
INSERT INTO fd (a) VALUES (6);
ALTER TABLE fd ADD CONSTRAINT fd_ck
CHECK (pg_datum_image_equal(c, 5));
ALTER TABLE fd ALTER COLUMN c
ADD GENERATED USING CONSTRAINT fd_ck STORED;
SELECT a, c FROM fd ORDER BY a;
a | c
---+---
1 |
2 |
3 |
4 |
5 |
6 | 5
(Same with DEFAULT 0 and an expression such as a * 0.) Afterwards
fd_ck is still convalidated, VACUUM FULL keeps the NULLs, and
"UPDATE fd SET a = a WHERE a = 1" fails with a violation of fd_ck.
ATExecAlterColumnType() and ATExecSetExpression() also clear the
missing value, but only together with a table rewrite. There is none
here. v11 left both fields alone and returns 5 for every row above;
removing the two repl_repl[] assignments from v12 does the same, and
VACUUM FULL or SET EXPRESSION later resets atthasmissing as usual.
A test with ALTER TABLE ... ADD COLUMN ... DEFAULT would be good.
I have only looked at this part of the patch. I'll set the entry to
Waiting on Author.
--
Xiaoxuan Li
Amazon Web Services
On Fri, Nov 6, 2026 at 4:36 AM Alberto Piai <alberto.piai@gmail.com> wrote:
On Fri Oct 2, 2026 at 1:30 AM CEST, Alberto Piai wrote:
> On Thu Sep 24, 2026 at 12:47 PM CEST, Laurenz Albe wrote:
>> On Thu, 2026-09-24 at 00:19 +0200, Alberto Piai wrote:
>>> I find Matthias' proposal of exposing a function to check image equality
>>> very compelling for the purpose of this patch: besides fixing this
>>> problem, it would also make the command usable for data types which
>>> don't define = (json), as well as those which don't (can't?) define
>>> equalimage()... jsonb, numeric but also tsvector and PostGIS geometry.
>>
>> True, "tsvector" is limiting; I can see people wanting that for
>> generated columns.
I propose to move forward with pg_datum_image_equal() as the contract
for the check constraint. It is simpler for the user. We can always
reconsider the ROW()::record indirection in case the datum image
equality patch cannot be committed for some reason.
So here's v12, rebased on top of master + Matthias'
pg_datum_image_equal() patch from [0]. It changes the implementation to
require the new constraint shape, and updates all the documentation,
tests and error messages.
Besides that, I made a few more changes since v11:
- bail if the column is part of a FK with on delete/update actions:
adding the column directly in CREATE TABLE and ALTER TABLE ADD COLUMN
also rejects that.
- clear atthasmissing and attmissingval for consistency with CREATE
TABLE: a column that was GENERATED since the beginning can't have
those set, so let's be consistent.
- remove support for foreign tables: I don't see the point of supporting
this, since adding a stored generated column on a foreign table does
not involve a rewrite nor a scan. The actual data migration would have
to be done on the remote anyway.
- fix wrong type for a pg_depend.refobjsubid lookup.
- release AccessShareLock after scanning pg_depend: it's inconsequential
since the target rel is already under AccessExclusiveLock, so no
concurrent DDL involving it would happen. But it makes the function
more self contained.
- fix detection of trivial constraint col1=col2 (two Vars, but in
swapped order).
- add a tsvector test, also for dump/restore.
- a few minor fixes, such as an incorrect use of errmsg instead of
errmsg_internal and an incorrect comment.
Looking forward to your thoughts on this!
Regards,
Alberto
[0] https://postgr.es/m/CAEze2WhW41mVDMKRcpLaj_NMLVp4jtQLZjtG3M8RXNNbhZmCcw@mail.gmail.com
--
Alberto Piai
Sensational AG
Zürich, Switzerland
Re: Adding a stored generated column without long-lived locks
От:
"Alberto Piai" <alberto.piai@gmail.com>
Дата:
Hi Xiaoxuan, thank you for having a look at the patch! On Fri Nov 13, 2026 at 9:06 PM CET, Xiaoxuan Li wrote: > Hi Alberto, > > v12 (on e405a46c45b, Linux/aarch64, gcc 11, cassert) builds cleanly > and passes the regression tests, but this new change loses data: > >> - clear atthasmissing and attmissingval for consistency with CREATE >> TABLE: a column that was GENERATED since the beginning can't have >> those set, so let's be consistent. > > A column added with a constant default has no stored value in the rows > that existed before; they read attmissingval. The constraint is > validated against those values, and then the command removes them: Oops, nice catch, and what an embarassing thinko on my side. The property I'd like to establish here is that a stored generated column added with this command should be indistinguishable from one that was defined with CREATE TABLE or ALTER TABLE ... ADD COLUMN. So when I noticed the different atthasmissing/attmissingval, I thought I'd just drop those. Your test case shows an even bigger problem: in the presence of a previous default value, the CHECK constraint is not sufficient to prove that the column was completely backfilled with the correct data. My first thought now would be to have the command bail if the column has atthasmissing/attmissingval, and document that it must be added without a DEFAULT value. The (not so small, but not terrible and maybe unavoidable) downside is that this can't be detected early, so a user who's doing this migration and oversees the note in the docs will only notice at the very end, and will have to start from scratch and do the work of backfilling the data again. Or alternatively, I give up on trying to preserve such a property. A column which was added with a default value and freshly migrated with this command will have atthasmissing/attmissingval. Since the constraint has been validated aginst the missingval, we are sure that if/when the table is eventually rewritten (for example with REPACK), the correct value will be stored (and atthasmissing/attmissingval will be cleared). This might allow saving some work in the backfilling phase if most rows would end up with the default value anyway. WDYT? (I am inclined to go for the latter, but I want to spend some more time thinking about this.) Regards, Alberto -- Alberto Piai Sensational AG Zürich, Switzerland
Re: Adding a stored generated column without long-lived locks
Hi all,
On Sat Nov 14, 2026 at 4:50 PM CET, Alberto Piai wrote:
> The property I'd like to establish here is that a stored generated
> column added with this command should be indistinguishable from one that
> was defined with CREATE TABLE or ALTER TABLE ... ADD COLUMN.
>
> So when I noticed the different atthasmissing/attmissingval, I thought
> I'd just drop those.
>
> Your test case shows an even bigger problem: in the presence of a
> previous default value, the CHECK constraint is not sufficient to prove
> that the column was completely backfilled with the correct data.
Thanks again Xiaoxuan for testing and catching this.
One of the reasons I went with this design for my proposal was that I
was trying very hard to avoid creating a new state in which a column
could be. The intention was to make it possible to add a new stored
generated column without rewrites-under-lock, and without having to
reason about new states ("column is being backfilled"; "column is
half-virtual half-stored";) which would have existed in alternative
implementations I considered.
Now as you point out: the presence of atthasmissing/attmissingval _is_ a
new state. After the migration, we'd have a column which has
attgenerated='s' *and* atthasmissing/attmissingval.
That is not possible to ever reach nowadays by adding a new stored
generated column via CREATE TABLE or ALTER TABLE ... ADD COLUMN.
I prefer to avoid introducing the extra state, because I cannot be
reasonably sure that it is handled correctly everywhere.
I have verified, for example, that pg_dump --binary-upgrade emits a call
to binary_upgrade_set_missing_value() even if the column is generated.
So the new state (generated *and* atthasmissing) would be preserved
across a binary upgrade.
But that is just one aspect of it, there might be many cases I did not
think about. I prefer to be conservative about this, unless someone else
with more knowledge about postgres internals than me can show that this
would indeed be safe.
So here's v13, which:
- bails if the column has atthasmissing, because in that case we can't
be sure the values have been physically stored in each row:
ERROR: cannot convert column "b" to generated
DETAIL: Cannot ensure that column "b" of relation "t" has been completely backfilled.
HINT: Drop the column and create it again without a DEFAULT value.
- documents in alter_table.sgml that the column must be initially
defined without a DEFAULT value:
Note: the column column_name must be defined without a DEFAULT value
I am aware that this is not entirely accurate: the column could be
defined with a DEFAULT value, but if it's empty at that point then it
would never gain atthasmissing. Or it could be rewritten with REPACK or
another command which would clear the attributes on rewrite. But given
the use case for this command, this seemed good enough to me.
It is also not ideal that a user who oversees the "Note:" in the
documentation could do the whole work of backfilling the column, only to
find out at the very end of the migration that they used a DEFAULT
value. But this really cannot be detected earlier.
Happy to hear your thoughts about this,
Alberto
--
Alberto Piai
Sensational AG
Zürich, Switzerland
Re: Adding a stored generated column without long-lived locks
От:
Zsolt Parragi <zsolt.parragi@percona.com>
Дата:
Hello! I started testing this patchset (with some LLM help), and identified some issues: 1. The generation expression can change when it is reparsed based on session GUCs CREATE TABLE g (a float8, b float8); INSERT INTO g VALUES (1, 1 + '3.141592653589793'::float8); ALTER TABLE g ADD CONSTRAINT c CHECK (pg_datum_image_equal(b, a + '3.141592653589793'::float8)); SET extra_float_digits = 0; ALTER TABLE g ALTER b ADD GENERATED USING CONSTRAINT c STORED; RESET extra_float_digits; \d g b | double precision | generated always as (a + '3.14159265358979'::double precision) stored UPDATE g SET a = a; -- ERROR: new row for relation "g" violates check constraint "c" -- DETAIL: Failing row contains (1, 4.14159265358979). float4/timestamptz is also affected. 2. BEFORE triggers with WHEN on NEW.b survive the conversion CREATE TABLE t (a int, b int); INSERT INTO t VALUES (1, 2); ALTER TABLE t ADD CONSTRAINT c CHECK (pg_datum_image_equal(b, a*2)); CREATE TRIGGER w_null BEFORE INSERT OR UPDATE ON t FOR EACH ROW WHEN (NEW.b IS NULL) EXECUTE FUNCTION trg(); CREATE TRIGGER w_100 BEFORE INSERT OR UPDATE ON t FOR EACH ROW WHEN (NEW.b = 100) EXECUTE FUNCTION trg(); ALTER TABLE t ALTER b ADD GENERATED USING CONSTRAINT c STORED; -- succeeds INSERT INTO t (a) VALUES (50); -- fires w_null, not w_100, stored b = 100 -- pg_dump | psql: -- ERROR: BEFORE trigger's WHEN condition cannot reference NEW generated columns CREATE TRIGGER refuses this combination (trigger.c, "BEFORE trigger's WHEN condition cannot reference NEW generated columns"), because the generated value isn't computed yet when WHEN runs. Note that this is partially preexisting, the whole-row variant (WHEN (NEW IS DISTINCT FROM OLD)) is already reachable on master with ADD COLUMN ... GENERATED, but the NEW.b one is new. 3. Multiple inheritance CREATE TABLE p1 (a int, b int); CREATE TABLE p2 (a int, b int); CREATE TABLE c () INHERITS (p1, p2); ALTER TABLE p1 ADD CONSTRAINT k CHECK (pg_datum_image_equal(b, a*2)); INSERT INTO c VALUES (1, 2); ALTER TABLE p1 ALTER b ADD GENERATED USING CONSTRAINT k STORED; -- succeeds ALTER TABLE p1 DROP CONSTRAINT k; UPDATE p2 SET b = 999; SELECT a, b FROM c; -- 1 | 999 (expression gives 2) -- pg_dump | psql: -- ERROR: inherited column "b" has a generation conflict -- ERROR: relation "public.c" does not exist c.b becomes generated while p2.b stays a regular column. This seems to come from DROP EXPRESSION: it has the same problem in the other direction on master (drop the expression on one of two generated parents), which probably deserves a separate fix. 4. Typed tables are converted although CREATE TABLE OF refuses generated columns CREATE TYPE tt AS (a int, b int); CREATE TABLE s6 OF tt; INSERT INTO s6 VALUES (1, 2); ALTER TABLE s6 ADD CONSTRAINT c CHECK (pg_datum_image_equal(b, a + 1)); ALTER TABLE s6 ALTER b ADD GENERATED USING CONSTRAINT c STORED; -- succeeds -- pg_dump | psql: -- ERROR: generated columns are not supported on typed tables -- ERROR: relation "public.s6" does not exist 5. FK check also rejects the referenced side CREATE TABLE pk (a int, b int UNIQUE); CREATE TABLE fk (x int REFERENCES pk(b) ON UPDATE CASCADE); ALTER TABLE pk ADD CONSTRAINT k CHECK (pg_datum_image_equal(b, a*2)); ALTER TABLE pk ALTER b ADD GENERATED USING CONSTRAINT k STORED; -- ERROR: cannot convert column "b" to generated -- DETAIL: Column "b" is part of a foreign key with an ON DELETE / ON UPDATE action. Master only restricts the actions when the referencing columns are generated, a generated UNIQUE column can be referenced with ON UPDATE CASCADE. The detail is also a bit misleading, ON DELETE CASCADE is accepted.