pg.ddx.io  pgsql-committers@postgresql.org mailing list archive  
help / color / mirror / Atom feed
pgsql: Don't trust NOT NULL on virtual generated columns of partitioned
24+ messages / 6 participants
[nested] [flat]

* pgsql: Don't trust NOT NULL on virtual generated columns of partitioned
@ 2026-10-10 00:23 Richard Guo <rguo@postgresql.org>
  2026-10-13 12:42 ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  0 siblings, 1 reply; 24+ messages in thread

From: Richard Guo @ 2026-10-10 00:23 UTC (permalink / raw)
  To: pgsql-committers@lists.postgresql.org

Don't trust NOT NULL on virtual generated columns of partitioned tables

Commit 383eb21eb taught the planner to convert a NOT IN sublink to an
anti-join when the sub-select's outputs are provably non-nullable.
Since the sub-select has not been through any planner processing at
that point, a reference to a virtual generated column is still a plain
Var, and query_outputs_are_not_nullable() relied on the column's NOT
NULL constraint to prove it non-nullable.

That is not safe for a partitioned table.  A partition can have a
generation expression different from its parent's, and it enforces the
NOT NULL constraint against its own expression, whereas a query on the
parent computes the column using the parent's expression.  So the
column can be NULL when read through the parent despite the
constraint, and the anti-join would then produce wrong results, as it
returns rows that NOT IN should have rejected.

To fix, make var_is_nonnullable() ignore the NOT NULL constraint on a
virtual generated column of a partitioned table when consulting the
catalogs.  The other sources of NOT NULL information are only used
after virtual generated columns have been expanded, so they are not
affected.

Author: Shihao Zhong <zhong950419@gmail.com>
Reviewed-by: Richard Guo <guofenglinux@gmail.com>
Discussion: https://postgr.es/m/CAGRkXqR7VXacmRP41UBaM5u4aseeCH5ECVmQgn_YS=L7=xdhTw@mail.gmail.com
Backpatch-through: 19

Branch
------
master

Details
-------
https://git.postgresql.org/pg/commitdiff/d8444163d22e576c9f284a55eab7999ba67c4ceb

Modified Files
--------------
src/backend/optimizer/util/clauses.c            | 12 ++++++++++++
src/test/regress/expected/generated_virtual.out | 21 +++++++++++++++++++++
src/test/regress/sql/generated_virtual.sql      | 10 ++++++++++
3 files changed, 43 insertions(+)



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

* Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned
  2026-10-10 00:23 pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Richard Guo <rguo@postgresql.org>
@ 2026-10-13 12:42 ` Álvaro Herrera <alvherre@kurilemu.de>
  2026-10-13 14:34   ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Richard Guo <guofenglinux@gmail.com>
  0 siblings, 1 reply; 24+ messages in thread

From: Álvaro Herrera @ 2026-10-13 12:42 UTC (permalink / raw)
  To: Richard Guo <rguo@postgresql.org>; +Cc: pgsql-hackers@lists.postgresql.org

On 2026-Oct-10, Richard Guo wrote:

> Don't trust NOT NULL on virtual generated columns of partitioned tables
[...]
> That is not safe for a partitioned table.  A partition can have a
> generation expression different from its parent's, and it enforces the
> NOT NULL constraint against its own expression, whereas a query on the
> parent computes the column using the parent's expression.  So the
> column can be NULL when read through the parent despite the
> constraint, and the anti-join would then produce wrong results, as it
> returns rows that NOT IN should have rejected.

I find this very surprising.  Are we sure that it makes sense for a
partition to have a generating expression that differs from the one in
the parent table?

Copying from the test case you added,

 CREATE TABLE gtestnn_parent2 (a int NOT NULL, b int GENERATED ALWAYS AS (nullif(a, 0)) VIRTUAL NOT NULL) PARTITION BY LIST (a);
 CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 (b GENERATED ALWAYS AS (a + 1) VIRTUAL) FOR VALUES IN (0);
 INSERT INTO gtestnn_parent2 VALUES (0);

we read a NULL value from a column that's marked as not-null, which
shouldn't happen.

alvherre=# select * from gtestnn_parent2 ;
 a |   b    
---+--------
 0 | (null)
(1 row)

alvherre=# \d gtestnn_parent2 
                  Partitioned table "public.gtestnn_parent2"
 Column |  Type   | Collation | Nullable |              Default               
--------+---------+-----------+----------+------------------------------------
 a      | integer |           | not null | 
 b      | integer |           | not null | generated always as (NULLIF(a, 0))
Partition key: LIST (a)
Number of partitions: 1 (Use \d+ to list them.)

The row is of course different if I read it directly from the partition.

alvherre=# select * from gtestnn_child2 ;
 a | b 
---+---
 0 | 1
(1 row)


I didn't try but I imagine that allowing partitions to have a different
generating expression than the parent can break all kinds of constraint,
not just not-null ones, if generating expressions are "broken" enough.
Maybe we should disallow expressions to be different, and force users to
use STORED virtual columns if they want to do that.  This seems
dangerous.

Alternatively, you could argue that at read time the row should get its
virtual column values using the expressions from the children rather
than for the parent.

-- 
Álvaro Herrera        Breisgau, Deutschland  —  https://www.EnterpriseDB.com/
"Las navajas y los monos deben estar siempre distantes"   (Germán Poo)





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

* Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned
  2026-10-10 00:23 pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Richard Guo <rguo@postgresql.org>
  2026-10-13 12:42 ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
@ 2026-10-13 14:34   ` Richard Guo <guofenglinux@gmail.com>
  2026-10-13 15:41     ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-10-13 15:45     ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  0 siblings, 2 replies; 24+ messages in thread

From: Richard Guo @ 2026-10-13 14:34 UTC (permalink / raw)
  To: Álvaro Herrera <alvherre@kurilemu.de>; +Cc: Richard Guo <rguo@postgresql.org>; pgsql-hackers@lists.postgresql.org

On Tue, Oct 13, 2026 at 9:43 PM Álvaro Herrera <alvherre@kurilemu.de> wrote:
> I find this very surprising.  Are we sure that it makes sense for a
> partition to have a generating expression that differs from the one in
> the parent table?

No, I don't think it makes sense for a partition to have a different
virtual generation expression than its parent.  I raised this exact
same complaint in [1], the paragraph starting with "Regarding #4",
quoted below:

  Regarding #4, the fix is to not trust NOT NULL on a virtual generated
  column of a partitioned table.  But I don't like this fix at all.  I
  think the real problem is that a partition is allowed to have a
  different virtual generation expression than its parent.  The
  constraint is enforced with the partition's expression, while a query
  on the parent computes the column with the parent's expression.  So
  even on v18, a NOT NULL column can read as NULL through the parent,
  and the same goes for CHECK constraints.  That seems fragile to me,
  and I suspect it will bite us again.  CC'ing Peter here.

I'm not sure why virtual generated columns are designed this way, or
if this is required by the SQL standard.  But I can see it breaks a
lot of things, and what this commit does is just to work-around one of
the things that design breaks.

[1] https://postgr.es/m/CAMbWs4-dfVUXSu1fwfTd8HZypKsSN1uYjEPfMDb6bqB58Pas4g@mail.gmail.com

- Richard





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

* Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned
  2026-10-10 00:23 pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Richard Guo <rguo@postgresql.org>
  2026-10-13 12:42 ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-10-13 14:34   ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Richard Guo <guofenglinux@gmail.com>
@ 2026-10-13 15:41     ` shihao zhong <zhong950419@gmail.com>
  2026-10-13 16:00       ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  1 sibling, 1 reply; 24+ messages in thread

From: shihao zhong @ 2026-10-13 15:41 UTC (permalink / raw)
  To: Richard Guo <guofenglinux@gmail.com>; +Cc: Álvaro Herrera <alvherre@kurilemu.de>; Richard Guo <rguo@postgresql.org>; pgsql-hackers@lists.postgresql.org

Hi Alvaro and Richard,

Álvaro Herrera <alvherre@kurilemu.de> writes:
> we read a NULL value from a column that's marked as not-null, which
> shouldn't happen.

One data point, this part is not new in 19. Your example reads the
same NULL through the parent on 18.6. My initial idea is to just fix
the PG19 regression instead of addressing the entire problem.

> But I can see it breaks a
> lot of things, and what this commit does is just to work-around one of
> the things that design breaks.

Agree, I think there is a design question here and a more completed
fix should target 20.

Thanks,
Shihao

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

* Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned
  2026-10-10 00:23 pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Richard Guo <rguo@postgresql.org>
  2026-10-13 12:42 ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-10-13 14:34   ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Richard Guo <guofenglinux@gmail.com>
  2026-10-13 15:41     ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
@ 2026-10-13 16:00       ` Álvaro Herrera <alvherre@kurilemu.de>
  2026-10-14 04:39         ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  0 siblings, 1 reply; 24+ messages in thread

From: Álvaro Herrera @ 2026-10-13 16:00 UTC (permalink / raw)
  To: shihao zhong <zhong950419@gmail.com>; +Cc: Richard Guo <guofenglinux@gmail.com>; Richard Guo <rguo@postgresql.org>; pgsql-hackers@lists.postgresql.org

Hi,

On 2026-Oct-13, shihao zhong wrote:

> Álvaro Herrera <alvherre@kurilemu.de> writes:
> > we read a NULL value from a column that's marked as not-null, which
> > shouldn't happen.
> 
> One data point, this part is not new in 19. Your example reads the
> same NULL through the parent on 18.6.

Right -- I was running the reproducer in 18 as well.

> My initial idea is to just fix the PG19 regression instead of
> addressing the entire problem.

Yes, Richard committed this fix already -- I was replying to his commit
message of your fix.
https://postgr.es/m/flat/E1xFKs5-0000000116b-2Cge%40gemulon.postgresql.org

> > But I can see it breaks a lot of things, and what this commit does
> > is just to work-around one of the things that design breaks.
> 
> Agree, I think there is a design question here and a more completed
> fix should target 20.

This is where I disagree ... IMO this is serious problem whose fix
should be back-patched.  I suspect we don't really know what other
things this misfeature can break.

-- 
Álvaro Herrera        Breisgau, Deutschland  —  https://www.EnterpriseDB.com/
"Hay quien adquiere la mala costumbre de ser infeliz" (M. A. Evans)






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

* Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned
  2026-10-10 00:23 pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Richard Guo <rguo@postgresql.org>
  2026-10-13 12:42 ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-10-13 14:34   ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Richard Guo <guofenglinux@gmail.com>
  2026-10-13 15:41     ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-10-13 16:00       ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
@ 2026-10-14 04:39         ` shihao zhong <zhong950419@gmail.com>
  2026-10-26 17:40           ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Manu <manuelreyesbravo@gmail.com>
  0 siblings, 1 reply; 24+ messages in thread

From: shihao zhong @ 2026-10-14 04:39 UTC (permalink / raw)
  To: Álvaro Herrera <alvherre@kurilemu.de>; +Cc: Richard Guo <guofenglinux@gmail.com>; Richard Guo <rguo@postgresql.org>; pgsql-hackers@lists.postgresql.org

Hi Álvaro,

> This is where I disagree ... IMO this is serious problem whose fix
> should be back-patched.

Fair enough, I agree. Here is a patch for master and 19, and a version
for 18.

With the patch, a virtual generated column of a partition must use the
same expression as the parent. CREATE TABLE PARTITION OF and ATTACH
PARTITION check this, and SET EXPRESSION can only change the whole
partition tree. Stored columns and plain inheritance are unchanged.

On why it works this way today. Before 8bf6ec3ba3a, a child had to use
the parent's expression. That commit relaxed the rule when stored
columns were the only kind, and for them it is fine. Virtual columns
kept the relaxed rule, but they are computed with the expression of the
table named in the query, so the old rule fits them better.

>  provide SQL scripts that users can run to find and
> remove those that already exist there.

For existing databases, the attached query lists the partition columns
that differ, and pg_upgrade on master and 19 runs the same check. Users
can fix them with SET EXPRESSION on the parent, unless existing rows
break NOT NULL under the parent's expression.

For 18 there is one cost. A dump of a database that already has such
partitions will fail to attach them when restored into a patched 18.
So the release notes would need to ask users to run the query first.

Thanks,
Shihao

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

  nocfbot-find-mismatched-virtual-exprs.sql (application/octet-stream, 1.0K) download

v1-0001-Require-partitions-to-use-the-parent-s-virtual-ge.patch (application/octet-stream, 28.9K) download From 59e0b8f2da67326e4b734c178ff66ee8a56b4646 Mon Sep 17 00:00:00 2001 From: shihao zhong <zhong950419@gmail.com> Date: Tue, 13 Oct 2026 23:22:52 -0400 Subject: [PATCH v1] Require partitions to use the parent's virtual generation expression MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A query on a partitioned table computes a virtual generated column with the parent's expression, but constraints on a partition are checked with the partition's own. So a NOT NULL column could read as NULL through the parent. Reject a partition whose expression differs, and make pg_upgrade check for existing ones. Suggested-by: Álvaro Herrera <alvherre@kurilemu.de> Discussion: https://postgr.es/m/E1xFKs5-0000000116b-2Cge@gemulon.postgresql.org --- doc/src/sgml/ddl.sgml | 4 +- doc/src/sgml/ref/alter_table.sgml | 3 + src/backend/commands/tablecmds.c | 113 +++++++++++++++++- src/bin/pg_upgrade/check.c | 70 +++++++++++ .../regress/expected/generated_virtual.out | 110 +++++++---------- src/test/regress/sql/generated_virtual.sql | 44 +++---- 6 files changed, 253 insertions(+), 91 deletions(-) diff --git a/doc/src/sgml/ddl.sgml b/doc/src/sgml/ddl.sgml index d78d986756e..ae416531732 100644 --- a/doc/src/sgml/ddl.sgml +++ b/doc/src/sgml/ddl.sgml @@ -452,7 +452,9 @@ CREATE TABLE people ( <para> If a parent column is a generated column, its child column must also be a generated column of the same kind (stored or virtual); however, - the child column can have a different generation expression. + the child column can have a different generation expression, except + that a virtual generated column of a partition must have the same + generation expression as the partitioned table. </para> <para> diff --git a/doc/src/sgml/ref/alter_table.sgml b/doc/src/sgml/ref/alter_table.sgml index 0f9d698d170..d4156cc4253 100644 --- a/doc/src/sgml/ref/alter_table.sgml +++ b/doc/src/sgml/ref/alter_table.sgml @@ -276,6 +276,9 @@ WITH ( MODULUS <replaceable class="parameter">numeric_literal</replaceable>, REM Replacing the expression of a virtual generated column does not require a table rewrite, but if the column is used in a constraint, the table will be scanned to check that existing rows meet the constraint. + The expression of a virtual generated column cannot be changed for a + partition alone, or with <literal>ONLY</literal> for a partitioned table + that has partitions. </para> <para> diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 93ad49e59fd..a27fdfd1ddd 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -380,6 +380,7 @@ static List *MergeCheckConstraint(List *constraints, const char *name, Node *exp static void MergeChildAttribute(List *inh_columns, int exist_attno, int newcol_attno, const ColumnDef *newdef); static ColumnDef *MergeInheritedAttribute(List *inh_columns, int exist_attno, const ColumnDef *newdef); static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispartition); +static void CheckPartitionVirtualGeneratedExprs(Relation partrel, Relation parentrel); static void MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel); static void StoreCatalogInheritance(Oid relationId, List *supers, bool child_is_partition); @@ -539,6 +540,7 @@ static ObjectAddress ATExecDropIdentity(Relation rel, const char *colName, bool bool recurse, bool recursing); static ObjectAddress ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName, Node *newExpr, LOCKMODE lockmode); +static void ATPrepSetExpression(Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing); static void ATPrepDropExpression(Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode); static ObjectAddress ATExecDropExpression(Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode); static ObjectAddress ATExecSetStatistics(Relation rel, const char *colName, int16 colNum, @@ -1161,6 +1163,8 @@ DefineRelation(CreateStmt *stmt, char relkind, Oid ownerId, errmsg("\"%s\" is not partitioned", RelationGetRelationName(parent)))); + CheckPartitionVirtualGeneratedExprs(rel, parent); + /* * The partition constraint of the default partition depends on the * partition bounds of every other partition. It is possible that @@ -3096,7 +3100,8 @@ MergeAttributes(List *columns, const List *supers, char relpersistence, * * Same rules as above: generated-ness has to match the * parent, but the contents of the generation expression - * can be different. + * can be different, except for virtual generated columns + * (see CheckPartitionVirtualGeneratedExprs). */ if (coldef->generated) { @@ -5086,6 +5091,7 @@ ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd, case AT_SetExpression: /* ALTER COLUMN SET EXPRESSION */ ATSimplePermissions(cmd->subtype, rel, ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE); + ATPrepSetExpression(rel, cmd, recurse, recursing); ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context); pass = AT_PASS_SET_EXPRESSION; break; @@ -8836,6 +8842,45 @@ ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName, return address; } +/* + * ALTER TABLE ALTER COLUMN SET EXPRESSION + * + * The expression of a virtual generated column can only be changed for a + * whole partition tree. See CheckPartitionVirtualGeneratedExprs. + */ +static void +ATPrepSetExpression(Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing) +{ + HeapTuple tuple; + char attgenerated; + + if (recursing) + return; + + tuple = SearchSysCacheAttName(RelationGetRelid(rel), cmd->name); + if (!HeapTupleIsValid(tuple)) + return; /* error will be reported later */ + attgenerated = ((Form_pg_attribute) GETSTRUCT(tuple))->attgenerated; + ReleaseSysCache(tuple); + + if (attgenerated != ATTRIBUTE_GENERATED_VIRTUAL) + return; + + if (rel->rd_rel->relispartition) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("cannot alter generation expression of virtual generated column \"%s\" of partition \"%s\"", + cmd->name, RelationGetRelationName(rel)), + errhint("Alter the generation expression of the partitioned table instead."))); + + if (!recurse && + rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE && + find_inheritance_children(RelationGetRelid(rel), NoLock) != NIL) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("ALTER TABLE / SET EXPRESSION must be applied to child tables too"))); +} + /* * ALTER TABLE ALTER COLUMN DROP EXPRESSION */ @@ -18175,7 +18220,9 @@ constraints_equivalent(HeapTuple a, HeapTuple b, TupleDesc tupleDesc) * partitioned tables it's a foot-gun. * * The data type must match exactly. If the parent column is NOT NULL then - * the child must be as well. Defaults are not compared, however. + * the child must be as well. Defaults are not compared, however, and neither + * are generation expressions, except for virtual generated columns of a + * partition. */ static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispartition) @@ -18296,6 +18343,68 @@ MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispart } table_close(attrrel, RowExclusiveLock); + + if (ispartition) + CheckPartitionVirtualGeneratedExprs(child_rel, parent_rel); +} + +/* + * CheckPartitionVirtualGeneratedExprs + * Check that each virtual generated column of a partition has the same + * generation expression as in the partitioned table. + * + * Reading through the partitioned table computes the parent's expression, + * while constraints on the partition are checked with its own, so they must + * be the same. + */ +static void +CheckPartitionVirtualGeneratedExprs(Relation partrel, Relation parentrel) +{ + TupleDesc parent_desc = RelationGetDescr(parentrel); + TupleDesc part_desc = RelationGetDescr(partrel); + AttrMap *attmap; + + if (parent_desc->constr == NULL || + !parent_desc->constr->has_generated_virtual) + return; + + attmap = build_attrmap_by_name(part_desc, parent_desc, false); + + for (AttrNumber parent_attno = 1; parent_attno <= parent_desc->natts; parent_attno++) + { + Form_pg_attribute parent_att = TupleDescAttr(parent_desc, parent_attno - 1); + AttrNumber part_attno; + Node *parent_expr; + Node *part_expr; + bool found_whole_row; + + if (parent_att->attisdropped || + parent_att->attgenerated != ATTRIBUTE_GENERATED_VIRTUAL) + continue; + + part_attno = attmap->attnums[parent_attno - 1]; + Assert(part_attno > 0); + + parent_expr = TupleDescGetDefault(parent_desc, parent_attno); + part_expr = TupleDescGetDefault(part_desc, part_attno); + if (parent_expr == NULL || part_expr == NULL) + elog(ERROR, "missing generation expression for column \"%s\"", + NameStr(parent_att->attname)); + + parent_expr = map_variable_attnos(parent_expr, 1, 0, attmap, + InvalidOid, &found_whole_row); + /* generation expressions cannot contain whole-row Vars */ + Assert(!found_whole_row); + + if (!equal(parent_expr, part_expr)) + ereport(ERROR, + (errcode(ERRCODE_INVALID_COLUMN_DEFINITION), + errmsg("virtual generated column \"%s\" of partition \"%s\" must have the same generation expression as the partitioned table", + NameStr(parent_att->attname), + RelationGetRelationName(partrel)))); + } + + free_attrmap(attmap); } /* diff --git a/src/bin/pg_upgrade/check.c b/src/bin/pg_upgrade/check.c index 150c4fc34b9..3c5c3fa4878 100644 --- a/src/bin/pg_upgrade/check.c +++ b/src/bin/pg_upgrade/check.c @@ -29,6 +29,7 @@ static void check_for_user_defined_postfix_ops(ClusterInfo *cluster); static void check_for_incompatible_polymorphics(ClusterInfo *cluster); static void check_for_tables_with_oids(ClusterInfo *cluster); static void check_for_not_null_inheritance(ClusterInfo *cluster); +static void check_for_partition_virtual_generated_exprs(ClusterInfo *cluster); static void check_for_gist_inet_ops(ClusterInfo *cluster); static void check_for_new_tablespace_dir(void); static void check_for_user_defined_encoding_conversions(ClusterInfo *cluster); @@ -673,6 +674,15 @@ check_and_dump_old_cluster(void) if (GET_MAJOR_VERSION(old_cluster.major_version) <= 1800) check_for_not_null_inheritance(&old_cluster); + /* + * Virtual generated columns (new in PG 18) of a partition used to be + * allowed to have a different generation expression than the partitioned + * table, but schema restore fails for them now. Verify there are none. + */ + if (GET_MAJOR_VERSION(old_cluster.major_version) >= 1800 && + GET_MAJOR_VERSION(old_cluster.major_version) <= 1900) + check_for_partition_virtual_generated_exprs(&old_cluster); + /* * The btree_gist extension contains gist_inet_ops and gist_cidr_ops * opclasses that do not reliably give correct answers. We want to @@ -1738,6 +1748,66 @@ check_for_not_null_inheritance(ClusterInfo *cluster) check_ok(); } +/* + * check_for_partition_virtual_generated_exprs() + * + * A virtual generated column of a partition must have the same generation + * expression as the partitioned table. Check that the cluster to be upgraded + * has no partitions that differ, which older versions allowed. + */ +static void +check_for_partition_virtual_generated_exprs(ClusterInfo *cluster) +{ + UpgradeTaskReport report; + UpgradeTask *task; + const char *query; + + prep_status("Checking for virtual generated column inconsistencies"); + + report.file = NULL; + snprintf(report.path, sizeof(report.path), "%s/%s", + log_opts.basedir, + "partition_virtual_generated_columns.txt"); + + query = "SELECT nc.nspname, cc.relname, ac.attname " + "FROM pg_catalog.pg_class cc " + " JOIN pg_catalog.pg_namespace nc ON nc.oid = cc.relnamespace " + " JOIN pg_catalog.pg_inherits i ON i.inhrelid = cc.oid " + " JOIN pg_catalog.pg_attribute ac ON ac.attrelid = cc.oid " + " JOIN pg_catalog.pg_attribute ap ON ap.attrelid = i.inhparent " + " AND ap.attname = ac.attname " + " JOIN pg_catalog.pg_attrdef dc ON dc.adrelid = ac.attrelid " + " AND dc.adnum = ac.attnum " + " JOIN pg_catalog.pg_attrdef dp ON dp.adrelid = ap.attrelid " + " AND dp.adnum = ap.attnum " + "WHERE cc.relispartition AND ac.attgenerated = 'v' " + " AND pg_catalog.pg_get_expr(dc.adbin, dc.adrelid) <> " + " pg_catalog.pg_get_expr(dp.adbin, dp.adrelid)"; + + task = upgrade_task_create(); + /* the not-null check's callback reports the same columns */ + upgrade_task_add_step(task, query, + process_inconsistent_notnull, + true, &report); + upgrade_task_run(task, cluster); + upgrade_task_free(task); + + if (report.file) + { + fclose(report.file); + pg_log(PG_REPORT, "fatal"); + pg_fatal("Your installation contains partitions whose virtual generated columns\n" + "have a different generation expression than the partitioned table.\n" + "This is no longer allowed, so the upgrade would fail. You can fix\n" + "this by running\n" + " ALTER TABLE parent ALTER COLUMN column SET EXPRESSION AS (...);\n" + "on the partitioned table of each column listed in the file:\n" + " %s", report.path); + } + else + check_ok(); +} + /* * Callback function for processing results of query for * check_for_gist_inet_ops()'s UpgradeTask. If the query returned any rows diff --git a/src/test/regress/expected/generated_virtual.out b/src/test/regress/expected/generated_virtual.out index b2f8e16e63b..a021ad6d589 100644 --- a/src/test/regress/expected/generated_virtual.out +++ b/src/test/regress/expected/generated_virtual.out @@ -912,7 +912,11 @@ CREATE TABLE gtest_parent (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWA CREATE TABLE gtest_child PARTITION OF gtest_parent FOR VALUES FROM ('2016-07-01') TO ('2016-08-01'); -- inherits gen expr CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( - f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- overrides gen expr + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- error, must match parent +) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); +ERROR: virtual generated column "f3" of partition "gtest_child2" must have the same generation expression as the partitioned table +CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 2) VIRTUAL -- same as parent, ok ) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); CREATE TABLE gtest_child3 PARTITION OF gtest_parent ( f3 DEFAULT 42 -- error @@ -946,6 +950,11 @@ ERROR: column "f3" inherits from generated column of different kind DETAIL: Parent column is VIRTUAL, child column is STORED. DROP TABLE gtest_child3; CREATE TABLE gtest_child3 (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWAYS AS (f2 * 33) VIRTUAL); +ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); -- error +ERROR: virtual generated column "f3" of partition "gtest_child3" must have the same generation expression as the partitioned table +DROP TABLE gtest_child3; +-- different column order, so the parent's expression has to be mapped +CREATE TABLE gtest_child3 (f3 bigint GENERATED ALWAYS AS (f2 * 2) VIRTUAL, f2 bigint, f1 date NOT NULL); ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); \d gtest_child Table "generated_virtual_tests.gtest_child" @@ -957,21 +966,21 @@ ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09 Partition of: gtest_parent FOR VALUES FROM ('07-01-2016') TO ('08-01-2016') \d gtest_child2 - Table "generated_virtual_tests.gtest_child2" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- + Table "generated_virtual_tests.gtest_child2" + Column | Type | Collation | Nullable | Default +--------+--------+-----------+----------+------------------------------ f1 | date | | not null | f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 22) + f3 | bigint | | | generated always as (f2 * 2) Partition of: gtest_parent FOR VALUES FROM ('08-01-2016') TO ('09-01-2016') \d gtest_child3 - Table "generated_virtual_tests.gtest_child3" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | + Table "generated_virtual_tests.gtest_child3" + Column | Type | Collation | Nullable | Default +--------+--------+-----------+----------+------------------------------ + f3 | bigint | | | generated always as (f2 * 2) f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 33) + f1 | date | | not null | Partition of: gtest_parent FOR VALUES FROM ('09-01-2016') TO ('10-01-2016') INSERT INTO gtest_parent (f1, f2) VALUES ('2016-07-15', 1); @@ -992,14 +1001,14 @@ SELECT tableoid::regclass, * FROM gtest_child ORDER BY 1, 2, 3; gtest_child | 07-15-2016 | 2 | 4 (2 rows) -SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; -- uses child's generation expression, not parent's +SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; tableoid | f1 | f2 | f3 --------------+------------+----+---- - gtest_child2 | 08-15-2016 | 3 | 66 + gtest_child2 | 08-15-2016 | 3 | 6 (1 row) SELECT tableoid::regclass, * FROM gtest_child3 ORDER BY 1, 2, 3; - tableoid | f1 | f2 | f3 + tableoid | f3 | f2 | f1 ----------+----+----+---- (0 rows) @@ -1012,46 +1021,14 @@ SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; gtest_child3 | 09-13-2016 | 1 | 2 (3 rows) --- alter only parent's and one child's generation expression -ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -\d gtest_parent - Partitioned table "generated_virtual_tests.gtest_parent" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------ - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 4) -Partition key: RANGE (f1) -Number of partitions: 3 (Use \d+ to list them.) - -\d gtest_child - Table "generated_virtual_tests.gtest_child" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 10) -Partition of: gtest_parent FOR VALUES FROM ('07-01-2016') TO ('08-01-2016') - -\d gtest_child2 - Table "generated_virtual_tests.gtest_child2" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 22) -Partition of: gtest_parent FOR VALUES FROM ('08-01-2016') TO ('09-01-2016') - -\d gtest_child3 - Table "generated_virtual_tests.gtest_child3" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 33) -Partition of: gtest_parent FOR VALUES FROM ('09-01-2016') TO ('10-01-2016') - +-- cannot alter only parent's or one partition's generation expression +ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -- error +ERROR: ALTER TABLE / SET EXPRESSION must be applied to child tables too +ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -- error +ERROR: cannot alter generation expression of virtual generated column "f3" of partition "gtest_child" +HINT: Alter the generation expression of the partitioned table instead. +-- alter generation expression of parent and all its children altogether +ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; tableoid | f1 | f2 | f3 --------------+------------+----+---- @@ -1060,16 +1037,10 @@ SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; gtest_child3 | 09-13-2016 | 1 | 4 (3 rows) --- check constraint was validated based on each partitions's generation expression -ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 19); -- error -ERROR: check constraint "cc1" of relation "gtest_child" is violated by some row -ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 66); -- error +ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 12); -- error ERROR: check constraint "cc1" of relation "gtest_child2" is violated by some row -ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 <> 33); -- error -ERROR: check constraint "cc1" of relation "gtest_child3" is violated by some row -ALTER TABLE gtest_parent ADD CONSTRAINT cc CHECK (f3 < 67); -- ok +ALTER TABLE gtest_parent ADD CONSTRAINT cc CHECK (f3 < 13); -- ok ALTER TABLE gtest_parent DROP CONSTRAINT cc; --- alter generation expression of parent and all its children altogether ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 2); \d gtest_parent Partitioned table "generated_virtual_tests.gtest_parent" @@ -1103,9 +1074,9 @@ Partition of: gtest_parent FOR VALUES FROM ('08-01-2016') TO ('09-01-2016') Table "generated_virtual_tests.gtest_child3" Column | Type | Collation | Nullable | Default --------+--------+-----------+----------+------------------------------ - f1 | date | | not null | - f2 | bigint | | | f3 | bigint | | | generated always as (f2 * 2) + f2 | bigint | | | + f1 | date | | not null | Partition of: gtest_parent FOR VALUES FROM ('09-01-2016') TO ('10-01-2016') SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; @@ -1886,11 +1857,16 @@ select * from gtest_cursor order by id; commit; drop table gtest_cursor; --- NOT NULL on a partitioned table's virtual column does not prove non-nullness, --- because a partition can have a different generation expression +-- a partition cannot have a different generation expression, which would let +-- the partitioned table's NOT NULL virtual column read as NULL CREATE TABLE gtestnn_parent2 (a int NOT NULL, b int GENERATED ALWAYS AS (nullif(a, 0)) VIRTUAL NOT NULL) PARTITION BY LIST (a); -CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 (b GENERATED ALWAYS AS (a + 1) VIRTUAL) FOR VALUES IN (0); -INSERT INTO gtestnn_parent2 VALUES (0); +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 (b GENERATED ALWAYS AS (a + 1) VIRTUAL) FOR VALUES IN (0); -- error +ERROR: virtual generated column "b" of partition "gtestnn_child2" must have the same generation expression as the partitioned table +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 FOR VALUES IN (0, 1); +INSERT INTO gtestnn_parent2 VALUES (0); -- error +ERROR: null value in column "b" of relation "gtestnn_child2" violates not-null constraint +DETAIL: Failing row contains (0, virtual). +INSERT INTO gtestnn_parent2 VALUES (1); EXPLAIN (COSTS OFF) SELECT a FROM gtestnn_parent2 WHERE a NOT IN (SELECT b FROM gtestnn_parent2); QUERY PLAN diff --git a/src/test/regress/sql/generated_virtual.sql b/src/test/regress/sql/generated_virtual.sql index c4c4f3d5ef1..d36019b373a 100644 --- a/src/test/regress/sql/generated_virtual.sql +++ b/src/test/regress/sql/generated_virtual.sql @@ -529,7 +529,10 @@ CREATE TABLE gtest_parent (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWA CREATE TABLE gtest_child PARTITION OF gtest_parent FOR VALUES FROM ('2016-07-01') TO ('2016-08-01'); -- inherits gen expr CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( - f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- overrides gen expr + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- error, must match parent +) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); +CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 2) VIRTUAL -- same as parent, ok ) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); CREATE TABLE gtest_child3 PARTITION OF gtest_parent ( f3 DEFAULT 42 -- error @@ -553,6 +556,10 @@ CREATE TABLE gtest_child3 (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWA ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); -- error DROP TABLE gtest_child3; CREATE TABLE gtest_child3 (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWAYS AS (f2 * 33) VIRTUAL); +ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); -- error +DROP TABLE gtest_child3; +-- different column order, so the parent's expression has to be mapped +CREATE TABLE gtest_child3 (f3 bigint GENERATED ALWAYS AS (f2 * 2) VIRTUAL, f2 bigint, f1 date NOT NULL); ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); \d gtest_child \d gtest_child2 @@ -562,28 +569,21 @@ INSERT INTO gtest_parent (f1, f2) VALUES ('2016-07-15', 2); INSERT INTO gtest_parent (f1, f2) VALUES ('2016-08-15', 3); SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; SELECT tableoid::regclass, * FROM gtest_child ORDER BY 1, 2, 3; -SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; -- uses child's generation expression, not parent's +SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; SELECT tableoid::regclass, * FROM gtest_child3 ORDER BY 1, 2, 3; UPDATE gtest_parent SET f1 = f1 + 60 WHERE f2 = 1; SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; --- alter only parent's and one child's generation expression -ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -\d gtest_parent -\d gtest_child -\d gtest_child2 -\d gtest_child3 -SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; - --- check constraint was validated based on each partitions's generation expression -ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 19); -- error -ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 66); -- error -ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 <> 33); -- error -ALTER TABLE gtest_parent ADD CONSTRAINT cc CHECK (f3 < 67); -- ok -ALTER TABLE gtest_parent DROP CONSTRAINT cc; +-- cannot alter only parent's or one partition's generation expression +ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -- error +ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -- error -- alter generation expression of parent and all its children altogether +ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); +SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; +ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 12); -- error +ALTER TABLE gtest_parent ADD CONSTRAINT cc CHECK (f3 < 13); -- ok +ALTER TABLE gtest_parent DROP CONSTRAINT cc; ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 2); \d gtest_parent \d gtest_child @@ -1005,11 +1005,13 @@ commit; drop table gtest_cursor; --- NOT NULL on a partitioned table's virtual column does not prove non-nullness, --- because a partition can have a different generation expression +-- a partition cannot have a different generation expression, which would let +-- the partitioned table's NOT NULL virtual column read as NULL CREATE TABLE gtestnn_parent2 (a int NOT NULL, b int GENERATED ALWAYS AS (nullif(a, 0)) VIRTUAL NOT NULL) PARTITION BY LIST (a); -CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 (b GENERATED ALWAYS AS (a + 1) VIRTUAL) FOR VALUES IN (0); -INSERT INTO gtestnn_parent2 VALUES (0); +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 (b GENERATED ALWAYS AS (a + 1) VIRTUAL) FOR VALUES IN (0); -- error +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 FOR VALUES IN (0, 1); +INSERT INTO gtestnn_parent2 VALUES (0); -- error +INSERT INTO gtestnn_parent2 VALUES (1); EXPLAIN (COSTS OFF) SELECT a FROM gtestnn_parent2 WHERE a NOT IN (SELECT b FROM gtestnn_parent2); SELECT a FROM gtestnn_parent2 WHERE a NOT IN (SELECT b FROM gtestnn_parent2); -- 2.37.1 (Apple Git-137.1)
nocfbot-v1-REL_18-0001-Require-partitions-to-use-the-parent-s-virtual-gen.patch (application/octet-stream, 23.3K) download From 046485f55baddf964721de4a80636bad8c79d9cf Mon Sep 17 00:00:00 2001 From: shihao zhong <zhong950419@gmail.com> Date: Tue, 13 Oct 2026 23:22:52 -0400 Subject: [PATCH v1 REL_18] Require partitions to use the parent's virtual generation expression MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A query on a partitioned table computes a virtual generated column with the parent's expression, but constraints on a partition are checked with the partition's own. So a NOT NULL column could read as NULL through the parent. Reject a partition whose expression differs. Suggested-by: Álvaro Herrera <alvherre@kurilemu.de> Discussion: https://postgr.es/m/E1xFKs5-0000000116b-2Cge@gemulon.postgresql.org --- doc/src/sgml/ddl.sgml | 4 +- doc/src/sgml/ref/alter_table.sgml | 3 + src/backend/commands/tablecmds.c | 113 +++++++++++++++++- .../regress/expected/generated_virtual.out | 109 ++++++++--------- src/test/regress/sql/generated_virtual.sql | 37 ++++-- 5 files changed, 197 insertions(+), 69 deletions(-) diff --git a/doc/src/sgml/ddl.sgml b/doc/src/sgml/ddl.sgml index ddd7096f6b2..5c892706494 100644 --- a/doc/src/sgml/ddl.sgml +++ b/doc/src/sgml/ddl.sgml @@ -452,7 +452,9 @@ CREATE TABLE people ( <para> If a parent column is a generated column, its child column must also be a generated column of the same kind (stored or virtual); however, - the child column can have a different generation expression. + the child column can have a different generation expression, except + that a virtual generated column of a partition must have the same + generation expression as the partitioned table. </para> <para> diff --git a/doc/src/sgml/ref/alter_table.sgml b/doc/src/sgml/ref/alter_table.sgml index 31f2d91418b..d6a009a54a3 100644 --- a/doc/src/sgml/ref/alter_table.sgml +++ b/doc/src/sgml/ref/alter_table.sgml @@ -272,6 +272,9 @@ WITH ( MODULUS <replaceable class="parameter">numeric_literal</replaceable>, REM This form replaces the expression of a generated column. Existing data in a stored generated column is rewritten and all the future changes will apply the new generation expression. + The expression of a virtual generated column cannot be changed for a + partition alone, or with <literal>ONLY</literal> for a partitioned table + that has partitions. </para> <para> diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 5e8e247d9fe..7143655042f 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -378,6 +378,7 @@ static List *MergeCheckConstraint(List *constraints, const char *name, Node *exp static void MergeChildAttribute(List *inh_columns, int exist_attno, int newcol_attno, const ColumnDef *newdef); static ColumnDef *MergeInheritedAttribute(List *inh_columns, int exist_attno, const ColumnDef *newdef); static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispartition); +static void CheckPartitionVirtualGeneratedExprs(Relation partrel, Relation parentrel); static void MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel); static void StoreCatalogInheritance(Oid relationId, List *supers, bool child_is_partition); @@ -522,6 +523,7 @@ static ObjectAddress ATExecDropIdentity(Relation rel, const char *colName, bool bool recurse, bool recursing); static ObjectAddress ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName, Node *newExpr, LOCKMODE lockmode); +static void ATPrepSetExpression(Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing); static void ATPrepDropExpression(Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode); static ObjectAddress ATExecDropExpression(Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode); static ObjectAddress ATExecSetStatistics(Relation rel, const char *colName, int16 colNum, @@ -1142,6 +1144,8 @@ DefineRelation(CreateStmt *stmt, char relkind, Oid ownerId, errmsg("\"%s\" is not partitioned", RelationGetRelationName(parent)))); + CheckPartitionVirtualGeneratedExprs(rel, parent); + /* * The partition constraint of the default partition depends on the * partition bounds of every other partition. It is possible that @@ -3059,7 +3063,8 @@ MergeAttributes(List *columns, const List *supers, char relpersistence, * * Same rules as above: generated-ness has to match the * parent, but the contents of the generation expression - * can be different. + * can be different, except for virtual generated columns + * (see CheckPartitionVirtualGeneratedExprs). */ if (coldef->generated) { @@ -5036,6 +5041,7 @@ ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd, case AT_SetExpression: /* ALTER COLUMN SET EXPRESSION */ ATSimplePermissions(cmd->subtype, rel, ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE); + ATPrepSetExpression(rel, cmd, recurse, recursing); ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context); pass = AT_PASS_SET_EXPRESSION; break; @@ -8774,6 +8780,45 @@ ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName, return address; } +/* + * ALTER TABLE ALTER COLUMN SET EXPRESSION + * + * The expression of a virtual generated column can only be changed for a + * whole partition tree. See CheckPartitionVirtualGeneratedExprs. + */ +static void +ATPrepSetExpression(Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing) +{ + HeapTuple tuple; + char attgenerated; + + if (recursing) + return; + + tuple = SearchSysCacheAttName(RelationGetRelid(rel), cmd->name); + if (!HeapTupleIsValid(tuple)) + return; /* error will be reported later */ + attgenerated = ((Form_pg_attribute) GETSTRUCT(tuple))->attgenerated; + ReleaseSysCache(tuple); + + if (attgenerated != ATTRIBUTE_GENERATED_VIRTUAL) + return; + + if (rel->rd_rel->relispartition) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("cannot alter generation expression of virtual generated column \"%s\" of partition \"%s\"", + cmd->name, RelationGetRelationName(rel)), + errhint("Alter the generation expression of the partitioned table instead."))); + + if (!recurse && + rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE && + find_inheritance_children(RelationGetRelid(rel), NoLock) != NIL) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("ALTER TABLE / SET EXPRESSION must be applied to child tables too"))); +} + /* * ALTER TABLE ALTER COLUMN DROP EXPRESSION */ @@ -17551,7 +17596,9 @@ constraints_equivalent(HeapTuple a, HeapTuple b, TupleDesc tupleDesc) * partitioned tables it's a foot-gun. * * The data type must match exactly. If the parent column is NOT NULL then - * the child must be as well. Defaults are not compared, however. + * the child must be as well. Defaults are not compared, however, and neither + * are generation expressions, except for virtual generated columns of a + * partition. */ static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispartition) @@ -17672,6 +17719,68 @@ MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispart } table_close(attrrel, RowExclusiveLock); + + if (ispartition) + CheckPartitionVirtualGeneratedExprs(child_rel, parent_rel); +} + +/* + * CheckPartitionVirtualGeneratedExprs + * Check that each virtual generated column of a partition has the same + * generation expression as in the partitioned table. + * + * Reading through the partitioned table computes the parent's expression, + * while constraints on the partition are checked with its own, so they must + * be the same. + */ +static void +CheckPartitionVirtualGeneratedExprs(Relation partrel, Relation parentrel) +{ + TupleDesc parent_desc = RelationGetDescr(parentrel); + TupleDesc part_desc = RelationGetDescr(partrel); + AttrMap *attmap; + + if (parent_desc->constr == NULL || + !parent_desc->constr->has_generated_virtual) + return; + + attmap = build_attrmap_by_name(part_desc, parent_desc, false); + + for (AttrNumber parent_attno = 1; parent_attno <= parent_desc->natts; parent_attno++) + { + Form_pg_attribute parent_att = TupleDescAttr(parent_desc, parent_attno - 1); + AttrNumber part_attno; + Node *parent_expr; + Node *part_expr; + bool found_whole_row; + + if (parent_att->attisdropped || + parent_att->attgenerated != ATTRIBUTE_GENERATED_VIRTUAL) + continue; + + part_attno = attmap->attnums[parent_attno - 1]; + Assert(part_attno > 0); + + parent_expr = TupleDescGetDefault(parent_desc, parent_attno); + part_expr = TupleDescGetDefault(part_desc, part_attno); + if (parent_expr == NULL || part_expr == NULL) + elog(ERROR, "missing generation expression for column \"%s\"", + NameStr(parent_att->attname)); + + parent_expr = map_variable_attnos(parent_expr, 1, 0, attmap, + InvalidOid, &found_whole_row); + /* generation expressions cannot contain whole-row Vars */ + Assert(!found_whole_row); + + if (!equal(parent_expr, part_expr)) + ereport(ERROR, + (errcode(ERRCODE_INVALID_COLUMN_DEFINITION), + errmsg("virtual generated column \"%s\" of partition \"%s\" must have the same generation expression as the partitioned table", + NameStr(parent_att->attname), + RelationGetRelationName(partrel)))); + } + + free_attrmap(attmap); } /* diff --git a/src/test/regress/expected/generated_virtual.out b/src/test/regress/expected/generated_virtual.out index 03698488907..6108fce2ae4 100644 --- a/src/test/regress/expected/generated_virtual.out +++ b/src/test/regress/expected/generated_virtual.out @@ -882,7 +882,11 @@ CREATE TABLE gtest_parent (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWA CREATE TABLE gtest_child PARTITION OF gtest_parent FOR VALUES FROM ('2016-07-01') TO ('2016-08-01'); -- inherits gen expr CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( - f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- overrides gen expr + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- error, must match parent +) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); +ERROR: virtual generated column "f3" of partition "gtest_child2" must have the same generation expression as the partitioned table +CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 2) VIRTUAL -- same as parent, ok ) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); CREATE TABLE gtest_child3 PARTITION OF gtest_parent ( f3 DEFAULT 42 -- error @@ -916,6 +920,11 @@ ERROR: column "f3" inherits from generated column of different kind DETAIL: Parent column is VIRTUAL, child column is STORED. DROP TABLE gtest_child3; CREATE TABLE gtest_child3 (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWAYS AS (f2 * 33) VIRTUAL); +ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); -- error +ERROR: virtual generated column "f3" of partition "gtest_child3" must have the same generation expression as the partitioned table +DROP TABLE gtest_child3; +-- different column order, so the parent's expression has to be mapped +CREATE TABLE gtest_child3 (f3 bigint GENERATED ALWAYS AS (f2 * 2) VIRTUAL, f2 bigint, f1 date NOT NULL); ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); \d gtest_child Table "generated_virtual_tests.gtest_child" @@ -927,21 +936,21 @@ ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09 Partition of: gtest_parent FOR VALUES FROM ('07-01-2016') TO ('08-01-2016') \d gtest_child2 - Table "generated_virtual_tests.gtest_child2" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- + Table "generated_virtual_tests.gtest_child2" + Column | Type | Collation | Nullable | Default +--------+--------+-----------+----------+------------------------------ f1 | date | | not null | f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 22) + f3 | bigint | | | generated always as (f2 * 2) Partition of: gtest_parent FOR VALUES FROM ('08-01-2016') TO ('09-01-2016') \d gtest_child3 - Table "generated_virtual_tests.gtest_child3" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | + Table "generated_virtual_tests.gtest_child3" + Column | Type | Collation | Nullable | Default +--------+--------+-----------+----------+------------------------------ + f3 | bigint | | | generated always as (f2 * 2) f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 33) + f1 | date | | not null | Partition of: gtest_parent FOR VALUES FROM ('09-01-2016') TO ('10-01-2016') INSERT INTO gtest_parent (f1, f2) VALUES ('2016-07-15', 1); @@ -962,14 +971,14 @@ SELECT tableoid::regclass, * FROM gtest_child ORDER BY 1, 2, 3; gtest_child | 07-15-2016 | 2 | 4 (2 rows) -SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; -- uses child's generation expression, not parent's +SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; tableoid | f1 | f2 | f3 --------------+------------+----+---- - gtest_child2 | 08-15-2016 | 3 | 66 + gtest_child2 | 08-15-2016 | 3 | 6 (1 row) SELECT tableoid::regclass, * FROM gtest_child3 ORDER BY 1, 2, 3; - tableoid | f1 | f2 | f3 + tableoid | f3 | f2 | f1 ----------+----+----+---- (0 rows) @@ -982,46 +991,14 @@ SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; gtest_child3 | 09-13-2016 | 1 | 2 (3 rows) --- alter only parent's and one child's generation expression -ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -\d gtest_parent - Partitioned table "generated_virtual_tests.gtest_parent" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------ - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 4) -Partition key: RANGE (f1) -Number of partitions: 3 (Use \d+ to list them.) - -\d gtest_child - Table "generated_virtual_tests.gtest_child" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 10) -Partition of: gtest_parent FOR VALUES FROM ('07-01-2016') TO ('08-01-2016') - -\d gtest_child2 - Table "generated_virtual_tests.gtest_child2" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 22) -Partition of: gtest_parent FOR VALUES FROM ('08-01-2016') TO ('09-01-2016') - -\d gtest_child3 - Table "generated_virtual_tests.gtest_child3" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 33) -Partition of: gtest_parent FOR VALUES FROM ('09-01-2016') TO ('10-01-2016') - +-- cannot alter only parent's or one partition's generation expression +ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -- error +ERROR: ALTER TABLE / SET EXPRESSION must be applied to child tables too +ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -- error +ERROR: cannot alter generation expression of virtual generated column "f3" of partition "gtest_child" +HINT: Alter the generation expression of the partitioned table instead. +-- alter generation expression of parent and all its children altogether +ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; tableoid | f1 | f2 | f3 --------------+------------+----+---- @@ -1030,7 +1007,10 @@ SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; gtest_child3 | 09-13-2016 | 1 | 4 (3 rows) --- alter generation expression of parent and all its children altogether +ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 12); -- error +ERROR: check constraint "cc1" of relation "gtest_child2" is violated by some row +ALTER TABLE gtest_parent ADD CONSTRAINT cc CHECK (f3 < 13); -- ok +ALTER TABLE gtest_parent DROP CONSTRAINT cc; ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 2); \d gtest_parent Partitioned table "generated_virtual_tests.gtest_parent" @@ -1064,9 +1044,9 @@ Partition of: gtest_parent FOR VALUES FROM ('08-01-2016') TO ('09-01-2016') Table "generated_virtual_tests.gtest_child3" Column | Type | Collation | Nullable | Default --------+--------+-----------+----------+------------------------------ - f1 | date | | not null | - f2 | bigint | | | f3 | bigint | | | generated always as (f2 * 2) + f2 | bigint | | | + f1 | date | | not null | Partition of: gtest_parent FOR VALUES FROM ('09-01-2016') TO ('10-01-2016') SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; @@ -1812,3 +1792,20 @@ select * from gtest_cursor order by id; commit; drop table gtest_cursor; +-- a partition cannot have a different generation expression, which would let +-- the partitioned table's NOT NULL virtual column read as NULL +CREATE TABLE gtestnn_parent2 (a int NOT NULL, b int GENERATED ALWAYS AS (nullif(a, 0)) VIRTUAL NOT NULL) PARTITION BY LIST (a); +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 (b GENERATED ALWAYS AS (a + 1) VIRTUAL) FOR VALUES IN (0); -- error +ERROR: virtual generated column "b" of partition "gtestnn_child2" must have the same generation expression as the partitioned table +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 FOR VALUES IN (0, 1); +INSERT INTO gtestnn_parent2 VALUES (0); -- error +ERROR: null value in column "b" of relation "gtestnn_child2" violates not-null constraint +DETAIL: Failing row contains (0, virtual). +INSERT INTO gtestnn_parent2 VALUES (1); +SELECT a, b FROM gtestnn_parent2; + a | b +---+--- + 1 | 1 +(1 row) + +DROP TABLE gtestnn_parent2; diff --git a/src/test/regress/sql/generated_virtual.sql b/src/test/regress/sql/generated_virtual.sql index b1b92b2ced5..d1bbf9352d7 100644 --- a/src/test/regress/sql/generated_virtual.sql +++ b/src/test/regress/sql/generated_virtual.sql @@ -514,7 +514,10 @@ CREATE TABLE gtest_parent (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWA CREATE TABLE gtest_child PARTITION OF gtest_parent FOR VALUES FROM ('2016-07-01') TO ('2016-08-01'); -- inherits gen expr CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( - f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- overrides gen expr + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- error, must match parent +) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); +CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 2) VIRTUAL -- same as parent, ok ) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); CREATE TABLE gtest_child3 PARTITION OF gtest_parent ( f3 DEFAULT 42 -- error @@ -538,6 +541,10 @@ CREATE TABLE gtest_child3 (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWA ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); -- error DROP TABLE gtest_child3; CREATE TABLE gtest_child3 (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWAYS AS (f2 * 33) VIRTUAL); +ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); -- error +DROP TABLE gtest_child3; +-- different column order, so the parent's expression has to be mapped +CREATE TABLE gtest_child3 (f3 bigint GENERATED ALWAYS AS (f2 * 2) VIRTUAL, f2 bigint, f1 date NOT NULL); ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); \d gtest_child \d gtest_child2 @@ -547,21 +554,21 @@ INSERT INTO gtest_parent (f1, f2) VALUES ('2016-07-15', 2); INSERT INTO gtest_parent (f1, f2) VALUES ('2016-08-15', 3); SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; SELECT tableoid::regclass, * FROM gtest_child ORDER BY 1, 2, 3; -SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; -- uses child's generation expression, not parent's +SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; SELECT tableoid::regclass, * FROM gtest_child3 ORDER BY 1, 2, 3; UPDATE gtest_parent SET f1 = f1 + 60 WHERE f2 = 1; SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; --- alter only parent's and one child's generation expression -ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -\d gtest_parent -\d gtest_child -\d gtest_child2 -\d gtest_child3 -SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; +-- cannot alter only parent's or one partition's generation expression +ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -- error +ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -- error -- alter generation expression of parent and all its children altogether +ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); +SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; +ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 12); -- error +ALTER TABLE gtest_parent ADD CONSTRAINT cc CHECK (f3 < 13); -- ok +ALTER TABLE gtest_parent DROP CONSTRAINT cc; ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 2); \d gtest_parent \d gtest_child @@ -969,3 +976,13 @@ select * from gtest_cursor order by id; commit; drop table gtest_cursor; + +-- a partition cannot have a different generation expression, which would let +-- the partitioned table's NOT NULL virtual column read as NULL +CREATE TABLE gtestnn_parent2 (a int NOT NULL, b int GENERATED ALWAYS AS (nullif(a, 0)) VIRTUAL NOT NULL) PARTITION BY LIST (a); +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 (b GENERATED ALWAYS AS (a + 1) VIRTUAL) FOR VALUES IN (0); -- error +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 FOR VALUES IN (0, 1); +INSERT INTO gtestnn_parent2 VALUES (0); -- error +INSERT INTO gtestnn_parent2 VALUES (1); +SELECT a, b FROM gtestnn_parent2; +DROP TABLE gtestnn_parent2; -- 2.37.1 (Apple Git-137.1)
^ permalink raw reply [nested|flat] 24+ messages in thread

* Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned
  2026-10-10 00:23 pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Richard Guo <rguo@postgresql.org>
  2026-10-13 12:42 ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-10-13 14:34   ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Richard Guo <guofenglinux@gmail.com>
  2026-10-13 15:41     ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-10-13 16:00       ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-10-14 04:39         ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
@ 2026-10-26 17:40           ` Manu <manuelreyesbravo@gmail.com>
  2026-10-27 03:10             ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  0 siblings, 1 reply; 24+ messages in thread

From: Manu @ 2026-10-26 17:40 UTC (permalink / raw)
  To: shihao zhong <zhong950419@gmail.com>; +Cc: Álvaro Herrera <alvherre@kurilemu.de>; Richard Guo <guofenglinux@gmail.com>; Richard Guo <rguo@postgresql.org>; pgsql-hackers@lists.postgresql.org

Hi Shihao,

On Tue, Oct 13, 2026 at 6:00 PM Álvaro Herrera <alvherre@kurilemu.de>
wrote:
> I suspect we don't really know what other
> things this misfeature can break.

One more: with constraint_exclusion = on (not the default), a query
on the parent returns wrong results, on 18.6 too:

  create table p (a int,
    v int generated always as (nullif(a, 0)) virtual not null)
    partition by list (a);
  create table p1 partition of p
    (v generated always as (a + 1) virtual) for values in (0);
  insert into p values (0);
  set constraint_exclusion = on;
  select count(*) from p where v is null; -- 0, should be 1

The plan is "One-Time Filter: false": the parent's NOT NULL refutes
the qual, but the row read through p has v = NULL. A CHECK (v > 0)
on the parent does the same: count(*) where v < 0 gives 0, not 1.
Both on 18.6, 19beta4, 19rc1 and master (dfd7ede529f), so
d8444163d22 does not change it; with the default setting all give 1.
repro-ce-on.sql.txt is attached.

On Wed, Oct 14, 2026 at 12:39 AM shihao zhong <zhong950419@gmail.com>
wrote:
> With the patch, a virtual generated column of a partition must use the
> same expression as the parent. CREATE TABLE PARTITION OF and ATTACH
> PARTITION check this, and SET EXPRESSION can only change the whole
> partition tree. Stored columns and plain inheritance are unchanged.

I ran v1 on master and REL_19_STABLE, and the 18 version on
REL_18_STABLE, against 13 statements that create a divergent
expression: PARTITION OF (LIST, RANGE, HASH, DEFAULT), ATTACH, SET
EXPRESSION on a partition or on ONLY the parent, four multi-level
cases and two foreign-table partitions (paths.sql.txt). All 13 fail
on the three branches. The controls with the parent's expression,
STORED and INHERITS still work. Your query finds 7 mismatches
unpatched and 0 patched. make check passes on the three, and the
pg_upgrade TAP tests on master. Without the ATTACH check, 3 of the
13 get through, so the script catches that. On REL_19_STABLE v1
needs "git am -3" (check_for_pg_role_prefix is still in check.c).

> For existing databases, the attached query lists the partition columns
> that differ, and pg_upgrade on master and 19 runs the same check. Users
> can fix them with SET EXPRESSION on the parent, unless existing rows
> break NOT NULL under the parent's expression.

pg_upgrade --check from an 18.6 cluster to master and to 19 (both
patched) lists all four divergent columns I created. On patched 18
the existing ones keep the wrong result above until they are fixed.

One case where the fix fails on 18: SET EXPRESSION on a virtual
column errors out if the table has any CHECK constraint, even one
that does not involve the column, and also after the rows are fixed:

  ERROR:  ALTER TABLE / SET EXPRESSION is not supported for virtual
  generated columns in tables with check constraints

f80bedd52b1 lifted this in 19; 18 still has it. So the pg_upgrade
hint fails for such tables in an 18 cluster. What worked on patched
18, in one transaction: drop the CHECK, SET EXPRESSION on the parent,
add the CHECK back. After that your query is empty and pg_upgrade
--check passes (legacy.sh.txt).

All of this is on one machine, cassert builds; 17 and older not run,
no check-world. Details are in measurements.txt.

Regards,
Manu

Attachments:

repro-ce-on.sql.txt (text/plain, 1.5K) download -- Wrong result with constraint_exclusion = on (not the default) when a -- partition has its own VIRTUAL generation expression. The partition -- enforces NOT NULL / CHECK with its own expression, a read through the -- parent computes the parent's, and constraint exclusion trusts the -- parent's constraints. The correct answer is 1 for each count. -- Run with: psql -X -f repro-ce-on.sql.txt -- With the v1 patch, the two CREATE TABLE ... PARTITION OF fail. \pset null '(null)' select current_setting('server_version') as server_version; create table p (a int, v int generated always as (nullif(a, 0)) virtual not null) partition by list (a); create table p1 partition of p (v generated always as (a + 1) virtual) for values in (0); insert into p values (0); create table c (a int, v int generated always as (-a) virtual check (v > 0)) partition by list (a); create table c1 partition of c (v generated always as (a) virtual) for values in (5); insert into c values (5); select a, v from p; -- v reads NULL through p set constraint_exclusion = partition; -- the default select count(*) as p_null from p where v is null; -- 1 select count(*) as c_neg from c where v < 0; -- 1 set constraint_exclusion = on; select count(*) as p_null from p where v is null; -- 0, should be 1 select count(*) as c_neg from c where v < 0; -- 0, should be 1 explain (costs off) select count(*) from p where v is null; reset constraint_exclusion;
paths.sql.txt (text/plain, 5.4K) download -- Every DDL path that can give a partition a VIRTUAL generation expression -- different from its parent's, each with a control that uses the parent's -- expression and must keep working. Run with ON_ERROR_STOP off; the -- expected outcome is in the comment of each statement: -- [div] divergent: accepted on unpatched builds, should fail with the patch -- [same] same expression: should succeed on every build -- [keep] outside the patch's scope: should behave as before -- At the end, the find-mismatches query lists what got through. \pset null '(null)' select current_setting('server_version') as server_version; -- P1. CREATE TABLE ... PARTITION OF, LIST create table l (a int, v int generated always as (a * 2) virtual) partition by list (a); create table l1 partition of l (v generated always as (a * 3) virtual) for values in (1); -- [div] create table l2 partition of l (v generated always as (a * 2) virtual) for values in (2); -- [same] create table l3 partition of l for values in (3); -- [same] -- P2. RANGE and HASH create table r (a int, v int generated always as (a * 2) virtual) partition by range (a); create table r1 partition of r (v generated always as (a * 3) virtual) for values from (0) to (10); -- [div] create table h (a int, v int generated always as (a * 2) virtual) partition by hash (a); create table h1 partition of h (v generated always as (a * 3) virtual) for values with (modulus 2, remainder 0); -- [div] -- P3. ATTACH PARTITION, also with a different column order create table l4 (a int, v int generated always as (a * 3) virtual); alter table l attach partition l4 for values in (4); -- [div] create table l5 (v int generated always as (a * 2) virtual, a int); alter table l attach partition l5 for values in (5); -- [same] -- P4. DEFAULT partition create table l6 partition of l (v generated always as (a * 3) virtual) default; -- [div] -- P5. SET EXPRESSION alter table l2 alter column v set expression as (a * 5); -- [div] alter table only l alter column v set expression as (a * 5); -- [div] alter table l alter column v set expression as (a * 7); -- [same] select c.relname, pg_get_expr(d.adbin, d.adrelid) as expr from pg_class c join pg_attrdef d on d.adrelid = c.oid where c.oid = 'l'::regclass or c.oid in (select inhrelid from pg_inherits where inhparent = 'l'::regclass) order by 1; -- P6. Multi-level: a partitioned partition create table m (a int, b int, v int generated always as (a * 2) virtual) partition by list (a); create table m1 partition of m (v generated always as (a * 3) virtual) for values in (1) partition by list (b); -- [div] create table m2 partition of m for values in (2) partition by list (b); -- [same] create table m2a partition of m2 (v generated always as (a * 3) virtual) for values in (1); -- [div] create table m2b partition of m2 for values in (2); -- [same] alter table m2 alter column v set expression as (a * 9); -- [div] -- a standalone partitioned table whose own leaf matches it, attached -- to a parent with a different expression create table m3 (a int, b int, v int generated always as (a * 3) virtual) partition by list (b); create table m3a partition of m3 for values in (1); -- [same] alter table m attach partition m3 for values in (3); -- [div] -- P7. Foreign table as a partition (no handler needed for DDL) create foreign data wrapper vgd_fdw; create server vgd_srv foreign data wrapper vgd_fdw; create foreign table f1 partition of l (v generated always as (a * 3) virtual) for values in (7) server vgd_srv; -- [div] create foreign table f2 (a int, v int generated always as (a * 3) virtual) server vgd_srv; alter table l attach partition f2 for values in (8); -- [div] -- P8. Unchanged by design: STORED and plain inheritance create table s (a int, v int generated always as (a * 2) stored) partition by list (a); create table s1 partition of s (v generated always as (a * 3) stored) for values in (1); -- [keep] create table i (a int, v int generated always as (a * 2) virtual); create table i1 (a int, v int generated always as (a * 3) virtual) inherits (i); -- [keep] alter table i1 alter column v set expression as (a * 4); -- [keep] -- What got through: the patch's own find-mismatches query select c.oid::pg_catalog.regclass as partition, i.inhparent::pg_catalog.regclass as parent, a.attname as column, pg_catalog.pg_get_expr(dc.adbin, dc.adrelid) as partition_expr, pg_catalog.pg_get_expr(dp.adbin, dp.adrelid) as parent_expr from pg_catalog.pg_class c join pg_catalog.pg_inherits i on i.inhrelid = c.oid join pg_catalog.pg_attribute a on a.attrelid = c.oid join pg_catalog.pg_attribute pa on pa.attrelid = i.inhparent and pa.attname = a.attname join pg_catalog.pg_attrdef dc on dc.adrelid = a.attrelid and dc.adnum = a.attnum join pg_catalog.pg_attrdef dp on dp.adrelid = pa.attrelid and dp.adnum = pa.attnum where c.relispartition and a.attgenerated = 'v' and pg_catalog.pg_get_expr(dc.adbin, dc.adrelid) <> pg_catalog.pg_get_expr(dp.adbin, dp.adrelid) order by 1, 3;
legacy.sh.txt (text/plain, 6.9K) download #!/usr/bin/env bash # Divergent partitions that already exist when the patch arrives. # Usage: bash legacy.sh.txt OLD18=<bindir> NEW18=<bindir> [UP_LABEL=<bindir> ...] # OLD18 unpatched 18.x: creates the divergent partitions # NEW18 18.x with the REL_18 patch: same data directory, minor update # UP_* newer major versions with the patch: pg_upgrade --check targets # Output goes to stdout; every cluster lives in a temp dir removed at exit. set -uo pipefail old=${1#*=}; new18=${2#*=}; shift 2 tmp=$(mktemp -d "${TMPDIR:-/tmp}/vgdl.XXXXXX") trap 'for d in "$tmp"/*/; do [ -f "$d/postmaster.pid" ] && \ "$new18/pg_ctl" -D "$d" -m immediate -w stop >/dev/null 2>&1; done; rm -rf "$tmp"' EXIT port=${PORT_BASE:-61600} cat >"$tmp/legacy.sql" <<'EOF' -- Divergent partitions created on an unpatched server (the state that -- already exists in deployed databases). create table p (a int, v int generated always as (nullif(a, 0)) virtual not null) partition by list (a); create table p1 partition of p (v generated always as (a + 1) virtual) for values in (0); insert into p values (0); create table c (a int, v int generated always as (-a) virtual check (v > 0)) partition by list (a); create table c1 partition of c (v generated always as (a) virtual) for values in (5); insert into c values (5); -- divergent, but no constraint is violated through the parent create table b (a int, v int generated always as (a * 2) virtual) partition by list (a); create table b1 partition of b (v generated always as (a * 3) virtual) for values in (1); insert into b values (1); -- divergent, with a CHECK constraint that does not involve v create table k (a int check (a > 0), v int generated always as (a * 2) virtual) partition by list (a); create table k1 partition of k (v generated always as (a * 3) virtual) for values in (1); insert into k values (1); EOF cat >"$tmp/legacy-check.sql" <<'EOF' \pset null '(null)' select current_setting('server_version') as server_version; -- mismatches as the patch's query reports them select c.oid::pg_catalog.regclass as partition, a.attname as column, pg_catalog.pg_get_expr(dc.adbin, dc.adrelid) as partition_expr, pg_catalog.pg_get_expr(dp.adbin, dp.adrelid) as parent_expr from pg_catalog.pg_class c join pg_catalog.pg_inherits i on i.inhrelid = c.oid join pg_catalog.pg_attribute a on a.attrelid = c.oid join pg_catalog.pg_attribute pa on pa.attrelid = i.inhparent and pa.attname = a.attname join pg_catalog.pg_attrdef dc on dc.adrelid = a.attrelid and dc.adnum = a.attnum join pg_catalog.pg_attrdef dp on dp.adrelid = pa.attrelid and dp.adnum = pa.attnum where c.relispartition and a.attgenerated = 'v' and pg_catalog.pg_get_expr(dc.adbin, dc.adrelid) <> pg_catalog.pg_get_expr(dp.adbin, dp.adrelid) order by 1, 2; -- the wrong result: correct answer is 1 for both set constraint_exclusion = partition; select 'ce=partition' as setting, (select count(*) from p where v is null) as p_null, (select count(*) from c where v < 0) as c_neg; set constraint_exclusion = on; select 'ce=on' as setting, (select count(*) from p where v is null) as p_null, (select count(*) from c where v < 0) as c_neg; reset constraint_exclusion; EOF start() { "$1/pg_ctl" -D "$2" -l "$2.log" -w \ -o "-p $port -k $tmp -c listen_addresses=''" start >/dev/null; } stop() { "$1/pg_ctl" -D "$2" -m fast -w stop >/dev/null; } sql() { local bin=$1 db=$2; shift 2 "$bin/psql" -X -h "$tmp" -p "$port" -U postgres -d "$db" "$@" 2>&1; } say() { printf '\n### %s\n' "$*"; } say "1. unpatched $("$old/postgres" --version): create divergent partitions" "$old/initdb" -D "$tmp/old" -U postgres -A trust >/dev/null start "$old" "$tmp/old" "$old/createdb" -h "$tmp" -p "$port" -U postgres legacy sql "$old" legacy -q -f "$tmp/legacy.sql" sql "$old" legacy -f "$tmp/legacy-check.sql" say "2. pg_dump of the unpatched server: how the partitions are emitted" "$old/pg_dump" -h "$tmp" -p "$port" -U postgres legacy >"$tmp/dump-old.sql" grep -nE 'CREATE TABLE|ATTACH PARTITION|GENERATED ALWAYS' "$tmp/dump-old.sql" \ | sed 's/^/ /' stop "$old" "$tmp/old" for spec in "$@"; do label=${spec%%=*}; bin=${spec#*=} say "3. pg_upgrade --check, old cluster as created in 1 -> $label" "$bin/initdb" -D "$tmp/new-$label" -U postgres -A trust >/dev/null ( cd "$tmp" && "$bin/pg_upgrade" --check -U postgres -b "$old" -B "$bin" \ -d "$tmp/old" -D "$tmp/new-$label" -p $((port + 1)) -P $((port + 2)) \ -s "$tmp" ) 2>&1 | grep -vE '^\s*$' | sed 's/^/ /' f=$(find "$tmp/new-$label" -name partition_virtual_generated_columns.txt | head -1) [ -n "$f" ] && { echo " report file:"; sed 's/^/ /' "$f"; } done say "4. same data directory started with $("$new18/postgres" --version) + patch" start "$new18" "$tmp/old" sql "$new18" legacy -f "$tmp/legacy-check.sql" say "5. restore the unpatched dump (2) into the patched server" "$new18/createdb" -h "$tmp" -p "$port" -U postgres restored_old sql "$new18" restored_old -q -f "$tmp/dump-old.sql" | grep -E 'ERROR|DETAIL' \ | sed 's/^/ /' sql "$new18" restored_old -f "$tmp/legacy-check.sql" say "6. dump with the patched pg_dump, restore into the patched server" "$new18/pg_dump" -h "$tmp" -p "$port" -U postgres legacy >"$tmp/dump-new.sql" "$new18/createdb" -h "$tmp" -p "$port" -U postgres restored_new sql "$new18" restored_new -q -f "$tmp/dump-new.sql" | grep -E 'ERROR|DETAIL' \ | sed 's/^/ /' say "7. remedy suggested by the patch: SET EXPRESSION on the parent" for t in "b:(a * 2)" "p:(nullif(a, 0))" "c:(-a)" "k:(a * 2)"; do echo " $t" sql "$new18" legacy -c "alter table ${t%%:*} alter column v set expression as ${t#*:}" \ | sed 's/^/ /' done say "7b. after deleting the rows that violate the parent's constraints" sql "$new18" legacy -c 'delete from p1' -c 'delete from c1' | sed 's/^/ /' for t in "p:(nullif(a, 0))" "c:(-a)"; do echo " $t" sql "$new18" legacy -c "alter table ${t%%:*} alter column v set expression as ${t#*:}" \ | sed 's/^/ /' done say "7c. drop the CHECK, SET EXPRESSION, add the CHECK back" sql "$new18" legacy -c 'begin' \ -c 'alter table c drop constraint c_v_check' \ -c 'alter table c alter column v set expression as (-a)' \ -c 'alter table c add constraint c_v_check check (v > 0)' \ -c 'alter table k drop constraint k_a_check' \ -c 'alter table k alter column v set expression as (a * 2)' \ -c 'alter table k add constraint k_a_check check (a > 0)' \ -c 'commit' | sed 's/^/ /' sql "$new18" legacy -f "$tmp/legacy-check.sql" stop "$new18" "$tmp/old" for spec in "$@"; do label=${spec%%=*}; bin=${spec#*=} say "8. pg_upgrade --check after 7c -> $label" rm -rf "$tmp/new-$label" "$bin/initdb" -D "$tmp/new-$label" -U postgres -A trust >/dev/null ( cd "$tmp" && "$bin/pg_upgrade" --check -U postgres -b "$new18" -B "$bin" \ -d "$tmp/old" -D "$tmp/new-$label" -p $((port + 1)) -P $((port + 2)) \ -s "$tmp" ) 2>&1 | grep -iE 'virtual|clusters are compatible|fatal' \ | sed 's/^/ /' done
measurements.txt (text/plain, 5.3K) download Partition with its own VIRTUAL generation expression: wrong result with constraint_exclusion = on, and shihao's v1 against every DDL path ========================================================================= Correctness only, no timings. One machine (x86_64, Linux), gcc, --enable-cassert --enable-debug, CFLAGS=-O2. 17 and older not run (no virtual generated columns before 18). Builds 18.6 REL_18_6 release 19beta4 REL_19_BETA4 (before d8444163d22) 19rc1 REL_19_RC1 (contains d8444163d22) master dfd7ede529f (2026-10-25) m-v1 master + v1-0001 (applies cleanly) 19-v1 REL_19_STABLE 2b491ff1cd2 + v1-0001; plain "git am" fails on the src/bin/pg_upgrade/check.c prototype context (check_for_pg_role_prefix is still there in 19); "git am -3" applies it without conflicts 18-v1 REL_18_STABLE 1735ad557d3 + nocfbot-v1-REL_18-0001 mutant m-v1 with the CheckPartitionVirtualGeneratedExprs() call in MergeAttributesIntoExisting() removed (ATTACH unchecked) 1. repro-ce-on.sql.txt (correct answer: 1 in every cell) ------------------------------------------------------- 18.6 19beta4 19rc1 master NOT NULL: count(*) WHERE v IS NULL constraint_exclusion=partition 1 1 1 1 constraint_exclusion=on 0 0 0 0 CHECK (v > 0): count(*) WHERE v < 0 constraint_exclusion=partition 1 1 1 1 constraint_exclusion=on 0 0 0 0 Plan with "on": Result, One-Time Filter: false, on all four. m-v1, 19-v1, 18-v1: both CREATE TABLE ... PARTITION OF are rejected, so the case cannot be built. 2. paths.sql.txt: DDL paths that create a divergent expression -------------------------------------------------------------- A = accepted, R = rejected 18.6/master m-v1/19-v1/18-v1 P1 CREATE TABLE ... PARTITION OF, LIST A R P2 same, RANGE and HASH A R P3 ATTACH PARTITION A R P4 DEFAULT partition A R P5 SET EXPRESSION on a partition A R SET EXPRESSION on ONLY parent A R P6 partitioned partition, own expression A R leaf under it, own expression A R SET EXPRESSION on the middle level A R ATTACH of a partitioned table (its leaf matches it, it differs from the parent) A R P7 CREATE FOREIGN TABLE ... PARTITION OF A R ATTACH of a foreign table A R 13 divergent statements: 13 errors on each patched build, the same 13 statements, and 0 on 18.6/master. Every control with the parent's expression is accepted on all builds: CREATE ... PARTITION OF with the same or no expression, ATTACH with a different column order, recursive SET EXPRESSION on the parent, a leaf under a partitioned partition. P8 (STORED partitions, INHERITS children, SET EXPRESSION on an INHERITS child) is accepted on all builds. Final query (the one from nocfbot-find-mismatched-virtual-exprs.sql): 7 rows on 18.6/master, 0 rows on each patched build. mutant: the 3 ATTACH statements are accepted again (10 errors), and the final query lists the 2 that survive to the end (m3, f2). 3. legacy.sh.txt: divergent partitions that already exist --------------------------------------------------------- Created on 18.6: p1 (NOT NULL broken through the parent), c1 (CHECK on v broken), b1 (no constraint), k1 (CHECK (a > 0), not on v). 1 18.6: the query lists 4; constraint_exclusion=on gives 0 and 0. 3 pg_upgrade --check 18.6 -> m-v1 and -> 19-v1: fatal, the report file lists the 4 columns, on both. 4 same data directory started with 18-v1: the query lists 4; constraint_exclusion=on still gives 0 and 0 (the patch prevents new ones; existing ones stay until fixed). 5 18.6 pg_dump restored into 18-v1: each of the 4 ATTACH PARTITION fails, as the v1 mail says. 7 ALTER TABLE <parent> ALTER COLUMN v SET EXPRESSION (on 18-v1): b ok p ERROR: column "v" of relation "p1" contains null values c ERROR: ALTER TABLE / SET EXPRESSION is not supported for virtual generated columns in tables with check constraints k same ERROR as c, although its CHECK does not involve v 7b after deleting the violating rows: p ok, c same ERROR. The restriction is in REL_18_STABLE ATExecSetExpression() (num_check > 0 on the relation, any CHECK); f80bedd52b1 lifted it in 19 and it was not back-patched. 7c in one transaction: DROP CONSTRAINT, SET EXPRESSION on the parent, ADD CONSTRAINT again, for c and k: ok; the query lists 0. 8 pg_upgrade --check after 7c -> m-v1 and -> 19-v1: compatible. 4. Tests on the patched builds ------------------------------ make check: m-v1 239/239, 19-v1 239/239, 18-v1 231/231. src/bin/pg_upgrade TAP on m-v1 (--enable-tap-tests, PROVE_FLAGS=-j1): 8 files, 160 tests, PASS. Not run: check-world, meson/clang, cross-version pg_upgrade TAP. How to repeat psql -X -f repro-ce-on.sql.txt (any database) psql -X -f paths.sql.txt (fresh database) bash legacy.sh.txt OLD18=<18.x bindir> NEW18=<patched 18 bindir> \ <label>=<patched 19 or master bindir> ...
^ permalink raw reply [nested|flat] 24+ messages in thread

* Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned
  2026-10-10 00:23 pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Richard Guo <rguo@postgresql.org>
  2026-10-13 12:42 ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-10-13 14:34   ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Richard Guo <guofenglinux@gmail.com>
  2026-10-13 15:41     ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-10-13 16:00       ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-10-14 04:39         ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-10-26 17:40           ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Manu <manuelreyesbravo@gmail.com>
@ 2026-10-27 03:10             ` shihao zhong <zhong950419@gmail.com>
  2026-11-11 15:41               ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  0 siblings, 1 reply; 24+ messages in thread

From: shihao zhong @ 2026-10-27 03:10 UTC (permalink / raw)
  To: Manu <manuelreyesbravo@gmail.com>; +Cc: Álvaro Herrera <alvherre@kurilemu.de>; Richard Guo <guofenglinux@gmail.com>; Richard Guo <rguo@postgresql.org>; pgsql-hackers@lists.postgresql.org

Hi Manu,

Thanks for testing the pg_upgrade, I forgot about that.

I don't think the logic is wrong here, but maybe we can make some
improvement to the error message. v2 changes

  on the partitioned table of each column listed in the file
=>
  on the partitioned table of each column. In version 18 this is not
  allowed on a table with CHECK constraints, so drop them first and
  add them back afterwards. A list of the problem columns is in the
  file
Thanks,
Shihao

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

nocfbot-v2-REL_18-0001-Require-partitions-to-use-the-parent-s-virtual-gen.patch (application/octet-stream, 23.1K) download From ac9c0a80a7fe7898f967b69edf416d74a29978e0 Mon Sep 17 00:00:00 2001 From: shihao zhong <zhong950419@gmail.com> Date: Tue, 13 Oct 2026 23:22:52 -0400 Subject: [PATCH v2 REL_18] Require partitions to use the parent's virtual generation expression MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Otherwise a NOT NULL column can read as NULL through the parent. Suggested-by: Álvaro Herrera <alvherre@kurilemu.de> Discussion: https://postgr.es/m/E1xFKs5-0000000116b-2Cge@gemulon.postgresql.org --- doc/src/sgml/ddl.sgml | 4 +- doc/src/sgml/ref/alter_table.sgml | 3 + src/backend/commands/tablecmds.c | 113 +++++++++++++++++- .../regress/expected/generated_virtual.out | 109 ++++++++--------- src/test/regress/sql/generated_virtual.sql | 37 ++++-- 5 files changed, 197 insertions(+), 69 deletions(-) diff --git a/doc/src/sgml/ddl.sgml b/doc/src/sgml/ddl.sgml index ddd7096f6b2..5c892706494 100644 --- a/doc/src/sgml/ddl.sgml +++ b/doc/src/sgml/ddl.sgml @@ -452,7 +452,9 @@ CREATE TABLE people ( <para> If a parent column is a generated column, its child column must also be a generated column of the same kind (stored or virtual); however, - the child column can have a different generation expression. + the child column can have a different generation expression, except + that a virtual generated column of a partition must have the same + generation expression as the partitioned table. </para> <para> diff --git a/doc/src/sgml/ref/alter_table.sgml b/doc/src/sgml/ref/alter_table.sgml index 31f2d91418b..d6a009a54a3 100644 --- a/doc/src/sgml/ref/alter_table.sgml +++ b/doc/src/sgml/ref/alter_table.sgml @@ -272,6 +272,9 @@ WITH ( MODULUS <replaceable class="parameter">numeric_literal</replaceable>, REM This form replaces the expression of a generated column. Existing data in a stored generated column is rewritten and all the future changes will apply the new generation expression. + The expression of a virtual generated column cannot be changed for a + partition alone, or with <literal>ONLY</literal> for a partitioned table + that has partitions. </para> <para> diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 5059909833e..c841f409499 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -378,6 +378,7 @@ static List *MergeCheckConstraint(List *constraints, const char *name, Node *exp static void MergeChildAttribute(List *inh_columns, int exist_attno, int newcol_attno, const ColumnDef *newdef); static ColumnDef *MergeInheritedAttribute(List *inh_columns, int exist_attno, const ColumnDef *newdef); static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispartition); +static void CheckPartitionVirtualGeneratedExprs(Relation partrel, Relation parentrel); static void MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel); static void StoreCatalogInheritance(Oid relationId, List *supers, bool child_is_partition); @@ -522,6 +523,7 @@ static ObjectAddress ATExecDropIdentity(Relation rel, const char *colName, bool bool recurse, bool recursing); static ObjectAddress ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName, Node *newExpr, LOCKMODE lockmode); +static void ATPrepSetExpression(Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing); static void ATPrepDropExpression(Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode); static ObjectAddress ATExecDropExpression(Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode); static ObjectAddress ATExecSetStatistics(Relation rel, const char *colName, int16 colNum, @@ -1142,6 +1144,8 @@ DefineRelation(CreateStmt *stmt, char relkind, Oid ownerId, errmsg("\"%s\" is not partitioned", RelationGetRelationName(parent)))); + CheckPartitionVirtualGeneratedExprs(rel, parent); + /* * The partition constraint of the default partition depends on the * partition bounds of every other partition. It is possible that @@ -3059,7 +3063,8 @@ MergeAttributes(List *columns, const List *supers, char relpersistence, * * Same rules as above: generated-ness has to match the * parent, but the contents of the generation expression - * can be different. + * can be different, except for virtual generated columns + * (see CheckPartitionVirtualGeneratedExprs). */ if (coldef->generated) { @@ -5036,6 +5041,7 @@ ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd, case AT_SetExpression: /* ALTER COLUMN SET EXPRESSION */ ATSimplePermissions(cmd->subtype, rel, ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE); + ATPrepSetExpression(rel, cmd, recurse, recursing); ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context); pass = AT_PASS_SET_EXPRESSION; break; @@ -8774,6 +8780,45 @@ ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName, return address; } +/* + * ALTER TABLE ALTER COLUMN SET EXPRESSION + * + * The expression of a virtual generated column can only be changed for a + * whole partition tree. See CheckPartitionVirtualGeneratedExprs. + */ +static void +ATPrepSetExpression(Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing) +{ + HeapTuple tuple; + char attgenerated; + + if (recursing) + return; + + tuple = SearchSysCacheAttName(RelationGetRelid(rel), cmd->name); + if (!HeapTupleIsValid(tuple)) + return; /* error will be reported later */ + attgenerated = ((Form_pg_attribute) GETSTRUCT(tuple))->attgenerated; + ReleaseSysCache(tuple); + + if (attgenerated != ATTRIBUTE_GENERATED_VIRTUAL) + return; + + if (rel->rd_rel->relispartition) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("cannot alter generation expression of virtual generated column \"%s\" of partition \"%s\"", + cmd->name, RelationGetRelationName(rel)), + errhint("Alter the generation expression of the partitioned table instead."))); + + if (!recurse && + rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE && + find_inheritance_children(RelationGetRelid(rel), NoLock) != NIL) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("ALTER TABLE / SET EXPRESSION must be applied to child tables too"))); +} + /* * ALTER TABLE ALTER COLUMN DROP EXPRESSION */ @@ -17551,7 +17596,9 @@ constraints_equivalent(HeapTuple a, HeapTuple b, TupleDesc tupleDesc) * partitioned tables it's a foot-gun. * * The data type must match exactly. If the parent column is NOT NULL then - * the child must be as well. Defaults are not compared, however. + * the child must be as well. Defaults are not compared, however, and neither + * are generation expressions, except for virtual generated columns of a + * partition. */ static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispartition) @@ -17672,6 +17719,68 @@ MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispart } table_close(attrrel, RowExclusiveLock); + + if (ispartition) + CheckPartitionVirtualGeneratedExprs(child_rel, parent_rel); +} + +/* + * CheckPartitionVirtualGeneratedExprs + * Check that each virtual generated column of a partition has the same + * generation expression as in the partitioned table. + * + * Reading through the partitioned table computes the parent's expression, + * while constraints on the partition are checked with its own, so they must + * be the same. + */ +static void +CheckPartitionVirtualGeneratedExprs(Relation partrel, Relation parentrel) +{ + TupleDesc parent_desc = RelationGetDescr(parentrel); + TupleDesc part_desc = RelationGetDescr(partrel); + AttrMap *attmap; + + if (parent_desc->constr == NULL || + !parent_desc->constr->has_generated_virtual) + return; + + attmap = build_attrmap_by_name(part_desc, parent_desc, false); + + for (AttrNumber parent_attno = 1; parent_attno <= parent_desc->natts; parent_attno++) + { + Form_pg_attribute parent_att = TupleDescAttr(parent_desc, parent_attno - 1); + AttrNumber part_attno; + Node *parent_expr; + Node *part_expr; + bool found_whole_row; + + if (parent_att->attisdropped || + parent_att->attgenerated != ATTRIBUTE_GENERATED_VIRTUAL) + continue; + + part_attno = attmap->attnums[parent_attno - 1]; + Assert(part_attno > 0); + + parent_expr = TupleDescGetDefault(parent_desc, parent_attno); + part_expr = TupleDescGetDefault(part_desc, part_attno); + if (parent_expr == NULL || part_expr == NULL) + elog(ERROR, "missing generation expression for column \"%s\"", + NameStr(parent_att->attname)); + + parent_expr = map_variable_attnos(parent_expr, 1, 0, attmap, + InvalidOid, &found_whole_row); + /* generation expressions cannot contain whole-row Vars */ + Assert(!found_whole_row); + + if (!equal(parent_expr, part_expr)) + ereport(ERROR, + (errcode(ERRCODE_INVALID_COLUMN_DEFINITION), + errmsg("virtual generated column \"%s\" of partition \"%s\" must have the same generation expression as the partitioned table", + NameStr(parent_att->attname), + RelationGetRelationName(partrel)))); + } + + free_attrmap(attmap); } /* diff --git a/src/test/regress/expected/generated_virtual.out b/src/test/regress/expected/generated_virtual.out index 03698488907..6108fce2ae4 100644 --- a/src/test/regress/expected/generated_virtual.out +++ b/src/test/regress/expected/generated_virtual.out @@ -882,7 +882,11 @@ CREATE TABLE gtest_parent (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWA CREATE TABLE gtest_child PARTITION OF gtest_parent FOR VALUES FROM ('2016-07-01') TO ('2016-08-01'); -- inherits gen expr CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( - f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- overrides gen expr + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- error, must match parent +) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); +ERROR: virtual generated column "f3" of partition "gtest_child2" must have the same generation expression as the partitioned table +CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 2) VIRTUAL -- same as parent, ok ) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); CREATE TABLE gtest_child3 PARTITION OF gtest_parent ( f3 DEFAULT 42 -- error @@ -916,6 +920,11 @@ ERROR: column "f3" inherits from generated column of different kind DETAIL: Parent column is VIRTUAL, child column is STORED. DROP TABLE gtest_child3; CREATE TABLE gtest_child3 (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWAYS AS (f2 * 33) VIRTUAL); +ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); -- error +ERROR: virtual generated column "f3" of partition "gtest_child3" must have the same generation expression as the partitioned table +DROP TABLE gtest_child3; +-- different column order, so the parent's expression has to be mapped +CREATE TABLE gtest_child3 (f3 bigint GENERATED ALWAYS AS (f2 * 2) VIRTUAL, f2 bigint, f1 date NOT NULL); ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); \d gtest_child Table "generated_virtual_tests.gtest_child" @@ -927,21 +936,21 @@ ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09 Partition of: gtest_parent FOR VALUES FROM ('07-01-2016') TO ('08-01-2016') \d gtest_child2 - Table "generated_virtual_tests.gtest_child2" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- + Table "generated_virtual_tests.gtest_child2" + Column | Type | Collation | Nullable | Default +--------+--------+-----------+----------+------------------------------ f1 | date | | not null | f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 22) + f3 | bigint | | | generated always as (f2 * 2) Partition of: gtest_parent FOR VALUES FROM ('08-01-2016') TO ('09-01-2016') \d gtest_child3 - Table "generated_virtual_tests.gtest_child3" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | + Table "generated_virtual_tests.gtest_child3" + Column | Type | Collation | Nullable | Default +--------+--------+-----------+----------+------------------------------ + f3 | bigint | | | generated always as (f2 * 2) f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 33) + f1 | date | | not null | Partition of: gtest_parent FOR VALUES FROM ('09-01-2016') TO ('10-01-2016') INSERT INTO gtest_parent (f1, f2) VALUES ('2016-07-15', 1); @@ -962,14 +971,14 @@ SELECT tableoid::regclass, * FROM gtest_child ORDER BY 1, 2, 3; gtest_child | 07-15-2016 | 2 | 4 (2 rows) -SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; -- uses child's generation expression, not parent's +SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; tableoid | f1 | f2 | f3 --------------+------------+----+---- - gtest_child2 | 08-15-2016 | 3 | 66 + gtest_child2 | 08-15-2016 | 3 | 6 (1 row) SELECT tableoid::regclass, * FROM gtest_child3 ORDER BY 1, 2, 3; - tableoid | f1 | f2 | f3 + tableoid | f3 | f2 | f1 ----------+----+----+---- (0 rows) @@ -982,46 +991,14 @@ SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; gtest_child3 | 09-13-2016 | 1 | 2 (3 rows) --- alter only parent's and one child's generation expression -ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -\d gtest_parent - Partitioned table "generated_virtual_tests.gtest_parent" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------ - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 4) -Partition key: RANGE (f1) -Number of partitions: 3 (Use \d+ to list them.) - -\d gtest_child - Table "generated_virtual_tests.gtest_child" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 10) -Partition of: gtest_parent FOR VALUES FROM ('07-01-2016') TO ('08-01-2016') - -\d gtest_child2 - Table "generated_virtual_tests.gtest_child2" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 22) -Partition of: gtest_parent FOR VALUES FROM ('08-01-2016') TO ('09-01-2016') - -\d gtest_child3 - Table "generated_virtual_tests.gtest_child3" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 33) -Partition of: gtest_parent FOR VALUES FROM ('09-01-2016') TO ('10-01-2016') - +-- cannot alter only parent's or one partition's generation expression +ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -- error +ERROR: ALTER TABLE / SET EXPRESSION must be applied to child tables too +ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -- error +ERROR: cannot alter generation expression of virtual generated column "f3" of partition "gtest_child" +HINT: Alter the generation expression of the partitioned table instead. +-- alter generation expression of parent and all its children altogether +ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; tableoid | f1 | f2 | f3 --------------+------------+----+---- @@ -1030,7 +1007,10 @@ SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; gtest_child3 | 09-13-2016 | 1 | 4 (3 rows) --- alter generation expression of parent and all its children altogether +ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 12); -- error +ERROR: check constraint "cc1" of relation "gtest_child2" is violated by some row +ALTER TABLE gtest_parent ADD CONSTRAINT cc CHECK (f3 < 13); -- ok +ALTER TABLE gtest_parent DROP CONSTRAINT cc; ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 2); \d gtest_parent Partitioned table "generated_virtual_tests.gtest_parent" @@ -1064,9 +1044,9 @@ Partition of: gtest_parent FOR VALUES FROM ('08-01-2016') TO ('09-01-2016') Table "generated_virtual_tests.gtest_child3" Column | Type | Collation | Nullable | Default --------+--------+-----------+----------+------------------------------ - f1 | date | | not null | - f2 | bigint | | | f3 | bigint | | | generated always as (f2 * 2) + f2 | bigint | | | + f1 | date | | not null | Partition of: gtest_parent FOR VALUES FROM ('09-01-2016') TO ('10-01-2016') SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; @@ -1812,3 +1792,20 @@ select * from gtest_cursor order by id; commit; drop table gtest_cursor; +-- a partition cannot have a different generation expression, which would let +-- the partitioned table's NOT NULL virtual column read as NULL +CREATE TABLE gtestnn_parent2 (a int NOT NULL, b int GENERATED ALWAYS AS (nullif(a, 0)) VIRTUAL NOT NULL) PARTITION BY LIST (a); +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 (b GENERATED ALWAYS AS (a + 1) VIRTUAL) FOR VALUES IN (0); -- error +ERROR: virtual generated column "b" of partition "gtestnn_child2" must have the same generation expression as the partitioned table +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 FOR VALUES IN (0, 1); +INSERT INTO gtestnn_parent2 VALUES (0); -- error +ERROR: null value in column "b" of relation "gtestnn_child2" violates not-null constraint +DETAIL: Failing row contains (0, virtual). +INSERT INTO gtestnn_parent2 VALUES (1); +SELECT a, b FROM gtestnn_parent2; + a | b +---+--- + 1 | 1 +(1 row) + +DROP TABLE gtestnn_parent2; diff --git a/src/test/regress/sql/generated_virtual.sql b/src/test/regress/sql/generated_virtual.sql index b1b92b2ced5..d1bbf9352d7 100644 --- a/src/test/regress/sql/generated_virtual.sql +++ b/src/test/regress/sql/generated_virtual.sql @@ -514,7 +514,10 @@ CREATE TABLE gtest_parent (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWA CREATE TABLE gtest_child PARTITION OF gtest_parent FOR VALUES FROM ('2016-07-01') TO ('2016-08-01'); -- inherits gen expr CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( - f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- overrides gen expr + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- error, must match parent +) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); +CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 2) VIRTUAL -- same as parent, ok ) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); CREATE TABLE gtest_child3 PARTITION OF gtest_parent ( f3 DEFAULT 42 -- error @@ -538,6 +541,10 @@ CREATE TABLE gtest_child3 (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWA ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); -- error DROP TABLE gtest_child3; CREATE TABLE gtest_child3 (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWAYS AS (f2 * 33) VIRTUAL); +ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); -- error +DROP TABLE gtest_child3; +-- different column order, so the parent's expression has to be mapped +CREATE TABLE gtest_child3 (f3 bigint GENERATED ALWAYS AS (f2 * 2) VIRTUAL, f2 bigint, f1 date NOT NULL); ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); \d gtest_child \d gtest_child2 @@ -547,21 +554,21 @@ INSERT INTO gtest_parent (f1, f2) VALUES ('2016-07-15', 2); INSERT INTO gtest_parent (f1, f2) VALUES ('2016-08-15', 3); SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; SELECT tableoid::regclass, * FROM gtest_child ORDER BY 1, 2, 3; -SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; -- uses child's generation expression, not parent's +SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; SELECT tableoid::regclass, * FROM gtest_child3 ORDER BY 1, 2, 3; UPDATE gtest_parent SET f1 = f1 + 60 WHERE f2 = 1; SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; --- alter only parent's and one child's generation expression -ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -\d gtest_parent -\d gtest_child -\d gtest_child2 -\d gtest_child3 -SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; +-- cannot alter only parent's or one partition's generation expression +ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -- error +ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -- error -- alter generation expression of parent and all its children altogether +ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); +SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; +ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 12); -- error +ALTER TABLE gtest_parent ADD CONSTRAINT cc CHECK (f3 < 13); -- ok +ALTER TABLE gtest_parent DROP CONSTRAINT cc; ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 2); \d gtest_parent \d gtest_child @@ -969,3 +976,13 @@ select * from gtest_cursor order by id; commit; drop table gtest_cursor; + +-- a partition cannot have a different generation expression, which would let +-- the partitioned table's NOT NULL virtual column read as NULL +CREATE TABLE gtestnn_parent2 (a int NOT NULL, b int GENERATED ALWAYS AS (nullif(a, 0)) VIRTUAL NOT NULL) PARTITION BY LIST (a); +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 (b GENERATED ALWAYS AS (a + 1) VIRTUAL) FOR VALUES IN (0); -- error +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 FOR VALUES IN (0, 1); +INSERT INTO gtestnn_parent2 VALUES (0); -- error +INSERT INTO gtestnn_parent2 VALUES (1); +SELECT a, b FROM gtestnn_parent2; +DROP TABLE gtestnn_parent2; -- 2.37.1 (Apple Git-137.1)
v2-0001-Require-partitions-to-use-the-parent-s-virtual-ge.patch (application/octet-stream, 28.9K) download From 9ba50b64cf9089953c48463f4f3e622b691d6607 Mon Sep 17 00:00:00 2001 From: shihao zhong <zhong950419@gmail.com> Date: Tue, 13 Oct 2026 23:22:52 -0400 Subject: [PATCH v2] Require partitions to use the parent's virtual generation expression MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Otherwise a NOT NULL column can read as NULL through the parent. Suggested-by: Álvaro Herrera <alvherre@kurilemu.de> Discussion: https://postgr.es/m/E1xFKs5-0000000116b-2Cge@gemulon.postgresql.org --- doc/src/sgml/ddl.sgml | 4 +- doc/src/sgml/ref/alter_table.sgml | 3 + src/backend/commands/tablecmds.c | 113 +++++++++++++++++- src/bin/pg_upgrade/check.c | 73 +++++++++++ .../regress/expected/generated_virtual.out | 110 +++++++---------- src/test/regress/sql/generated_virtual.sql | 44 +++---- 6 files changed, 256 insertions(+), 91 deletions(-) diff --git a/doc/src/sgml/ddl.sgml b/doc/src/sgml/ddl.sgml index d78d986756e..ae416531732 100644 --- a/doc/src/sgml/ddl.sgml +++ b/doc/src/sgml/ddl.sgml @@ -452,7 +452,9 @@ CREATE TABLE people ( <para> If a parent column is a generated column, its child column must also be a generated column of the same kind (stored or virtual); however, - the child column can have a different generation expression. + the child column can have a different generation expression, except + that a virtual generated column of a partition must have the same + generation expression as the partitioned table. </para> <para> diff --git a/doc/src/sgml/ref/alter_table.sgml b/doc/src/sgml/ref/alter_table.sgml index 0f9d698d170..d4156cc4253 100644 --- a/doc/src/sgml/ref/alter_table.sgml +++ b/doc/src/sgml/ref/alter_table.sgml @@ -276,6 +276,9 @@ WITH ( MODULUS <replaceable class="parameter">numeric_literal</replaceable>, REM Replacing the expression of a virtual generated column does not require a table rewrite, but if the column is used in a constraint, the table will be scanned to check that existing rows meet the constraint. + The expression of a virtual generated column cannot be changed for a + partition alone, or with <literal>ONLY</literal> for a partitioned table + that has partitions. </para> <para> diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 97e16f3eb47..5fcddac4420 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -380,6 +380,7 @@ static List *MergeCheckConstraint(List *constraints, const char *name, Node *exp static void MergeChildAttribute(List *inh_columns, int exist_attno, int newcol_attno, const ColumnDef *newdef); static ColumnDef *MergeInheritedAttribute(List *inh_columns, int exist_attno, const ColumnDef *newdef); static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispartition); +static void CheckPartitionVirtualGeneratedExprs(Relation partrel, Relation parentrel); static void MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel); static void StoreCatalogInheritance(Oid relationId, List *supers, bool child_is_partition); @@ -539,6 +540,7 @@ static ObjectAddress ATExecDropIdentity(Relation rel, const char *colName, bool bool recurse, bool recursing); static ObjectAddress ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName, Node *newExpr, LOCKMODE lockmode); +static void ATPrepSetExpression(Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing); static void ATPrepDropExpression(Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode); static ObjectAddress ATExecDropExpression(Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode); static ObjectAddress ATExecSetStatistics(Relation rel, const char *colName, int16 colNum, @@ -1161,6 +1163,8 @@ DefineRelation(CreateStmt *stmt, char relkind, Oid ownerId, errmsg("\"%s\" is not partitioned", RelationGetRelationName(parent)))); + CheckPartitionVirtualGeneratedExprs(rel, parent); + /* * The partition constraint of the default partition depends on the * partition bounds of every other partition. It is possible that @@ -3096,7 +3100,8 @@ MergeAttributes(List *columns, const List *supers, char relpersistence, * * Same rules as above: generated-ness has to match the * parent, but the contents of the generation expression - * can be different. + * can be different, except for virtual generated columns + * (see CheckPartitionVirtualGeneratedExprs). */ if (coldef->generated) { @@ -5086,6 +5091,7 @@ ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd, case AT_SetExpression: /* ALTER COLUMN SET EXPRESSION */ ATSimplePermissions(cmd->subtype, rel, ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE); + ATPrepSetExpression(rel, cmd, recurse, recursing); ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context); pass = AT_PASS_SET_EXPRESSION; break; @@ -8836,6 +8842,45 @@ ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName, return address; } +/* + * ALTER TABLE ALTER COLUMN SET EXPRESSION + * + * The expression of a virtual generated column can only be changed for a + * whole partition tree. See CheckPartitionVirtualGeneratedExprs. + */ +static void +ATPrepSetExpression(Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing) +{ + HeapTuple tuple; + char attgenerated; + + if (recursing) + return; + + tuple = SearchSysCacheAttName(RelationGetRelid(rel), cmd->name); + if (!HeapTupleIsValid(tuple)) + return; /* error will be reported later */ + attgenerated = ((Form_pg_attribute) GETSTRUCT(tuple))->attgenerated; + ReleaseSysCache(tuple); + + if (attgenerated != ATTRIBUTE_GENERATED_VIRTUAL) + return; + + if (rel->rd_rel->relispartition) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("cannot alter generation expression of virtual generated column \"%s\" of partition \"%s\"", + cmd->name, RelationGetRelationName(rel)), + errhint("Alter the generation expression of the partitioned table instead."))); + + if (!recurse && + rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE && + find_inheritance_children(RelationGetRelid(rel), NoLock) != NIL) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("ALTER TABLE / SET EXPRESSION must be applied to child tables too"))); +} + /* * ALTER TABLE ALTER COLUMN DROP EXPRESSION */ @@ -18175,7 +18220,9 @@ constraints_equivalent(HeapTuple a, HeapTuple b, TupleDesc tupleDesc) * partitioned tables it's a foot-gun. * * The data type must match exactly. If the parent column is NOT NULL then - * the child must be as well. Defaults are not compared, however. + * the child must be as well. Defaults are not compared, however, and neither + * are generation expressions, except for virtual generated columns of a + * partition. */ static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispartition) @@ -18296,6 +18343,68 @@ MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispart } table_close(attrrel, RowExclusiveLock); + + if (ispartition) + CheckPartitionVirtualGeneratedExprs(child_rel, parent_rel); +} + +/* + * CheckPartitionVirtualGeneratedExprs + * Check that each virtual generated column of a partition has the same + * generation expression as in the partitioned table. + * + * Reading through the partitioned table computes the parent's expression, + * while constraints on the partition are checked with its own, so they must + * be the same. + */ +static void +CheckPartitionVirtualGeneratedExprs(Relation partrel, Relation parentrel) +{ + TupleDesc parent_desc = RelationGetDescr(parentrel); + TupleDesc part_desc = RelationGetDescr(partrel); + AttrMap *attmap; + + if (parent_desc->constr == NULL || + !parent_desc->constr->has_generated_virtual) + return; + + attmap = build_attrmap_by_name(part_desc, parent_desc, false); + + for (AttrNumber parent_attno = 1; parent_attno <= parent_desc->natts; parent_attno++) + { + Form_pg_attribute parent_att = TupleDescAttr(parent_desc, parent_attno - 1); + AttrNumber part_attno; + Node *parent_expr; + Node *part_expr; + bool found_whole_row; + + if (parent_att->attisdropped || + parent_att->attgenerated != ATTRIBUTE_GENERATED_VIRTUAL) + continue; + + part_attno = attmap->attnums[parent_attno - 1]; + Assert(part_attno > 0); + + parent_expr = TupleDescGetDefault(parent_desc, parent_attno); + part_expr = TupleDescGetDefault(part_desc, part_attno); + if (parent_expr == NULL || part_expr == NULL) + elog(ERROR, "missing generation expression for column \"%s\"", + NameStr(parent_att->attname)); + + parent_expr = map_variable_attnos(parent_expr, 1, 0, attmap, + InvalidOid, &found_whole_row); + /* generation expressions cannot contain whole-row Vars */ + Assert(!found_whole_row); + + if (!equal(parent_expr, part_expr)) + ereport(ERROR, + (errcode(ERRCODE_INVALID_COLUMN_DEFINITION), + errmsg("virtual generated column \"%s\" of partition \"%s\" must have the same generation expression as the partitioned table", + NameStr(parent_att->attname), + RelationGetRelationName(partrel)))); + } + + free_attrmap(attmap); } /* diff --git a/src/bin/pg_upgrade/check.c b/src/bin/pg_upgrade/check.c index 150c4fc34b9..f9a76b4ae8f 100644 --- a/src/bin/pg_upgrade/check.c +++ b/src/bin/pg_upgrade/check.c @@ -29,6 +29,7 @@ static void check_for_user_defined_postfix_ops(ClusterInfo *cluster); static void check_for_incompatible_polymorphics(ClusterInfo *cluster); static void check_for_tables_with_oids(ClusterInfo *cluster); static void check_for_not_null_inheritance(ClusterInfo *cluster); +static void check_for_partition_virtual_generated_exprs(ClusterInfo *cluster); static void check_for_gist_inet_ops(ClusterInfo *cluster); static void check_for_new_tablespace_dir(void); static void check_for_user_defined_encoding_conversions(ClusterInfo *cluster); @@ -673,6 +674,15 @@ check_and_dump_old_cluster(void) if (GET_MAJOR_VERSION(old_cluster.major_version) <= 1800) check_for_not_null_inheritance(&old_cluster); + /* + * Virtual generated columns (new in PG 18) of a partition used to be + * allowed to have a different generation expression than the partitioned + * table, but schema restore fails for them now. Verify there are none. + */ + if (GET_MAJOR_VERSION(old_cluster.major_version) >= 1800 && + GET_MAJOR_VERSION(old_cluster.major_version) <= 1900) + check_for_partition_virtual_generated_exprs(&old_cluster); + /* * The btree_gist extension contains gist_inet_ops and gist_cidr_ops * opclasses that do not reliably give correct answers. We want to @@ -1738,6 +1748,69 @@ check_for_not_null_inheritance(ClusterInfo *cluster) check_ok(); } +/* + * check_for_partition_virtual_generated_exprs() + * + * A virtual generated column of a partition must have the same generation + * expression as the partitioned table. Check that the cluster to be upgraded + * has no partitions that differ, which older versions allowed. + */ +static void +check_for_partition_virtual_generated_exprs(ClusterInfo *cluster) +{ + UpgradeTaskReport report; + UpgradeTask *task; + const char *query; + + prep_status("Checking for virtual generated column inconsistencies"); + + report.file = NULL; + snprintf(report.path, sizeof(report.path), "%s/%s", + log_opts.basedir, + "partition_virtual_generated_columns.txt"); + + query = "SELECT nc.nspname, cc.relname, ac.attname " + "FROM pg_catalog.pg_class cc " + " JOIN pg_catalog.pg_namespace nc ON nc.oid = cc.relnamespace " + " JOIN pg_catalog.pg_inherits i ON i.inhrelid = cc.oid " + " JOIN pg_catalog.pg_attribute ac ON ac.attrelid = cc.oid " + " JOIN pg_catalog.pg_attribute ap ON ap.attrelid = i.inhparent " + " AND ap.attname = ac.attname " + " JOIN pg_catalog.pg_attrdef dc ON dc.adrelid = ac.attrelid " + " AND dc.adnum = ac.attnum " + " JOIN pg_catalog.pg_attrdef dp ON dp.adrelid = ap.attrelid " + " AND dp.adnum = ap.attnum " + "WHERE cc.relispartition AND ac.attgenerated = 'v' " + " AND pg_catalog.pg_get_expr(dc.adbin, dc.adrelid) <> " + " pg_catalog.pg_get_expr(dp.adbin, dp.adrelid)"; + + task = upgrade_task_create(); + /* the not-null check's callback reports the same columns */ + upgrade_task_add_step(task, query, + process_inconsistent_notnull, + true, &report); + upgrade_task_run(task, cluster); + upgrade_task_free(task); + + if (report.file) + { + fclose(report.file); + pg_log(PG_REPORT, "fatal"); + pg_fatal("Your installation contains partitions whose virtual generated columns\n" + "have a different generation expression than the partitioned table.\n" + "This is no longer allowed, so the upgrade would fail. You can fix\n" + "this by running\n" + " ALTER TABLE parent ALTER COLUMN column SET EXPRESSION AS (...);\n" + "on the partitioned table of each column. In version 18 this is not\n" + "allowed on a table with CHECK constraints, so drop them first and\n" + "add them back afterwards. A list of the problem columns is in the\n" + "file:\n" + " %s", report.path); + } + else + check_ok(); +} + /* * Callback function for processing results of query for * check_for_gist_inet_ops()'s UpgradeTask. If the query returned any rows diff --git a/src/test/regress/expected/generated_virtual.out b/src/test/regress/expected/generated_virtual.out index b2f8e16e63b..a021ad6d589 100644 --- a/src/test/regress/expected/generated_virtual.out +++ b/src/test/regress/expected/generated_virtual.out @@ -912,7 +912,11 @@ CREATE TABLE gtest_parent (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWA CREATE TABLE gtest_child PARTITION OF gtest_parent FOR VALUES FROM ('2016-07-01') TO ('2016-08-01'); -- inherits gen expr CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( - f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- overrides gen expr + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- error, must match parent +) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); +ERROR: virtual generated column "f3" of partition "gtest_child2" must have the same generation expression as the partitioned table +CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 2) VIRTUAL -- same as parent, ok ) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); CREATE TABLE gtest_child3 PARTITION OF gtest_parent ( f3 DEFAULT 42 -- error @@ -946,6 +950,11 @@ ERROR: column "f3" inherits from generated column of different kind DETAIL: Parent column is VIRTUAL, child column is STORED. DROP TABLE gtest_child3; CREATE TABLE gtest_child3 (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWAYS AS (f2 * 33) VIRTUAL); +ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); -- error +ERROR: virtual generated column "f3" of partition "gtest_child3" must have the same generation expression as the partitioned table +DROP TABLE gtest_child3; +-- different column order, so the parent's expression has to be mapped +CREATE TABLE gtest_child3 (f3 bigint GENERATED ALWAYS AS (f2 * 2) VIRTUAL, f2 bigint, f1 date NOT NULL); ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); \d gtest_child Table "generated_virtual_tests.gtest_child" @@ -957,21 +966,21 @@ ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09 Partition of: gtest_parent FOR VALUES FROM ('07-01-2016') TO ('08-01-2016') \d gtest_child2 - Table "generated_virtual_tests.gtest_child2" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- + Table "generated_virtual_tests.gtest_child2" + Column | Type | Collation | Nullable | Default +--------+--------+-----------+----------+------------------------------ f1 | date | | not null | f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 22) + f3 | bigint | | | generated always as (f2 * 2) Partition of: gtest_parent FOR VALUES FROM ('08-01-2016') TO ('09-01-2016') \d gtest_child3 - Table "generated_virtual_tests.gtest_child3" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | + Table "generated_virtual_tests.gtest_child3" + Column | Type | Collation | Nullable | Default +--------+--------+-----------+----------+------------------------------ + f3 | bigint | | | generated always as (f2 * 2) f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 33) + f1 | date | | not null | Partition of: gtest_parent FOR VALUES FROM ('09-01-2016') TO ('10-01-2016') INSERT INTO gtest_parent (f1, f2) VALUES ('2016-07-15', 1); @@ -992,14 +1001,14 @@ SELECT tableoid::regclass, * FROM gtest_child ORDER BY 1, 2, 3; gtest_child | 07-15-2016 | 2 | 4 (2 rows) -SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; -- uses child's generation expression, not parent's +SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; tableoid | f1 | f2 | f3 --------------+------------+----+---- - gtest_child2 | 08-15-2016 | 3 | 66 + gtest_child2 | 08-15-2016 | 3 | 6 (1 row) SELECT tableoid::regclass, * FROM gtest_child3 ORDER BY 1, 2, 3; - tableoid | f1 | f2 | f3 + tableoid | f3 | f2 | f1 ----------+----+----+---- (0 rows) @@ -1012,46 +1021,14 @@ SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; gtest_child3 | 09-13-2016 | 1 | 2 (3 rows) --- alter only parent's and one child's generation expression -ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -\d gtest_parent - Partitioned table "generated_virtual_tests.gtest_parent" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------ - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 4) -Partition key: RANGE (f1) -Number of partitions: 3 (Use \d+ to list them.) - -\d gtest_child - Table "generated_virtual_tests.gtest_child" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 10) -Partition of: gtest_parent FOR VALUES FROM ('07-01-2016') TO ('08-01-2016') - -\d gtest_child2 - Table "generated_virtual_tests.gtest_child2" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 22) -Partition of: gtest_parent FOR VALUES FROM ('08-01-2016') TO ('09-01-2016') - -\d gtest_child3 - Table "generated_virtual_tests.gtest_child3" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 33) -Partition of: gtest_parent FOR VALUES FROM ('09-01-2016') TO ('10-01-2016') - +-- cannot alter only parent's or one partition's generation expression +ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -- error +ERROR: ALTER TABLE / SET EXPRESSION must be applied to child tables too +ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -- error +ERROR: cannot alter generation expression of virtual generated column "f3" of partition "gtest_child" +HINT: Alter the generation expression of the partitioned table instead. +-- alter generation expression of parent and all its children altogether +ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; tableoid | f1 | f2 | f3 --------------+------------+----+---- @@ -1060,16 +1037,10 @@ SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; gtest_child3 | 09-13-2016 | 1 | 4 (3 rows) --- check constraint was validated based on each partitions's generation expression -ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 19); -- error -ERROR: check constraint "cc1" of relation "gtest_child" is violated by some row -ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 66); -- error +ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 12); -- error ERROR: check constraint "cc1" of relation "gtest_child2" is violated by some row -ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 <> 33); -- error -ERROR: check constraint "cc1" of relation "gtest_child3" is violated by some row -ALTER TABLE gtest_parent ADD CONSTRAINT cc CHECK (f3 < 67); -- ok +ALTER TABLE gtest_parent ADD CONSTRAINT cc CHECK (f3 < 13); -- ok ALTER TABLE gtest_parent DROP CONSTRAINT cc; --- alter generation expression of parent and all its children altogether ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 2); \d gtest_parent Partitioned table "generated_virtual_tests.gtest_parent" @@ -1103,9 +1074,9 @@ Partition of: gtest_parent FOR VALUES FROM ('08-01-2016') TO ('09-01-2016') Table "generated_virtual_tests.gtest_child3" Column | Type | Collation | Nullable | Default --------+--------+-----------+----------+------------------------------ - f1 | date | | not null | - f2 | bigint | | | f3 | bigint | | | generated always as (f2 * 2) + f2 | bigint | | | + f1 | date | | not null | Partition of: gtest_parent FOR VALUES FROM ('09-01-2016') TO ('10-01-2016') SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; @@ -1886,11 +1857,16 @@ select * from gtest_cursor order by id; commit; drop table gtest_cursor; --- NOT NULL on a partitioned table's virtual column does not prove non-nullness, --- because a partition can have a different generation expression +-- a partition cannot have a different generation expression, which would let +-- the partitioned table's NOT NULL virtual column read as NULL CREATE TABLE gtestnn_parent2 (a int NOT NULL, b int GENERATED ALWAYS AS (nullif(a, 0)) VIRTUAL NOT NULL) PARTITION BY LIST (a); -CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 (b GENERATED ALWAYS AS (a + 1) VIRTUAL) FOR VALUES IN (0); -INSERT INTO gtestnn_parent2 VALUES (0); +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 (b GENERATED ALWAYS AS (a + 1) VIRTUAL) FOR VALUES IN (0); -- error +ERROR: virtual generated column "b" of partition "gtestnn_child2" must have the same generation expression as the partitioned table +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 FOR VALUES IN (0, 1); +INSERT INTO gtestnn_parent2 VALUES (0); -- error +ERROR: null value in column "b" of relation "gtestnn_child2" violates not-null constraint +DETAIL: Failing row contains (0, virtual). +INSERT INTO gtestnn_parent2 VALUES (1); EXPLAIN (COSTS OFF) SELECT a FROM gtestnn_parent2 WHERE a NOT IN (SELECT b FROM gtestnn_parent2); QUERY PLAN diff --git a/src/test/regress/sql/generated_virtual.sql b/src/test/regress/sql/generated_virtual.sql index c4c4f3d5ef1..d36019b373a 100644 --- a/src/test/regress/sql/generated_virtual.sql +++ b/src/test/regress/sql/generated_virtual.sql @@ -529,7 +529,10 @@ CREATE TABLE gtest_parent (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWA CREATE TABLE gtest_child PARTITION OF gtest_parent FOR VALUES FROM ('2016-07-01') TO ('2016-08-01'); -- inherits gen expr CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( - f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- overrides gen expr + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- error, must match parent +) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); +CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 2) VIRTUAL -- same as parent, ok ) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); CREATE TABLE gtest_child3 PARTITION OF gtest_parent ( f3 DEFAULT 42 -- error @@ -553,6 +556,10 @@ CREATE TABLE gtest_child3 (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWA ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); -- error DROP TABLE gtest_child3; CREATE TABLE gtest_child3 (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWAYS AS (f2 * 33) VIRTUAL); +ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); -- error +DROP TABLE gtest_child3; +-- different column order, so the parent's expression has to be mapped +CREATE TABLE gtest_child3 (f3 bigint GENERATED ALWAYS AS (f2 * 2) VIRTUAL, f2 bigint, f1 date NOT NULL); ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); \d gtest_child \d gtest_child2 @@ -562,28 +569,21 @@ INSERT INTO gtest_parent (f1, f2) VALUES ('2016-07-15', 2); INSERT INTO gtest_parent (f1, f2) VALUES ('2016-08-15', 3); SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; SELECT tableoid::regclass, * FROM gtest_child ORDER BY 1, 2, 3; -SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; -- uses child's generation expression, not parent's +SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; SELECT tableoid::regclass, * FROM gtest_child3 ORDER BY 1, 2, 3; UPDATE gtest_parent SET f1 = f1 + 60 WHERE f2 = 1; SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; --- alter only parent's and one child's generation expression -ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -\d gtest_parent -\d gtest_child -\d gtest_child2 -\d gtest_child3 -SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; - --- check constraint was validated based on each partitions's generation expression -ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 19); -- error -ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 66); -- error -ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 <> 33); -- error -ALTER TABLE gtest_parent ADD CONSTRAINT cc CHECK (f3 < 67); -- ok -ALTER TABLE gtest_parent DROP CONSTRAINT cc; +-- cannot alter only parent's or one partition's generation expression +ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -- error +ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -- error -- alter generation expression of parent and all its children altogether +ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); +SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; +ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 12); -- error +ALTER TABLE gtest_parent ADD CONSTRAINT cc CHECK (f3 < 13); -- ok +ALTER TABLE gtest_parent DROP CONSTRAINT cc; ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 2); \d gtest_parent \d gtest_child @@ -1005,11 +1005,13 @@ commit; drop table gtest_cursor; --- NOT NULL on a partitioned table's virtual column does not prove non-nullness, --- because a partition can have a different generation expression +-- a partition cannot have a different generation expression, which would let +-- the partitioned table's NOT NULL virtual column read as NULL CREATE TABLE gtestnn_parent2 (a int NOT NULL, b int GENERATED ALWAYS AS (nullif(a, 0)) VIRTUAL NOT NULL) PARTITION BY LIST (a); -CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 (b GENERATED ALWAYS AS (a + 1) VIRTUAL) FOR VALUES IN (0); -INSERT INTO gtestnn_parent2 VALUES (0); +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 (b GENERATED ALWAYS AS (a + 1) VIRTUAL) FOR VALUES IN (0); -- error +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 FOR VALUES IN (0, 1); +INSERT INTO gtestnn_parent2 VALUES (0); -- error +INSERT INTO gtestnn_parent2 VALUES (1); EXPLAIN (COSTS OFF) SELECT a FROM gtestnn_parent2 WHERE a NOT IN (SELECT b FROM gtestnn_parent2); SELECT a FROM gtestnn_parent2 WHERE a NOT IN (SELECT b FROM gtestnn_parent2); -- 2.37.1 (Apple Git-137.1)
^ permalink raw reply [nested|flat] 24+ messages in thread

* Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned
  2026-10-10 00:23 pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Richard Guo <rguo@postgresql.org>
  2026-10-13 12:42 ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-10-13 14:34   ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Richard Guo <guofenglinux@gmail.com>
  2026-10-13 15:41     ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-10-13 16:00       ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-10-14 04:39         ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-10-26 17:40           ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Manu <manuelreyesbravo@gmail.com>
  2026-10-27 03:10             ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
@ 2026-11-11 15:41               ` Álvaro Herrera <alvherre@kurilemu.de>
  2026-11-11 15:47                 ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  0 siblings, 1 reply; 24+ messages in thread

From: Álvaro Herrera @ 2026-11-11 15:41 UTC (permalink / raw)
  To: shihao zhong <zhong950419@gmail.com>; +Cc: Manu <manuelreyesbravo@gmail.com>; Richard Guo <guofenglinux@gmail.com>; Richard Guo <rguo@postgresql.org>; pgsql-hackers@lists.postgresql.org

On 2026-Oct-26, shihao zhong wrote:

> Hi Manu,
> 
> Thanks for testing the pg_upgrade, I forgot about that.
> 
> I don't think the logic is wrong here, but maybe we can make some
> improvement to the error message. v2 changes
> 
>   on the partitioned table of each column listed in the file
> =>
>   on the partitioned table of each column. In version 18 this is not
>   allowed on a table with CHECK constraints, so drop them first and
>   add them back afterwards. A list of the problem columns is in the
>   file

I think the doc changes here are not ideal; they kinda suggest that there are
numerous different generated column types for which you can have different
generation expressions except for one special case -- rather than one case yes,
one case no.  How about something like this?

         If a parent column is a generated column, its child column must also
-        be a generated column of the same kind (stored or virtual); however,
-        the child column can have a different generation expression, except
-        that a virtual generated column of a partition must have the same
-        generation expression as the partitioned table.
+        be a generated column of the same kind (stored or virtual).
+        In addition, for virtual generated columns, the child column's
+        generation expression must be identical to that of the parent.
+        For stored generated columns, they are allowed to differ.

-- 
Álvaro Herrera        Breisgau, Deutschland  —  https://www.EnterpriseDB.com/
"I'm impressed how quickly you are fixing this obscure issue. I came from 
MS SQL and it would be hard for me to put into words how much of a better job
you all are doing on [PostgreSQL]."
 Steve Midgley, http://archives.postgresql.org/pgsql-sql/2008-08/msg00000.php





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

* Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned
  2026-10-10 00:23 pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Richard Guo <rguo@postgresql.org>
  2026-10-13 12:42 ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-10-13 14:34   ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Richard Guo <guofenglinux@gmail.com>
  2026-10-13 15:41     ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-10-13 16:00       ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-10-14 04:39         ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-10-26 17:40           ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Manu <manuelreyesbravo@gmail.com>
  2026-10-27 03:10             ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-11-11 15:41               ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
@ 2026-11-11 15:47                 ` Álvaro Herrera <alvherre@kurilemu.de>
  2026-11-12 04:36                   ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  0 siblings, 1 reply; 24+ messages in thread

From: Álvaro Herrera @ 2026-11-11 15:47 UTC (permalink / raw)
  To: shihao zhong <zhong950419@gmail.com>; +Cc: Manu <manuelreyesbravo@gmail.com>; Richard Guo <guofenglinux@gmail.com>; Richard Guo <rguo@postgresql.org>; pgsql-hackers@lists.postgresql.org

Also, the comment in MergeAttributes is ... not wrong, but doesn't
really flow with the code, I think.  How about a change like this?

                     * Same rules as above: generated-ness has to match the
-                    * parent, but the contents of the generation expression
-                    * can be different, except for virtual generated columns
-                    * (see CheckPartitionVirtualGeneratedExprs).
+                    * parent.  We don't check the expression itself here;
+                    * CheckPartitionVirtualGeneratedExprs will do so.


-- 
Álvaro Herrera        Breisgau, Deutschland  —  https://www.EnterpriseDB.com/






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

* Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned
  2026-10-10 00:23 pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Richard Guo <rguo@postgresql.org>
  2026-10-13 12:42 ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-10-13 14:34   ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Richard Guo <guofenglinux@gmail.com>
  2026-10-13 15:41     ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-10-13 16:00       ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-10-14 04:39         ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-10-26 17:40           ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Manu <manuelreyesbravo@gmail.com>
  2026-10-27 03:10             ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-11-11 15:41               ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-11-11 15:47                 ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
@ 2026-11-12 04:36                   ` shihao zhong <zhong950419@gmail.com>
  2026-11-14 01:12                     ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Manu <manuelreyesbravo@gmail.com>
  2026-11-21 11:31                     ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  0 siblings, 2 replies; 24+ messages in thread

From: shihao zhong @ 2026-11-12 04:36 UTC (permalink / raw)
  To: Álvaro Herrera <alvherre@kurilemu.de>; +Cc: Manu <manuelreyesbravo@gmail.com>; Richard Guo <guofenglinux@gmail.com>; Richard Guo <rguo@postgresql.org>; pgsql-hackers@lists.postgresql.org

Hi Álvaro,

Thanks for both rewrites. v3 follows your suggestion for doc and comment.

> "I'm impressed how quickly you are fixing this obscure issue. I came from
> MS SQL and it would be hard for me to put into words how much of a better
job
> you all are doing on [PostgreSQL]."

Also, just curious. Your emails often end with a nice quote. Does a tool
pick those for you?

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

v3-0001-Require-partitions-to-use-the-parent-s-virtual-gener.patch (application/octet-stream, 29.1K) download From 0c43177ee5355182439dfe4e811fdf0a7ddd83d3 Mon Sep 17 00:00:00 2001 From: shihao zhong <zhong950419@gmail.com> Date: Tue, 13 Oct 2026 23:22:52 -0400 Subject: [PATCH] Require partitions to use the parent's virtual generation expression MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Otherwise a NOT NULL column can read as NULL through the parent. Suggested-by: Álvaro Herrera <alvherre@kurilemu.de> Discussion: https://postgr.es/m/E1xFKs5-0000000116b-2Cge@gemulon.postgresql.org --- doc/src/sgml/ddl.sgml | 7 +- doc/src/sgml/ref/alter_table.sgml | 3 + src/backend/commands/tablecmds.c | 114 +++++++++++++++++- src/bin/pg_upgrade/check.c | 73 +++++++++++ .../regress/expected/generated_virtual.out | 110 +++++++---------- src/test/regress/sql/generated_virtual.sql | 44 +++---- 6 files changed, 258 insertions(+), 93 deletions(-) diff --git a/doc/src/sgml/ddl.sgml b/doc/src/sgml/ddl.sgml index d78d986756e..e8489824f9d 100644 --- a/doc/src/sgml/ddl.sgml +++ b/doc/src/sgml/ddl.sgml @@ -451,8 +451,11 @@ CREATE TABLE people ( <listitem> <para> If a parent column is a generated column, its child column must also - be a generated column of the same kind (stored or virtual); however, - the child column can have a different generation expression. + be a generated column of the same kind (stored or virtual). + In addition, for virtual generated columns of a partition, the + generation expression must be identical to that of the partitioned + table. In all other cases, the child column can have a different + generation expression. </para> <para> diff --git a/doc/src/sgml/ref/alter_table.sgml b/doc/src/sgml/ref/alter_table.sgml index 0f9d698d170..d4156cc4253 100644 --- a/doc/src/sgml/ref/alter_table.sgml +++ b/doc/src/sgml/ref/alter_table.sgml @@ -276,6 +276,9 @@ WITH ( MODULUS <replaceable class="parameter">numeric_literal</replaceable>, REM Replacing the expression of a virtual generated column does not require a table rewrite, but if the column is used in a constraint, the table will be scanned to check that existing rows meet the constraint. + The expression of a virtual generated column cannot be changed for a + partition alone, or with <literal>ONLY</literal> for a partitioned table + that has partitions. </para> <para> diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index aa89c9a4637..8aa738e0947 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -383,6 +383,7 @@ static List *MergeCheckConstraint(List *constraints, const char *name, Node *exp static void MergeChildAttribute(List *inh_columns, int exist_attno, int newcol_attno, const ColumnDef *newdef); static ColumnDef *MergeInheritedAttribute(List *inh_columns, int exist_attno, const ColumnDef *newdef); static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispartition); +static void CheckPartitionVirtualGeneratedExprs(Relation partrel, Relation parentrel); static void MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel); static void StoreCatalogInheritance(Oid relationId, List *supers, bool child_is_partition); @@ -553,6 +554,7 @@ static ObjectAddress ATExecDropIdentity(Relation rel, const char *colName, bool bool recurse, bool recursing); static ObjectAddress ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName, Node *newExpr, LOCKMODE lockmode); +static void ATPrepSetExpression(Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing); static void ATPrepDropExpression(Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode); static ObjectAddress ATExecDropExpression(Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode); static ObjectAddress ATExecSetStatistics(Relation rel, const char *colName, int16 colNum, @@ -1175,6 +1177,8 @@ DefineRelation(CreateStmt *stmt, char relkind, Oid ownerId, errmsg("\"%s\" is not partitioned", RelationGetRelationName(parent)))); + CheckPartitionVirtualGeneratedExprs(rel, parent); + /* * The partition constraint of the default partition depends on the * partition bounds of every other partition. It is possible that @@ -3109,8 +3113,8 @@ MergeAttributes(List *columns, const List *supers, char relpersistence, * Check for conflicts related to generated columns. * * Same rules as above: generated-ness has to match the - * parent, but the contents of the generation expression - * can be different. + * parent. We don't check the expression itself here; + * CheckPartitionVirtualGeneratedExprs will do so. */ if (coldef->generated) { @@ -5100,6 +5104,7 @@ ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd, case AT_SetExpression: /* ALTER COLUMN SET EXPRESSION */ ATSimplePermissions(cmd->subtype, rel, ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE); + ATPrepSetExpression(rel, cmd, recurse, recursing); ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context); pass = AT_PASS_SET_EXPRESSION; break; @@ -9409,6 +9414,45 @@ ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName, return address; } +/* + * ALTER TABLE ALTER COLUMN SET EXPRESSION + * + * The expression of a virtual generated column can only be changed for a + * whole partition tree. See CheckPartitionVirtualGeneratedExprs. + */ +static void +ATPrepSetExpression(Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing) +{ + HeapTuple tuple; + char attgenerated; + + if (recursing) + return; + + tuple = SearchSysCacheAttName(RelationGetRelid(rel), cmd->name); + if (!HeapTupleIsValid(tuple)) + return; /* error will be reported later */ + attgenerated = ((Form_pg_attribute) GETSTRUCT(tuple))->attgenerated; + ReleaseSysCache(tuple); + + if (attgenerated != ATTRIBUTE_GENERATED_VIRTUAL) + return; + + if (rel->rd_rel->relispartition) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("cannot alter generation expression of virtual generated column \"%s\" of partition \"%s\"", + cmd->name, RelationGetRelationName(rel)), + errhint("Alter the generation expression of the partitioned table instead."))); + + if (!recurse && + rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE && + find_inheritance_children(RelationGetRelid(rel), NoLock) != NIL) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("ALTER TABLE / SET EXPRESSION must be applied to child tables too"))); +} + /* * ALTER TABLE ALTER COLUMN DROP EXPRESSION */ @@ -18850,7 +18894,9 @@ constraints_equivalent(HeapTuple a, HeapTuple b, TupleDesc tupleDesc) * partitioned tables it's a foot-gun. * * The data type must match exactly. If the parent column is NOT NULL then - * the child must be as well. Defaults are not compared, however. + * the child must be as well. Defaults are not compared, however, and neither + * are generation expressions, except for virtual generated columns of a + * partition. */ static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispartition) @@ -18971,6 +19017,68 @@ MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispart } table_close(attrrel, RowExclusiveLock); + + if (ispartition) + CheckPartitionVirtualGeneratedExprs(child_rel, parent_rel); +} + +/* + * CheckPartitionVirtualGeneratedExprs + * Check that each virtual generated column of a partition has the same + * generation expression as in the partitioned table. + * + * Reading through the partitioned table computes the parent's expression, + * while constraints on the partition are checked with its own, so they must + * be the same. + */ +static void +CheckPartitionVirtualGeneratedExprs(Relation partrel, Relation parentrel) +{ + TupleDesc parent_desc = RelationGetDescr(parentrel); + TupleDesc part_desc = RelationGetDescr(partrel); + AttrMap *attmap; + + if (parent_desc->constr == NULL || + !parent_desc->constr->has_generated_virtual) + return; + + attmap = build_attrmap_by_name(part_desc, parent_desc, false); + + for (AttrNumber parent_attno = 1; parent_attno <= parent_desc->natts; parent_attno++) + { + Form_pg_attribute parent_att = TupleDescAttr(parent_desc, parent_attno - 1); + AttrNumber part_attno; + Node *parent_expr; + Node *part_expr; + bool found_whole_row; + + if (parent_att->attisdropped || + parent_att->attgenerated != ATTRIBUTE_GENERATED_VIRTUAL) + continue; + + part_attno = attmap->attnums[parent_attno - 1]; + Assert(part_attno > 0); + + parent_expr = TupleDescGetDefault(parent_desc, parent_attno); + part_expr = TupleDescGetDefault(part_desc, part_attno); + if (parent_expr == NULL || part_expr == NULL) + elog(ERROR, "missing generation expression for column \"%s\"", + NameStr(parent_att->attname)); + + parent_expr = map_variable_attnos(parent_expr, 1, 0, attmap, + InvalidOid, &found_whole_row); + /* generation expressions cannot contain whole-row Vars */ + Assert(!found_whole_row); + + if (!equal(parent_expr, part_expr)) + ereport(ERROR, + (errcode(ERRCODE_INVALID_COLUMN_DEFINITION), + errmsg("virtual generated column \"%s\" of partition \"%s\" must have the same generation expression as the partitioned table", + NameStr(parent_att->attname), + RelationGetRelationName(partrel)))); + } + + free_attrmap(attmap); } /* diff --git a/src/bin/pg_upgrade/check.c b/src/bin/pg_upgrade/check.c index 2d4aaf22a0f..97a8f7dfe6b 100644 --- a/src/bin/pg_upgrade/check.c +++ b/src/bin/pg_upgrade/check.c @@ -29,6 +29,7 @@ static void check_for_user_defined_postfix_ops(ClusterInfo *cluster); static void check_for_incompatible_polymorphics(ClusterInfo *cluster); static void check_for_tables_with_oids(ClusterInfo *cluster); static void check_for_not_null_inheritance(ClusterInfo *cluster); +static void check_for_partition_virtual_generated_exprs(ClusterInfo *cluster); static void check_for_gist_inet_ops(ClusterInfo *cluster); static void check_for_new_tablespace_dir(void); static void check_for_user_defined_encoding_conversions(ClusterInfo *cluster); @@ -673,6 +674,15 @@ check_and_dump_old_cluster(void) if (GET_MAJOR_VERSION(old_cluster.major_version) <= 1800) check_for_not_null_inheritance(&old_cluster); + /* + * Virtual generated columns (new in PG 18) of a partition used to be + * allowed to have a different generation expression than the partitioned + * table, but schema restore fails for them now. Verify there are none. + */ + if (GET_MAJOR_VERSION(old_cluster.major_version) >= 1800 && + GET_MAJOR_VERSION(old_cluster.major_version) <= 1900) + check_for_partition_virtual_generated_exprs(&old_cluster); + /* * The btree_gist extension contains gist_inet_ops and gist_cidr_ops * opclasses that do not reliably give correct answers. We want to @@ -1733,6 +1743,69 @@ check_for_not_null_inheritance(ClusterInfo *cluster) check_ok(); } +/* + * check_for_partition_virtual_generated_exprs() + * + * A virtual generated column of a partition must have the same generation + * expression as the partitioned table. Check that the cluster to be upgraded + * has no partitions that differ, which older versions allowed. + */ +static void +check_for_partition_virtual_generated_exprs(ClusterInfo *cluster) +{ + UpgradeTaskReport report; + UpgradeTask *task; + const char *query; + + prep_status("Checking for virtual generated column inconsistencies"); + + report.file = NULL; + snprintf(report.path, sizeof(report.path), "%s/%s", + log_opts.basedir, + "partition_virtual_generated_columns.txt"); + + query = "SELECT nc.nspname, cc.relname, ac.attname " + "FROM pg_catalog.pg_class cc " + " JOIN pg_catalog.pg_namespace nc ON nc.oid = cc.relnamespace " + " JOIN pg_catalog.pg_inherits i ON i.inhrelid = cc.oid " + " JOIN pg_catalog.pg_attribute ac ON ac.attrelid = cc.oid " + " JOIN pg_catalog.pg_attribute ap ON ap.attrelid = i.inhparent " + " AND ap.attname = ac.attname " + " JOIN pg_catalog.pg_attrdef dc ON dc.adrelid = ac.attrelid " + " AND dc.adnum = ac.attnum " + " JOIN pg_catalog.pg_attrdef dp ON dp.adrelid = ap.attrelid " + " AND dp.adnum = ap.attnum " + "WHERE cc.relispartition AND ac.attgenerated = 'v' " + " AND pg_catalog.pg_get_expr(dc.adbin, dc.adrelid) <> " + " pg_catalog.pg_get_expr(dp.adbin, dp.adrelid)"; + + task = upgrade_task_create(); + /* the not-null check's callback reports the same columns */ + upgrade_task_add_step(task, query, + process_inconsistent_notnull, + true, &report); + upgrade_task_run(task, cluster); + upgrade_task_free(task); + + if (report.file) + { + fclose(report.file); + pg_log(PG_REPORT, "fatal"); + pg_fatal("Your installation contains partitions whose virtual generated columns\n" + "have a different generation expression than the partitioned table.\n" + "This is no longer allowed, so the upgrade would fail. You can fix\n" + "this by running\n" + " ALTER TABLE parent ALTER COLUMN column SET EXPRESSION AS (...);\n" + "on the partitioned table of each column. In version 18 this is not\n" + "allowed on a table with CHECK constraints, so drop them first and\n" + "add them back afterwards. A list of the problem columns is in the\n" + "file:\n" + " %s", report.path); + } + else + check_ok(); +} + /* * Callback function for processing results of query for * check_for_gist_inet_ops()'s UpgradeTask. If the query returned any rows diff --git a/src/test/regress/expected/generated_virtual.out b/src/test/regress/expected/generated_virtual.out index b14e10fb5a0..9483cdb1857 100644 --- a/src/test/regress/expected/generated_virtual.out +++ b/src/test/regress/expected/generated_virtual.out @@ -912,7 +912,11 @@ CREATE TABLE gtest_parent (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWA CREATE TABLE gtest_child PARTITION OF gtest_parent FOR VALUES FROM ('2016-07-01') TO ('2016-08-01'); -- inherits gen expr CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( - f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- overrides gen expr + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- error, must match parent +) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); +ERROR: virtual generated column "f3" of partition "gtest_child2" must have the same generation expression as the partitioned table +CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 2) VIRTUAL -- same as parent, ok ) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); CREATE TABLE gtest_child3 PARTITION OF gtest_parent ( f3 DEFAULT 42 -- error @@ -946,6 +950,11 @@ ERROR: column "f3" inherits from generated column of different kind DETAIL: Parent column is VIRTUAL, child column is STORED. DROP TABLE gtest_child3; CREATE TABLE gtest_child3 (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWAYS AS (f2 * 33) VIRTUAL); +ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); -- error +ERROR: virtual generated column "f3" of partition "gtest_child3" must have the same generation expression as the partitioned table +DROP TABLE gtest_child3; +-- different column order, so the parent's expression has to be mapped +CREATE TABLE gtest_child3 (f3 bigint GENERATED ALWAYS AS (f2 * 2) VIRTUAL, f2 bigint, f1 date NOT NULL); ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); \d gtest_child Table "generated_virtual_tests.gtest_child" @@ -957,21 +966,21 @@ ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09 Partition of: gtest_parent FOR VALUES FROM ('07-01-2016') TO ('08-01-2016') \d gtest_child2 - Table "generated_virtual_tests.gtest_child2" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- + Table "generated_virtual_tests.gtest_child2" + Column | Type | Collation | Nullable | Default +--------+--------+-----------+----------+------------------------------ f1 | date | | not null | f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 22) + f3 | bigint | | | generated always as (f2 * 2) Partition of: gtest_parent FOR VALUES FROM ('08-01-2016') TO ('09-01-2016') \d gtest_child3 - Table "generated_virtual_tests.gtest_child3" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | + Table "generated_virtual_tests.gtest_child3" + Column | Type | Collation | Nullable | Default +--------+--------+-----------+----------+------------------------------ + f3 | bigint | | | generated always as (f2 * 2) f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 33) + f1 | date | | not null | Partition of: gtest_parent FOR VALUES FROM ('09-01-2016') TO ('10-01-2016') INSERT INTO gtest_parent (f1, f2) VALUES ('2016-07-15', 1); @@ -992,14 +1001,14 @@ SELECT tableoid::regclass, * FROM gtest_child ORDER BY 1, 2, 3; gtest_child | 07-15-2016 | 2 | 4 (2 rows) -SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; -- uses child's generation expression, not parent's +SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; tableoid | f1 | f2 | f3 --------------+------------+----+---- - gtest_child2 | 08-15-2016 | 3 | 66 + gtest_child2 | 08-15-2016 | 3 | 6 (1 row) SELECT tableoid::regclass, * FROM gtest_child3 ORDER BY 1, 2, 3; - tableoid | f1 | f2 | f3 + tableoid | f3 | f2 | f1 ----------+----+----+---- (0 rows) @@ -1012,46 +1021,14 @@ SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; gtest_child3 | 09-13-2016 | 1 | 2 (3 rows) --- alter only parent's and one child's generation expression -ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -\d gtest_parent - Partitioned table "generated_virtual_tests.gtest_parent" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------ - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 4) -Partition key: RANGE (f1) -Number of partitions: 3 (Use \d+ to list them.) - -\d gtest_child - Table "generated_virtual_tests.gtest_child" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 10) -Partition of: gtest_parent FOR VALUES FROM ('07-01-2016') TO ('08-01-2016') - -\d gtest_child2 - Table "generated_virtual_tests.gtest_child2" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 22) -Partition of: gtest_parent FOR VALUES FROM ('08-01-2016') TO ('09-01-2016') - -\d gtest_child3 - Table "generated_virtual_tests.gtest_child3" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 33) -Partition of: gtest_parent FOR VALUES FROM ('09-01-2016') TO ('10-01-2016') - +-- cannot alter only parent's or one partition's generation expression +ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -- error +ERROR: ALTER TABLE / SET EXPRESSION must be applied to child tables too +ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -- error +ERROR: cannot alter generation expression of virtual generated column "f3" of partition "gtest_child" +HINT: Alter the generation expression of the partitioned table instead. +-- alter generation expression of parent and all its children altogether +ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; tableoid | f1 | f2 | f3 --------------+------------+----+---- @@ -1060,16 +1037,10 @@ SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; gtest_child3 | 09-13-2016 | 1 | 4 (3 rows) --- check constraint was validated based on each partitions's generation expression -ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 19); -- error -ERROR: check constraint "cc1" of relation "gtest_child" is violated by some row -ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 66); -- error +ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 12); -- error ERROR: check constraint "cc1" of relation "gtest_child2" is violated by some row -ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 <> 33); -- error -ERROR: check constraint "cc1" of relation "gtest_child3" is violated by some row -ALTER TABLE gtest_parent ADD CONSTRAINT cc CHECK (f3 < 67); -- ok +ALTER TABLE gtest_parent ADD CONSTRAINT cc CHECK (f3 < 13); -- ok ALTER TABLE gtest_parent DROP CONSTRAINT cc; --- alter generation expression of parent and all its children altogether ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 2); \d gtest_parent Partitioned table "generated_virtual_tests.gtest_parent" @@ -1103,9 +1074,9 @@ Partition of: gtest_parent FOR VALUES FROM ('08-01-2016') TO ('09-01-2016') Table "generated_virtual_tests.gtest_child3" Column | Type | Collation | Nullable | Default --------+--------+-----------+----------+------------------------------ - f1 | date | | not null | - f2 | bigint | | | f3 | bigint | | | generated always as (f2 * 2) + f2 | bigint | | | + f1 | date | | not null | Partition of: gtest_parent FOR VALUES FROM ('09-01-2016') TO ('10-01-2016') SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; @@ -1894,11 +1865,16 @@ select * from gtest_cursor order by id; commit; drop table gtest_cursor; --- NOT NULL on a partitioned table's virtual column does not prove non-nullness, --- because a partition can have a different generation expression +-- a partition cannot have a different generation expression, which would let +-- the partitioned table's NOT NULL virtual column read as NULL CREATE TABLE gtestnn_parent2 (a int NOT NULL, b int GENERATED ALWAYS AS (nullif(a, 0)) VIRTUAL NOT NULL) PARTITION BY LIST (a); -CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 (b GENERATED ALWAYS AS (a + 1) VIRTUAL) FOR VALUES IN (0); -INSERT INTO gtestnn_parent2 VALUES (0); +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 (b GENERATED ALWAYS AS (a + 1) VIRTUAL) FOR VALUES IN (0); -- error +ERROR: virtual generated column "b" of partition "gtestnn_child2" must have the same generation expression as the partitioned table +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 FOR VALUES IN (0, 1); +INSERT INTO gtestnn_parent2 VALUES (0); -- error +ERROR: null value in column "b" of relation "gtestnn_child2" violates not-null constraint +DETAIL: Failing row contains (0, virtual). +INSERT INTO gtestnn_parent2 VALUES (1); EXPLAIN (COSTS OFF) SELECT a FROM gtestnn_parent2 WHERE a NOT IN (SELECT b FROM gtestnn_parent2); QUERY PLAN diff --git a/src/test/regress/sql/generated_virtual.sql b/src/test/regress/sql/generated_virtual.sql index e62880f941a..c13ff5eb4c6 100644 --- a/src/test/regress/sql/generated_virtual.sql +++ b/src/test/regress/sql/generated_virtual.sql @@ -529,7 +529,10 @@ CREATE TABLE gtest_parent (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWA CREATE TABLE gtest_child PARTITION OF gtest_parent FOR VALUES FROM ('2016-07-01') TO ('2016-08-01'); -- inherits gen expr CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( - f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- overrides gen expr + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- error, must match parent +) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); +CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 2) VIRTUAL -- same as parent, ok ) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); CREATE TABLE gtest_child3 PARTITION OF gtest_parent ( f3 DEFAULT 42 -- error @@ -553,6 +556,10 @@ CREATE TABLE gtest_child3 (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWA ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); -- error DROP TABLE gtest_child3; CREATE TABLE gtest_child3 (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWAYS AS (f2 * 33) VIRTUAL); +ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); -- error +DROP TABLE gtest_child3; +-- different column order, so the parent's expression has to be mapped +CREATE TABLE gtest_child3 (f3 bigint GENERATED ALWAYS AS (f2 * 2) VIRTUAL, f2 bigint, f1 date NOT NULL); ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); \d gtest_child \d gtest_child2 @@ -562,28 +569,21 @@ INSERT INTO gtest_parent (f1, f2) VALUES ('2016-07-15', 2); INSERT INTO gtest_parent (f1, f2) VALUES ('2016-08-15', 3); SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; SELECT tableoid::regclass, * FROM gtest_child ORDER BY 1, 2, 3; -SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; -- uses child's generation expression, not parent's +SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; SELECT tableoid::regclass, * FROM gtest_child3 ORDER BY 1, 2, 3; UPDATE gtest_parent SET f1 = f1 + 60 WHERE f2 = 1; SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; --- alter only parent's and one child's generation expression -ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -\d gtest_parent -\d gtest_child -\d gtest_child2 -\d gtest_child3 -SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; - --- check constraint was validated based on each partitions's generation expression -ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 19); -- error -ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 66); -- error -ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 <> 33); -- error -ALTER TABLE gtest_parent ADD CONSTRAINT cc CHECK (f3 < 67); -- ok -ALTER TABLE gtest_parent DROP CONSTRAINT cc; +-- cannot alter only parent's or one partition's generation expression +ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -- error +ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -- error -- alter generation expression of parent and all its children altogether +ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); +SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; +ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 12); -- error +ALTER TABLE gtest_parent ADD CONSTRAINT cc CHECK (f3 < 13); -- ok +ALTER TABLE gtest_parent DROP CONSTRAINT cc; ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 2); \d gtest_parent \d gtest_child @@ -1012,11 +1012,13 @@ commit; drop table gtest_cursor; --- NOT NULL on a partitioned table's virtual column does not prove non-nullness, --- because a partition can have a different generation expression +-- a partition cannot have a different generation expression, which would let +-- the partitioned table's NOT NULL virtual column read as NULL CREATE TABLE gtestnn_parent2 (a int NOT NULL, b int GENERATED ALWAYS AS (nullif(a, 0)) VIRTUAL NOT NULL) PARTITION BY LIST (a); -CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 (b GENERATED ALWAYS AS (a + 1) VIRTUAL) FOR VALUES IN (0); -INSERT INTO gtestnn_parent2 VALUES (0); +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 (b GENERATED ALWAYS AS (a + 1) VIRTUAL) FOR VALUES IN (0); -- error +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 FOR VALUES IN (0, 1); +INSERT INTO gtestnn_parent2 VALUES (0); -- error +INSERT INTO gtestnn_parent2 VALUES (1); EXPLAIN (COSTS OFF) SELECT a FROM gtestnn_parent2 WHERE a NOT IN (SELECT b FROM gtestnn_parent2); SELECT a FROM gtestnn_parent2 WHERE a NOT IN (SELECT b FROM gtestnn_parent2); -- 2.37.1 (Apple Git-137.1)
nocfbot-v3-REL_18-0001-Require-partitions-to-use-the-parent-s-virtual-gen.patch (application/octet-stream, 23.3K) download From 835821a729e595e002f8a92a415154d368821e61 Mon Sep 17 00:00:00 2001 From: shihao zhong <zhong950419@gmail.com> Date: Wed, 11 Nov 2026 23:00:18 -0500 Subject: [PATCH v3 REL_18] Require partitions to use the parent's virtual generation expression MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Otherwise a NOT NULL column can read as NULL through the parent. Suggested-by: Álvaro Herrera <alvherre@kurilemu.de> Discussion: https://postgr.es/m/E1xFKs5-0000000116b-2Cge@gemulon.postgresql.org --- doc/src/sgml/ddl.sgml | 7 +- doc/src/sgml/ref/alter_table.sgml | 3 + src/backend/commands/tablecmds.c | 114 +++++++++++++++++- .../regress/expected/generated_virtual.out | 109 ++++++++--------- src/test/regress/sql/generated_virtual.sql | 37 ++++-- 5 files changed, 199 insertions(+), 71 deletions(-) diff --git a/doc/src/sgml/ddl.sgml b/doc/src/sgml/ddl.sgml index ddd7096f6b2..40c66370a3c 100644 --- a/doc/src/sgml/ddl.sgml +++ b/doc/src/sgml/ddl.sgml @@ -451,8 +451,11 @@ CREATE TABLE people ( <listitem> <para> If a parent column is a generated column, its child column must also - be a generated column of the same kind (stored or virtual); however, - the child column can have a different generation expression. + be a generated column of the same kind (stored or virtual). + In addition, for virtual generated columns of a partition, the + generation expression must be identical to that of the partitioned + table. In all other cases, the child column can have a different + generation expression. </para> <para> diff --git a/doc/src/sgml/ref/alter_table.sgml b/doc/src/sgml/ref/alter_table.sgml index 31f2d91418b..d6a009a54a3 100644 --- a/doc/src/sgml/ref/alter_table.sgml +++ b/doc/src/sgml/ref/alter_table.sgml @@ -272,6 +272,9 @@ WITH ( MODULUS <replaceable class="parameter">numeric_literal</replaceable>, REM This form replaces the expression of a generated column. Existing data in a stored generated column is rewritten and all the future changes will apply the new generation expression. + The expression of a virtual generated column cannot be changed for a + partition alone, or with <literal>ONLY</literal> for a partitioned table + that has partitions. </para> <para> diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 5059909833e..6c3d2c81a9c 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -378,6 +378,7 @@ static List *MergeCheckConstraint(List *constraints, const char *name, Node *exp static void MergeChildAttribute(List *inh_columns, int exist_attno, int newcol_attno, const ColumnDef *newdef); static ColumnDef *MergeInheritedAttribute(List *inh_columns, int exist_attno, const ColumnDef *newdef); static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispartition); +static void CheckPartitionVirtualGeneratedExprs(Relation partrel, Relation parentrel); static void MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel); static void StoreCatalogInheritance(Oid relationId, List *supers, bool child_is_partition); @@ -522,6 +523,7 @@ static ObjectAddress ATExecDropIdentity(Relation rel, const char *colName, bool bool recurse, bool recursing); static ObjectAddress ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName, Node *newExpr, LOCKMODE lockmode); +static void ATPrepSetExpression(Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing); static void ATPrepDropExpression(Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode); static ObjectAddress ATExecDropExpression(Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode); static ObjectAddress ATExecSetStatistics(Relation rel, const char *colName, int16 colNum, @@ -1142,6 +1144,8 @@ DefineRelation(CreateStmt *stmt, char relkind, Oid ownerId, errmsg("\"%s\" is not partitioned", RelationGetRelationName(parent)))); + CheckPartitionVirtualGeneratedExprs(rel, parent); + /* * The partition constraint of the default partition depends on the * partition bounds of every other partition. It is possible that @@ -3058,8 +3062,8 @@ MergeAttributes(List *columns, const List *supers, char relpersistence, * Check for conflicts related to generated columns. * * Same rules as above: generated-ness has to match the - * parent, but the contents of the generation expression - * can be different. + * parent. We don't check the expression itself here; + * CheckPartitionVirtualGeneratedExprs will do so. */ if (coldef->generated) { @@ -5036,6 +5040,7 @@ ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd, case AT_SetExpression: /* ALTER COLUMN SET EXPRESSION */ ATSimplePermissions(cmd->subtype, rel, ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE); + ATPrepSetExpression(rel, cmd, recurse, recursing); ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context); pass = AT_PASS_SET_EXPRESSION; break; @@ -8774,6 +8779,45 @@ ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName, return address; } +/* + * ALTER TABLE ALTER COLUMN SET EXPRESSION + * + * The expression of a virtual generated column can only be changed for a + * whole partition tree. See CheckPartitionVirtualGeneratedExprs. + */ +static void +ATPrepSetExpression(Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing) +{ + HeapTuple tuple; + char attgenerated; + + if (recursing) + return; + + tuple = SearchSysCacheAttName(RelationGetRelid(rel), cmd->name); + if (!HeapTupleIsValid(tuple)) + return; /* error will be reported later */ + attgenerated = ((Form_pg_attribute) GETSTRUCT(tuple))->attgenerated; + ReleaseSysCache(tuple); + + if (attgenerated != ATTRIBUTE_GENERATED_VIRTUAL) + return; + + if (rel->rd_rel->relispartition) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("cannot alter generation expression of virtual generated column \"%s\" of partition \"%s\"", + cmd->name, RelationGetRelationName(rel)), + errhint("Alter the generation expression of the partitioned table instead."))); + + if (!recurse && + rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE && + find_inheritance_children(RelationGetRelid(rel), NoLock) != NIL) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("ALTER TABLE / SET EXPRESSION must be applied to child tables too"))); +} + /* * ALTER TABLE ALTER COLUMN DROP EXPRESSION */ @@ -17551,7 +17595,9 @@ constraints_equivalent(HeapTuple a, HeapTuple b, TupleDesc tupleDesc) * partitioned tables it's a foot-gun. * * The data type must match exactly. If the parent column is NOT NULL then - * the child must be as well. Defaults are not compared, however. + * the child must be as well. Defaults are not compared, however, and neither + * are generation expressions, except for virtual generated columns of a + * partition. */ static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispartition) @@ -17672,6 +17718,68 @@ MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispart } table_close(attrrel, RowExclusiveLock); + + if (ispartition) + CheckPartitionVirtualGeneratedExprs(child_rel, parent_rel); +} + +/* + * CheckPartitionVirtualGeneratedExprs + * Check that each virtual generated column of a partition has the same + * generation expression as in the partitioned table. + * + * Reading through the partitioned table computes the parent's expression, + * while constraints on the partition are checked with its own, so they must + * be the same. + */ +static void +CheckPartitionVirtualGeneratedExprs(Relation partrel, Relation parentrel) +{ + TupleDesc parent_desc = RelationGetDescr(parentrel); + TupleDesc part_desc = RelationGetDescr(partrel); + AttrMap *attmap; + + if (parent_desc->constr == NULL || + !parent_desc->constr->has_generated_virtual) + return; + + attmap = build_attrmap_by_name(part_desc, parent_desc, false); + + for (AttrNumber parent_attno = 1; parent_attno <= parent_desc->natts; parent_attno++) + { + Form_pg_attribute parent_att = TupleDescAttr(parent_desc, parent_attno - 1); + AttrNumber part_attno; + Node *parent_expr; + Node *part_expr; + bool found_whole_row; + + if (parent_att->attisdropped || + parent_att->attgenerated != ATTRIBUTE_GENERATED_VIRTUAL) + continue; + + part_attno = attmap->attnums[parent_attno - 1]; + Assert(part_attno > 0); + + parent_expr = TupleDescGetDefault(parent_desc, parent_attno); + part_expr = TupleDescGetDefault(part_desc, part_attno); + if (parent_expr == NULL || part_expr == NULL) + elog(ERROR, "missing generation expression for column \"%s\"", + NameStr(parent_att->attname)); + + parent_expr = map_variable_attnos(parent_expr, 1, 0, attmap, + InvalidOid, &found_whole_row); + /* generation expressions cannot contain whole-row Vars */ + Assert(!found_whole_row); + + if (!equal(parent_expr, part_expr)) + ereport(ERROR, + (errcode(ERRCODE_INVALID_COLUMN_DEFINITION), + errmsg("virtual generated column \"%s\" of partition \"%s\" must have the same generation expression as the partitioned table", + NameStr(parent_att->attname), + RelationGetRelationName(partrel)))); + } + + free_attrmap(attmap); } /* diff --git a/src/test/regress/expected/generated_virtual.out b/src/test/regress/expected/generated_virtual.out index 03698488907..6108fce2ae4 100644 --- a/src/test/regress/expected/generated_virtual.out +++ b/src/test/regress/expected/generated_virtual.out @@ -882,7 +882,11 @@ CREATE TABLE gtest_parent (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWA CREATE TABLE gtest_child PARTITION OF gtest_parent FOR VALUES FROM ('2016-07-01') TO ('2016-08-01'); -- inherits gen expr CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( - f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- overrides gen expr + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- error, must match parent +) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); +ERROR: virtual generated column "f3" of partition "gtest_child2" must have the same generation expression as the partitioned table +CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 2) VIRTUAL -- same as parent, ok ) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); CREATE TABLE gtest_child3 PARTITION OF gtest_parent ( f3 DEFAULT 42 -- error @@ -916,6 +920,11 @@ ERROR: column "f3" inherits from generated column of different kind DETAIL: Parent column is VIRTUAL, child column is STORED. DROP TABLE gtest_child3; CREATE TABLE gtest_child3 (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWAYS AS (f2 * 33) VIRTUAL); +ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); -- error +ERROR: virtual generated column "f3" of partition "gtest_child3" must have the same generation expression as the partitioned table +DROP TABLE gtest_child3; +-- different column order, so the parent's expression has to be mapped +CREATE TABLE gtest_child3 (f3 bigint GENERATED ALWAYS AS (f2 * 2) VIRTUAL, f2 bigint, f1 date NOT NULL); ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); \d gtest_child Table "generated_virtual_tests.gtest_child" @@ -927,21 +936,21 @@ ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09 Partition of: gtest_parent FOR VALUES FROM ('07-01-2016') TO ('08-01-2016') \d gtest_child2 - Table "generated_virtual_tests.gtest_child2" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- + Table "generated_virtual_tests.gtest_child2" + Column | Type | Collation | Nullable | Default +--------+--------+-----------+----------+------------------------------ f1 | date | | not null | f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 22) + f3 | bigint | | | generated always as (f2 * 2) Partition of: gtest_parent FOR VALUES FROM ('08-01-2016') TO ('09-01-2016') \d gtest_child3 - Table "generated_virtual_tests.gtest_child3" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | + Table "generated_virtual_tests.gtest_child3" + Column | Type | Collation | Nullable | Default +--------+--------+-----------+----------+------------------------------ + f3 | bigint | | | generated always as (f2 * 2) f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 33) + f1 | date | | not null | Partition of: gtest_parent FOR VALUES FROM ('09-01-2016') TO ('10-01-2016') INSERT INTO gtest_parent (f1, f2) VALUES ('2016-07-15', 1); @@ -962,14 +971,14 @@ SELECT tableoid::regclass, * FROM gtest_child ORDER BY 1, 2, 3; gtest_child | 07-15-2016 | 2 | 4 (2 rows) -SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; -- uses child's generation expression, not parent's +SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; tableoid | f1 | f2 | f3 --------------+------------+----+---- - gtest_child2 | 08-15-2016 | 3 | 66 + gtest_child2 | 08-15-2016 | 3 | 6 (1 row) SELECT tableoid::regclass, * FROM gtest_child3 ORDER BY 1, 2, 3; - tableoid | f1 | f2 | f3 + tableoid | f3 | f2 | f1 ----------+----+----+---- (0 rows) @@ -982,46 +991,14 @@ SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; gtest_child3 | 09-13-2016 | 1 | 2 (3 rows) --- alter only parent's and one child's generation expression -ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -\d gtest_parent - Partitioned table "generated_virtual_tests.gtest_parent" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------ - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 4) -Partition key: RANGE (f1) -Number of partitions: 3 (Use \d+ to list them.) - -\d gtest_child - Table "generated_virtual_tests.gtest_child" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 10) -Partition of: gtest_parent FOR VALUES FROM ('07-01-2016') TO ('08-01-2016') - -\d gtest_child2 - Table "generated_virtual_tests.gtest_child2" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 22) -Partition of: gtest_parent FOR VALUES FROM ('08-01-2016') TO ('09-01-2016') - -\d gtest_child3 - Table "generated_virtual_tests.gtest_child3" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 33) -Partition of: gtest_parent FOR VALUES FROM ('09-01-2016') TO ('10-01-2016') - +-- cannot alter only parent's or one partition's generation expression +ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -- error +ERROR: ALTER TABLE / SET EXPRESSION must be applied to child tables too +ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -- error +ERROR: cannot alter generation expression of virtual generated column "f3" of partition "gtest_child" +HINT: Alter the generation expression of the partitioned table instead. +-- alter generation expression of parent and all its children altogether +ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; tableoid | f1 | f2 | f3 --------------+------------+----+---- @@ -1030,7 +1007,10 @@ SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; gtest_child3 | 09-13-2016 | 1 | 4 (3 rows) --- alter generation expression of parent and all its children altogether +ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 12); -- error +ERROR: check constraint "cc1" of relation "gtest_child2" is violated by some row +ALTER TABLE gtest_parent ADD CONSTRAINT cc CHECK (f3 < 13); -- ok +ALTER TABLE gtest_parent DROP CONSTRAINT cc; ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 2); \d gtest_parent Partitioned table "generated_virtual_tests.gtest_parent" @@ -1064,9 +1044,9 @@ Partition of: gtest_parent FOR VALUES FROM ('08-01-2016') TO ('09-01-2016') Table "generated_virtual_tests.gtest_child3" Column | Type | Collation | Nullable | Default --------+--------+-----------+----------+------------------------------ - f1 | date | | not null | - f2 | bigint | | | f3 | bigint | | | generated always as (f2 * 2) + f2 | bigint | | | + f1 | date | | not null | Partition of: gtest_parent FOR VALUES FROM ('09-01-2016') TO ('10-01-2016') SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; @@ -1812,3 +1792,20 @@ select * from gtest_cursor order by id; commit; drop table gtest_cursor; +-- a partition cannot have a different generation expression, which would let +-- the partitioned table's NOT NULL virtual column read as NULL +CREATE TABLE gtestnn_parent2 (a int NOT NULL, b int GENERATED ALWAYS AS (nullif(a, 0)) VIRTUAL NOT NULL) PARTITION BY LIST (a); +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 (b GENERATED ALWAYS AS (a + 1) VIRTUAL) FOR VALUES IN (0); -- error +ERROR: virtual generated column "b" of partition "gtestnn_child2" must have the same generation expression as the partitioned table +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 FOR VALUES IN (0, 1); +INSERT INTO gtestnn_parent2 VALUES (0); -- error +ERROR: null value in column "b" of relation "gtestnn_child2" violates not-null constraint +DETAIL: Failing row contains (0, virtual). +INSERT INTO gtestnn_parent2 VALUES (1); +SELECT a, b FROM gtestnn_parent2; + a | b +---+--- + 1 | 1 +(1 row) + +DROP TABLE gtestnn_parent2; diff --git a/src/test/regress/sql/generated_virtual.sql b/src/test/regress/sql/generated_virtual.sql index b1b92b2ced5..d1bbf9352d7 100644 --- a/src/test/regress/sql/generated_virtual.sql +++ b/src/test/regress/sql/generated_virtual.sql @@ -514,7 +514,10 @@ CREATE TABLE gtest_parent (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWA CREATE TABLE gtest_child PARTITION OF gtest_parent FOR VALUES FROM ('2016-07-01') TO ('2016-08-01'); -- inherits gen expr CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( - f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- overrides gen expr + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- error, must match parent +) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); +CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 2) VIRTUAL -- same as parent, ok ) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); CREATE TABLE gtest_child3 PARTITION OF gtest_parent ( f3 DEFAULT 42 -- error @@ -538,6 +541,10 @@ CREATE TABLE gtest_child3 (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWA ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); -- error DROP TABLE gtest_child3; CREATE TABLE gtest_child3 (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWAYS AS (f2 * 33) VIRTUAL); +ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); -- error +DROP TABLE gtest_child3; +-- different column order, so the parent's expression has to be mapped +CREATE TABLE gtest_child3 (f3 bigint GENERATED ALWAYS AS (f2 * 2) VIRTUAL, f2 bigint, f1 date NOT NULL); ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); \d gtest_child \d gtest_child2 @@ -547,21 +554,21 @@ INSERT INTO gtest_parent (f1, f2) VALUES ('2016-07-15', 2); INSERT INTO gtest_parent (f1, f2) VALUES ('2016-08-15', 3); SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; SELECT tableoid::regclass, * FROM gtest_child ORDER BY 1, 2, 3; -SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; -- uses child's generation expression, not parent's +SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; SELECT tableoid::regclass, * FROM gtest_child3 ORDER BY 1, 2, 3; UPDATE gtest_parent SET f1 = f1 + 60 WHERE f2 = 1; SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; --- alter only parent's and one child's generation expression -ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -\d gtest_parent -\d gtest_child -\d gtest_child2 -\d gtest_child3 -SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; +-- cannot alter only parent's or one partition's generation expression +ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -- error +ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -- error -- alter generation expression of parent and all its children altogether +ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); +SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; +ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 12); -- error +ALTER TABLE gtest_parent ADD CONSTRAINT cc CHECK (f3 < 13); -- ok +ALTER TABLE gtest_parent DROP CONSTRAINT cc; ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 2); \d gtest_parent \d gtest_child @@ -969,3 +976,13 @@ select * from gtest_cursor order by id; commit; drop table gtest_cursor; + +-- a partition cannot have a different generation expression, which would let +-- the partitioned table's NOT NULL virtual column read as NULL +CREATE TABLE gtestnn_parent2 (a int NOT NULL, b int GENERATED ALWAYS AS (nullif(a, 0)) VIRTUAL NOT NULL) PARTITION BY LIST (a); +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 (b GENERATED ALWAYS AS (a + 1) VIRTUAL) FOR VALUES IN (0); -- error +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 FOR VALUES IN (0, 1); +INSERT INTO gtestnn_parent2 VALUES (0); -- error +INSERT INTO gtestnn_parent2 VALUES (1); +SELECT a, b FROM gtestnn_parent2; +DROP TABLE gtestnn_parent2; -- 2.37.1 (Apple Git-137.1)
^ permalink raw reply [nested|flat] 24+ messages in thread

* Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned
  2026-10-10 00:23 pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Richard Guo <rguo@postgresql.org>
  2026-10-13 12:42 ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-10-13 14:34   ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Richard Guo <guofenglinux@gmail.com>
  2026-10-13 15:41     ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-10-13 16:00       ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-10-14 04:39         ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-10-26 17:40           ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Manu <manuelreyesbravo@gmail.com>
  2026-10-27 03:10             ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-11-11 15:41               ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-11-11 15:47                 ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-11-12 04:36                   ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
@ 2026-11-14 01:12                     ` Manu <manuelreyesbravo@gmail.com>
  2026-11-15 03:36                       ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  1 sibling, 1 reply; 24+ messages in thread

From: Manu @ 2026-11-14 01:12 UTC (permalink / raw)
  To: shihao zhong <zhong950419@gmail.com>; +Cc: Álvaro Herrera <alvherre@kurilemu.de>; Richard Guo <guofenglinux@gmail.com>; Richard Guo <rguo@postgresql.org>; pgsql-hackers@lists.postgresql.org

Hi Shihao,

On Wed, Nov 11, 2026 at 11:36 PM shihao zhong <zhong950419@gmail.com>
wrote:
> Thanks for both rewrites. v3 follows your suggestion for doc and comment.

v3 works on master (77bba5454f9), REL_19_STABLE (dfffe8da630) and, in
its 18 version, REL_18_STABLE (2ea5222db7c): the 13 divergent
statements of my Oct 26 paths.sql all fail, the controls pass, and so
do make check and, on master and 19, the pg_upgrade TAP tests.  The
new pg_upgrade text falls short in two cases on 18.

On Mon, Oct 26, 2026 at 11:10 PM shihao zhong <zhong950419@gmail.com>
wrote:
> I don't think the logic is wrong here, but maybe we can make some
> improvement to the error message. v2 changes
>
>   on the partitioned table of each column listed in the file
> =>
>   on the partitioned table of each column. In version 18 this is not
>   allowed on a table with CHECK constraints, so drop them first and
>   add them back afterwards. A list of the problem columns is in the
>   file

Sorry for not answering this sooner.  On REL_18_STABLE, with and
without the patch, I did only what the text says, and with the CHECK
on the partitioned table pg_upgrade --check to master and 19 then
passes.  It does not when:

- the CHECK is only on the partition: SET EXPRESSION on the parent
  fails ("not supported for virtual generated columns in tables with
  check constraints"), and the parent has no CHECK to drop;
- the divergent partition is a leaf under a partitioned partition:
  with the 18 patch, SET EXPRESSION on its parent (the middle table)
  fails ("cannot alter ... of partition"); its hint, also on master,
  says to alter the partitioned table, which it is; the root works.

Rows that break NOT NULL or a CHECK under the parent's expression
stop it too, with clear errors.  Maybe:

  on the top-level partitioned table of each column.  In version 18
  this is not allowed if any table in that partition tree has CHECK
  constraints, so drop them first and add them back afterwards.  Rows
  that violate NOT NULL or CHECK with the new expression must be fixed
  first.  A list of the problem columns is in the file:

From unpatched REL_19_STABLE the check fires too, and SET EXPRESSION
on the parent is enough.  The script and its output are attached.

Regards,
Manu

Attachments:

h2.sh.txt (text/plain, 10.0K) download #!/usr/bin/env bash # Follow the v2/v3 pg_upgrade message literally on an old cluster with # partitions whose virtual generated column differs from the parent's. # # Usage: bash h2.sh.txt OLD=<bindir> FIX=<bindir> TARGET=<bindir> [TARGET2=<bindir>] # OLD unpatched server that creates the divergent partitions # FIX server of the same major that runs the fixes (OLD itself, or # the same major with the patch, i.e. after a minor update) # TARGET newer major with the patch: pg_upgrade --check, and the real # pg_upgrade at the end; TARGET2 only gets --check # # One database per case: # case_a CHECK on the parent that does not involve the column # case_b CHECK on the parent that involves the column; the rows meet # it with the partition's expression, not with the parent's # case_c CHECK only on the partition, none on the parent # case_d NOT NULL on the column; a row is NULL with the parent's # expression # case_e two levels: only the leaf under a partitioned partition differs # case_f two levels: the partitioned partition differs (and so its leaf) # # "Following the message" means only what the text says: for each column # in the file, take its partitioned table, and run SET EXPRESSION there # with that table's own expression; on 18, drop the CHECK constraints of # that table first and add them back afterwards, in one transaction. set -uo pipefail for a in "$@"; do eval "${a%%=*}=${a#*=}"; done : "${OLD:?}" "${FIX:?}" "${TARGET:?}"; TARGET2=${TARGET2:-} tmp=$(mktemp -d "${TMPDIR:-/tmp}/h2.XXXXXX") port=${PORT_BASE:-62100} trap 'for d in "$tmp"/old "$tmp"/new; do [ -f "$d/postmaster.pid" ] && \ "$FIX/pg_ctl" -D "$d" -m immediate -w stop >/dev/null 2>&1; \ [ -f "$d/postmaster.pid" ] && "$TARGET/pg_ctl" -D "$d" -m immediate -w stop \ >/dev/null 2>&1; done; rm -rf "$tmp"' EXIT major() { "$1/postgres" --version | sed -E 's/.* ([0-9]+).*/\1/'; } say() { printf '\n### %s\n' "$*"; } start() { "$1/pg_ctl" -D "$2" -l "$2.log" -w \ -o "-p $port -k $tmp -c listen_addresses=''" start >/dev/null; } stop() { "$1/pg_ctl" -D "$2" -m fast -w stop >/dev/null; } q() { local db=$1; shift; "$FIX/psql" -X -h "$tmp" -p "$port" -U postgres \ -d "$db" "$@" 2>&1; } # the SQL is echoed as run, so the output shows each command and its result run() { local db=$1; shift; "$FIX/psql" -X -e -h "$tmp" -p "$port" \ -U postgres -d "$db" "$@" 2>&1 | sed 's/^/ /'; } declare -A SQL SQL[case_a]=" create table ta (x int check (x > 0), v int generated always as (x * 2) virtual) partition by list (x); create table ta1 partition of ta (v generated always as (x * 3) virtual) for values in (1); insert into ta values (1);" SQL[case_b]=" create table tb (x int, v int generated always as (-x) virtual check (v > 0)) partition by list (x); create table tb1 partition of tb (v generated always as (x) virtual) for values in (5); insert into tb values (5);" SQL[case_c]=" create table tc (x int, v int generated always as (x * 2) virtual) partition by list (x); create table tc1 partition of tc (v generated always as (x * 3) virtual) for values in (1); alter table tc1 add constraint tc1_x_check check (x > 0); insert into tc values (1);" SQL[case_d]=" create table td (x int, v int generated always as (nullif(x, 0)) virtual not null) partition by list (x); create table td1 partition of td (v generated always as (x + 1) virtual) for values in (0); insert into td values (0);" SQL[case_e]=" create table te (x int, y int, v int generated always as (x * 2) virtual) partition by list (x); create table te1 partition of te for values in (1) partition by list (y); create table te1a partition of te1 (v generated always as (x * 3) virtual) for values in (1); insert into te values (1, 1);" SQL[case_f]=" create table tf (x int, y int, v int generated always as (x * 2) virtual) partition by list (x); create table tf1 partition of tf (v generated always as (x * 3) virtual) for values in (1) partition by list (y); create table tf1a partition of tf1 for values in (1); insert into tf values (1, 1);" CASES="case_a case_b case_c case_d case_e case_f" check() { # check LABEL BINDIR OLDBIN -> prints pg_upgrade output and the file local label=$1 bin=$2 ob=$3 f rm -rf "$tmp/new"; "$bin/initdb" -D "$tmp/new" -U postgres -A trust >/dev/null echo " \$ pg_upgrade --check ($("$ob/postgres" --version) -> $label)" ( cd "$tmp" && "$bin/pg_upgrade" --check -U postgres -b "$ob" -B "$bin" \ -d "$tmp/old" -D "$tmp/new" -p $((port + 1)) -P $((port + 2)) \ -s "$tmp" ) 2>&1 | grep -vE '^\s*$' | sed -E "s|$tmp|<tmp>|g; s/^/ /" f=$(find "$tmp/new" -name partition_virtual_generated_columns.txt | head -1) if [ -n "$f" ]; then echo " contents of partition_virtual_generated_columns.txt:" sed 's/^/ /' "$f"; cp "$f" "$tmp/report.txt" else rm -f "$tmp/report.txt"; fi } say "0. builds" echo " OLD $("$OLD/postgres" --version)" echo " FIX $("$FIX/postgres" --version)" echo " TARGET $("$TARGET/postgres" --version)" [ -n "$TARGET2" ] && echo " TARGET2 $("$TARGET2/postgres" --version)" say "1. create the cases with the unpatched server" "$OLD/initdb" -D "$tmp/old" -U postgres -A trust >/dev/null start "$OLD" "$tmp/old" for c in $CASES; do "$OLD/createdb" -h "$tmp" -p "$port" -U postgres "$c" "$OLD/psql" -X -q -h "$tmp" -p "$port" -U postgres -d "$c" -c "${SQL[$c]}" 2>&1 echo " $c: partitions created: $(echo "${SQL[$c]}" | grep -c "partition of")" done stop "$OLD" "$tmp/old" say "2. pg_upgrade --check before any fix" check TARGET "$TARGET" "$FIX" [ -n "$TARGET2" ] && check TARGET2 "$TARGET2" "$FIX" cp "$tmp/report.txt" "$tmp/report-0.txt" 2>/dev/null say "3. follow the message on $("$FIX/postgres" --version)" start "$FIX" "$tmp/old" fixmajor=$(major "$FIX") db=; add=() while IFS= read -r line; do case $line in "In database: "*) db=${line#In database: }; echo; echo " [$db]"; continue ;; esac col=${line##*.}; rel=${line%.*}; rel=${rel# }; rel=${rel# } parent=$(q "$db" -Atc "select inhparent::regclass from pg_inherits where inhrelid = '$rel'::regclass") expr=$(q "$db" -Atc "select pg_get_expr(d.adbin, d.adrelid) from pg_attrdef d join pg_attribute a on a.attrelid = d.adrelid and a.attnum = d.adnum where a.attrelid = '$parent'::regclass and a.attname = '$col'") echo " file lists $rel.$col; its partitioned table is $parent, expression $expr" cmds=(-c begin) if [ "$fixmajor" = 18 ]; then while IFS='|' read -r cn cd; do [ -n "$cn" ] || continue cmds+=(-c "alter table $parent drop constraint $cn") add+=(-c "alter table $parent add constraint $cn $cd") done < <(q "$db" -Atc "select conname, pg_get_constraintdef(oid) from pg_constraint where conrelid = '$parent'::regclass and contype = 'c' order by conname") fi cmds+=(-c "alter table $parent alter column $col set expression as ($expr)") cmds+=("${add[@]}"); unset add; add=() cmds+=(-c commit) run "$db" "${cmds[@]}" done < "$tmp/report-0.txt" add=() stop "$FIX" "$tmp/old" say "4. pg_upgrade --check after following the message" check TARGET "$TARGET" "$FIX" [ -n "$TARGET2" ] && check TARGET2 "$TARGET2" "$FIX" say "5. what the message does not say: the remaining cases by hand" start "$FIX" "$tmp/old" echo " [case_b] the rows do not meet the CHECK with the parent's expression" run case_b -c "select x, v as v_via_partition, -x as v_via_parent from tb1" if [ "$fixmajor" = 18 ]; then echo " [case_c] drop the CHECK of the partition instead, then add it back" run case_c -c begin -c "alter table tc1 drop constraint tc1_x_check" \ -c "alter table tc alter column v set expression as (x * 2)" \ -c "alter table tc1 add constraint tc1_x_check check (x > 0)" -c commit fi echo " [case_e] SET EXPRESSION on the root instead of the listed partition's parent" run case_e -c "alter table te alter column v set expression as (x * 2)" echo " [case_d] the row is NULL with the parent's expression" run case_d -c "select x, v as v_via_partition, nullif(x, 0) as v_via_parent from td1" stop "$FIX" "$tmp/old" check TARGET "$TARGET" "$FIX" say "6. real pg_upgrade -> TARGET, without case_b and case_d" start "$FIX" "$tmp/old" for c in case_b case_d; do "$FIX/dropdb" -h "$tmp" -p "$port" -U postgres "$c"; done stop "$FIX" "$tmp/old" rm -rf "$tmp/new"; "$TARGET/initdb" -D "$tmp/new" -U postgres -A trust >/dev/null ( cd "$tmp" && "$TARGET/pg_upgrade" -U postgres -b "$FIX" -B "$TARGET" \ -d "$tmp/old" -D "$tmp/new" -p $((port + 1)) -P $((port + 2)) \ -s "$tmp" ) >"$tmp/upgrade.out" 2>&1 echo " pg_upgrade exit $?: $(grep -E 'Upgrade Complete|fatal|failure' "$tmp/upgrade.out")" start "$TARGET" "$tmp/new" P() { "$TARGET/psql" -X -h "$tmp" -p "$port" -U postgres "$@" 2>&1 | sed 's/^/ /'; } echo " each leaf: rows read through the root, rows read directly, its expression" for t in case_a:ta:ta1 case_c:tc:tc1 case_e:te:te1a case_f:tf:tf1a; do IFS=: read -r d r l <<<"$t" P -d "$d" -At -c "select '$r/$l', (select string_agg(x||'='||v, ',') from $r), (select string_agg(x||'='||v, ',') from $l), (select pg_get_expr(adbin, adrelid) from pg_attrdef where adrelid = '$l'::regclass and adnum = (select attnum from pg_attribute where attrelid = '$l'::regclass and attname = 'v'))" done echo " count(*) where v = 2 through each root, constraint_exclusion on / partition" for t in case_a:ta case_c:tc case_e:te case_f:tf; do P -d "${t%%:*}" -At -c "set constraint_exclusion = on" \ -c "select '${t#*:} on', count(*) from ${t#*:} where v = 2" \ -c "set constraint_exclusion = partition" \ -c "select '${t#*:} partition', count(*) from ${t#*:} where v = 2" | grep -v SET done echo " repro-ce-on.sql in a new database of the upgraded cluster" "$TARGET/createdb" -h "$tmp" -p "$port" -U postgres repro [ -f "${REPRO:-}" ] && P -d repro -f "$REPRO" | sed -E 's|psql:[^:]*:|psql:repro:|' stop "$TARGET" "$tmp/new"
h2-output.txt (text/plain, 39.5K) download Output of h2.sh.txt, three runs. Builds: cassert, -O2. master 77bba5454f9 + v3 REL_19_STABLE dfffe8da630 + v3, and unpatched REL_18_STABLE 2ea5222db7c + v3's REL_18 version, and unpatched Paths of the temporary clusters are shown as <tmp>. ================================================================ RUN: REL_18_STABLE unpatched creates and fixes; --check to master and 19 ================================================================ ### 0. builds OLD postgres (PostgreSQL) 18.7 FIX postgres (PostgreSQL) 18.7 TARGET postgres (PostgreSQL) 20devel TARGET2 postgres (PostgreSQL) 19rc2 ### 1. create the cases with the unpatched server case_a: partitions created: 1 case_b: partitions created: 1 case_c: partitions created: 1 case_d: partitions created: 1 case_e: partitions created: 2 case_f: partitions created: 2 ### 2. pg_upgrade --check before any fix $ pg_upgrade --check (postgres (PostgreSQL) 18.7 -> TARGET) Performing Consistency Checks ----------------------------- Checking cluster versions ok Checking database connection settings ok Checking for unsupported encodings ok Checking names of databases, roles, and tablespaces ok Checking database user is the install user ok Checking for prepared transactions ok Checking oldestXID and oldestMultiXid consistency ok Checking for contrib/isn with bigint-passing mismatch ok Checking logical replication slots ok Checking subscription state ok Checking data type usage ok Checking for objects affected by Unicode update ok Checking for not-null constraint inconsistencies ok Checking for virtual generated column inconsistencies fatal Your installation contains partitions whose virtual generated columns have a different generation expression than the partitioned table. This is no longer allowed, so the upgrade would fail. You can fix this by running ALTER TABLE parent ALTER COLUMN column SET EXPRESSION AS (...); on the partitioned table of each column. In version 18 this is not allowed on a table with CHECK constraints, so drop them first and add them back afterwards. A list of the problem columns is in the file: <tmp>/new/pg_upgrade_output.d/20261113T214002.753/partition_virtual_generated_columns.txt Failure, exiting contents of partition_virtual_generated_columns.txt: In database: case_a public.ta1.v In database: case_b public.tb1.v In database: case_c public.tc1.v In database: case_d public.td1.v In database: case_e public.te1a.v In database: case_f public.tf1.v $ pg_upgrade --check (postgres (PostgreSQL) 18.7 -> TARGET2) Performing Consistency Checks ----------------------------- Checking cluster versions ok Checking database connection settings ok Checking for unsupported encodings ok Checking names of databases, roles, and tablespaces ok Checking database user is the install user ok Checking for prepared transactions ok Checking oldestXID and oldestMultiXid consistency ok Checking for contrib/isn with bigint-passing mismatch ok Checking logical replication slots ok Checking subscription state ok Checking data type usage ok Checking for objects affected by Unicode update ok Checking for not-null constraint inconsistencies ok Checking for virtual generated column inconsistencies fatal Your installation contains partitions whose virtual generated columns have a different generation expression than the partitioned table. This is no longer allowed, so the upgrade would fail. You can fix this by running ALTER TABLE parent ALTER COLUMN column SET EXPRESSION AS (...); on the partitioned table of each column. In version 18 this is not allowed on a table with CHECK constraints, so drop them first and add them back afterwards. A list of the problem columns is in the file: <tmp>/new/pg_upgrade_output.d/20261113T214004.531/partition_virtual_generated_columns.txt Failure, exiting contents of partition_virtual_generated_columns.txt: In database: case_a public.ta1.v In database: case_b public.tb1.v In database: case_c public.tc1.v In database: case_d public.td1.v In database: case_e public.te1a.v In database: case_f public.tf1.v ### 3. follow the message on postgres (PostgreSQL) 18.7 [case_a] file lists public.ta1.v; its partitioned table is ta, expression (x * 2) begin BEGIN alter table ta drop constraint ta_x_check ALTER TABLE alter table ta alter column v set expression as ((x * 2)) ALTER TABLE alter table ta add constraint ta_x_check CHECK ((x > 0)) ALTER TABLE commit COMMIT [case_b] file lists public.tb1.v; its partitioned table is tb, expression (- x) begin BEGIN alter table tb drop constraint tb_v_check ALTER TABLE alter table tb alter column v set expression as ((- x)) ALTER TABLE alter table tb add constraint tb_v_check CHECK ((v > 0)) ERROR: check constraint "tb_v_check" of relation "tb1" is violated by some row commit ROLLBACK [case_c] file lists public.tc1.v; its partitioned table is tc, expression (x * 2) begin BEGIN alter table tc alter column v set expression as ((x * 2)) ERROR: ALTER TABLE / SET EXPRESSION is not supported for virtual generated columns in tables with check constraints DETAIL: Column "v" of relation "tc1" is a virtual generated column. commit ROLLBACK [case_d] file lists public.td1.v; its partitioned table is td, expression NULLIF(x, 0) begin BEGIN alter table td alter column v set expression as (NULLIF(x, 0)) ERROR: column "v" of relation "td1" contains null values commit ROLLBACK [case_e] file lists public.te1a.v; its partitioned table is te1, expression (x * 2) begin BEGIN alter table te1 alter column v set expression as ((x * 2)) ALTER TABLE commit COMMIT [case_f] file lists public.tf1.v; its partitioned table is tf, expression (x * 2) begin BEGIN alter table tf alter column v set expression as ((x * 2)) ALTER TABLE commit COMMIT ### 4. pg_upgrade --check after following the message $ pg_upgrade --check (postgres (PostgreSQL) 18.7 -> TARGET) Performing Consistency Checks ----------------------------- Checking cluster versions ok Checking database connection settings ok Checking for unsupported encodings ok Checking names of databases, roles, and tablespaces ok Checking database user is the install user ok Checking for prepared transactions ok Checking oldestXID and oldestMultiXid consistency ok Checking for contrib/isn with bigint-passing mismatch ok Checking logical replication slots ok Checking subscription state ok Checking data type usage ok Checking for objects affected by Unicode update ok Checking for not-null constraint inconsistencies ok Checking for virtual generated column inconsistencies fatal Your installation contains partitions whose virtual generated columns have a different generation expression than the partitioned table. This is no longer allowed, so the upgrade would fail. You can fix this by running ALTER TABLE parent ALTER COLUMN column SET EXPRESSION AS (...); on the partitioned table of each column. In version 18 this is not allowed on a table with CHECK constraints, so drop them first and add them back afterwards. A list of the problem columns is in the file: <tmp>/new/pg_upgrade_output.d/20261113T214006.867/partition_virtual_generated_columns.txt Failure, exiting contents of partition_virtual_generated_columns.txt: In database: case_b public.tb1.v In database: case_c public.tc1.v In database: case_d public.td1.v $ pg_upgrade --check (postgres (PostgreSQL) 18.7 -> TARGET2) Performing Consistency Checks ----------------------------- Checking cluster versions ok Checking database connection settings ok Checking for unsupported encodings ok Checking names of databases, roles, and tablespaces ok Checking database user is the install user ok Checking for prepared transactions ok Checking oldestXID and oldestMultiXid consistency ok Checking for contrib/isn with bigint-passing mismatch ok Checking logical replication slots ok Checking subscription state ok Checking data type usage ok Checking for objects affected by Unicode update ok Checking for not-null constraint inconsistencies ok Checking for virtual generated column inconsistencies fatal Your installation contains partitions whose virtual generated columns have a different generation expression than the partitioned table. This is no longer allowed, so the upgrade would fail. You can fix this by running ALTER TABLE parent ALTER COLUMN column SET EXPRESSION AS (...); on the partitioned table of each column. In version 18 this is not allowed on a table with CHECK constraints, so drop them first and add them back afterwards. A list of the problem columns is in the file: <tmp>/new/pg_upgrade_output.d/20261113T214008.918/partition_virtual_generated_columns.txt Failure, exiting contents of partition_virtual_generated_columns.txt: In database: case_b public.tb1.v In database: case_c public.tc1.v In database: case_d public.td1.v ### 5. what the message does not say: the remaining cases by hand [case_b] the rows do not meet the CHECK with the parent's expression select x, v as v_via_partition, -x as v_via_parent from tb1 x | v_via_partition | v_via_parent ---+-----------------+-------------- 5 | 5 | -5 (1 row) [case_c] drop the CHECK of the partition instead, then add it back begin BEGIN alter table tc1 drop constraint tc1_x_check ALTER TABLE alter table tc alter column v set expression as (x * 2) ALTER TABLE alter table tc1 add constraint tc1_x_check check (x > 0) ALTER TABLE commit COMMIT [case_e] SET EXPRESSION on the root instead of the listed partition's parent alter table te alter column v set expression as (x * 2) ALTER TABLE [case_d] the row is NULL with the parent's expression select x, v as v_via_partition, nullif(x, 0) as v_via_parent from td1 x | v_via_partition | v_via_parent ---+-----------------+-------------- 0 | 1 | (1 row) $ pg_upgrade --check (postgres (PostgreSQL) 18.7 -> TARGET) Performing Consistency Checks ----------------------------- Checking cluster versions ok Checking database connection settings ok Checking for unsupported encodings ok Checking names of databases, roles, and tablespaces ok Checking database user is the install user ok Checking for prepared transactions ok Checking oldestXID and oldestMultiXid consistency ok Checking for contrib/isn with bigint-passing mismatch ok Checking logical replication slots ok Checking subscription state ok Checking data type usage ok Checking for objects affected by Unicode update ok Checking for not-null constraint inconsistencies ok Checking for virtual generated column inconsistencies fatal Your installation contains partitions whose virtual generated columns have a different generation expression than the partitioned table. This is no longer allowed, so the upgrade would fail. You can fix this by running ALTER TABLE parent ALTER COLUMN column SET EXPRESSION AS (...); on the partitioned table of each column. In version 18 this is not allowed on a table with CHECK constraints, so drop them first and add them back afterwards. A list of the problem columns is in the file: <tmp>/new/pg_upgrade_output.d/20261113T214013.021/partition_virtual_generated_columns.txt Failure, exiting contents of partition_virtual_generated_columns.txt: In database: case_b public.tb1.v In database: case_d public.td1.v ### 6. real pg_upgrade -> TARGET, without case_b and case_d pg_upgrade exit 0: Upgrade Complete each leaf: rows read through the root, rows read directly, its expression ta/ta1|1=2|1=2|(x * 2) tc/tc1|1=2|1=2|(x * 2) te/te1a|1=2|1=2|(x * 2) tf/tf1a|1=2|1=2|(x * 2) count(*) where v = 2 through each root, constraint_exclusion on / partition ta on|1 ta partition|1 tc on|1 tc partition|1 te on|1 te partition|1 tf on|1 tf partition|1 repro-ce-on.sql in a new database of the upgraded cluster Null display is "(null)". server_version ---------------- 20devel (1 row) CREATE TABLE psql:repro:15: ERROR: virtual generated column "v" of partition "p1" must have the same generation expression as the partitioned table psql:repro:16: ERROR: no partition of relation "p" found for row DETAIL: Partition key of the failing row contains (a) = (0). CREATE TABLE psql:repro:22: ERROR: virtual generated column "v" of partition "c1" must have the same generation expression as the partitioned table psql:repro:23: ERROR: no partition of relation "c" found for row DETAIL: Partition key of the failing row contains (a) = (5). a | v ---+--- (0 rows) SET p_null -------- 0 (1 row) c_neg ------- 0 (1 row) SET p_null -------- 0 (1 row) c_neg ------- 0 (1 row) QUERY PLAN -------------------------------- Aggregate -> Result Replaces: Scan on p One-Time Filter: false (4 rows) RESET ================================================================ RUN: REL_18_STABLE unpatched creates, the same data directory is fixed with the REL_18 patch; --check to master and 19 ================================================================ ### 0. builds OLD postgres (PostgreSQL) 18.7 FIX postgres (PostgreSQL) 18.7 TARGET postgres (PostgreSQL) 20devel TARGET2 postgres (PostgreSQL) 19rc2 ### 1. create the cases with the unpatched server case_a: partitions created: 1 case_b: partitions created: 1 case_c: partitions created: 1 case_d: partitions created: 1 case_e: partitions created: 2 case_f: partitions created: 2 ### 2. pg_upgrade --check before any fix $ pg_upgrade --check (postgres (PostgreSQL) 18.7 -> TARGET) Performing Consistency Checks ----------------------------- Checking cluster versions ok Checking database connection settings ok Checking for unsupported encodings ok Checking names of databases, roles, and tablespaces ok Checking database user is the install user ok Checking for prepared transactions ok Checking oldestXID and oldestMultiXid consistency ok Checking for contrib/isn with bigint-passing mismatch ok Checking logical replication slots ok Checking subscription state ok Checking data type usage ok Checking for objects affected by Unicode update ok Checking for not-null constraint inconsistencies ok Checking for virtual generated column inconsistencies fatal Your installation contains partitions whose virtual generated columns have a different generation expression than the partitioned table. This is no longer allowed, so the upgrade would fail. You can fix this by running ALTER TABLE parent ALTER COLUMN column SET EXPRESSION AS (...); on the partitioned table of each column. In version 18 this is not allowed on a table with CHECK constraints, so drop them first and add them back afterwards. A list of the problem columns is in the file: <tmp>/new/pg_upgrade_output.d/20261113T214023.139/partition_virtual_generated_columns.txt Failure, exiting contents of partition_virtual_generated_columns.txt: In database: case_a public.ta1.v In database: case_b public.tb1.v In database: case_c public.tc1.v In database: case_d public.td1.v In database: case_e public.te1a.v In database: case_f public.tf1.v $ pg_upgrade --check (postgres (PostgreSQL) 18.7 -> TARGET2) Performing Consistency Checks ----------------------------- Checking cluster versions ok Checking database connection settings ok Checking for unsupported encodings ok Checking names of databases, roles, and tablespaces ok Checking database user is the install user ok Checking for prepared transactions ok Checking oldestXID and oldestMultiXid consistency ok Checking for contrib/isn with bigint-passing mismatch ok Checking logical replication slots ok Checking subscription state ok Checking data type usage ok Checking for objects affected by Unicode update ok Checking for not-null constraint inconsistencies ok Checking for virtual generated column inconsistencies fatal Your installation contains partitions whose virtual generated columns have a different generation expression than the partitioned table. This is no longer allowed, so the upgrade would fail. You can fix this by running ALTER TABLE parent ALTER COLUMN column SET EXPRESSION AS (...); on the partitioned table of each column. In version 18 this is not allowed on a table with CHECK constraints, so drop them first and add them back afterwards. A list of the problem columns is in the file: <tmp>/new/pg_upgrade_output.d/20261113T214024.883/partition_virtual_generated_columns.txt Failure, exiting contents of partition_virtual_generated_columns.txt: In database: case_a public.ta1.v In database: case_b public.tb1.v In database: case_c public.tc1.v In database: case_d public.td1.v In database: case_e public.te1a.v In database: case_f public.tf1.v ### 3. follow the message on postgres (PostgreSQL) 18.7 [case_a] file lists public.ta1.v; its partitioned table is ta, expression (x * 2) begin BEGIN alter table ta drop constraint ta_x_check ALTER TABLE alter table ta alter column v set expression as ((x * 2)) ALTER TABLE alter table ta add constraint ta_x_check CHECK ((x > 0)) ALTER TABLE commit COMMIT [case_b] file lists public.tb1.v; its partitioned table is tb, expression (- x) begin BEGIN alter table tb drop constraint tb_v_check ALTER TABLE alter table tb alter column v set expression as ((- x)) ALTER TABLE alter table tb add constraint tb_v_check CHECK ((v > 0)) ERROR: check constraint "tb_v_check" of relation "tb1" is violated by some row commit ROLLBACK [case_c] file lists public.tc1.v; its partitioned table is tc, expression (x * 2) begin BEGIN alter table tc alter column v set expression as ((x * 2)) ERROR: ALTER TABLE / SET EXPRESSION is not supported for virtual generated columns in tables with check constraints DETAIL: Column "v" of relation "tc1" is a virtual generated column. commit ROLLBACK [case_d] file lists public.td1.v; its partitioned table is td, expression NULLIF(x, 0) begin BEGIN alter table td alter column v set expression as (NULLIF(x, 0)) ERROR: column "v" of relation "td1" contains null values commit ROLLBACK [case_e] file lists public.te1a.v; its partitioned table is te1, expression (x * 2) begin BEGIN alter table te1 alter column v set expression as ((x * 2)) ERROR: cannot alter generation expression of virtual generated column "v" of partition "te1" HINT: Alter the generation expression of the partitioned table instead. commit ROLLBACK [case_f] file lists public.tf1.v; its partitioned table is tf, expression (x * 2) begin BEGIN alter table tf alter column v set expression as ((x * 2)) ALTER TABLE commit COMMIT ### 4. pg_upgrade --check after following the message $ pg_upgrade --check (postgres (PostgreSQL) 18.7 -> TARGET) Performing Consistency Checks ----------------------------- Checking cluster versions ok Checking database connection settings ok Checking for unsupported encodings ok Checking names of databases, roles, and tablespaces ok Checking database user is the install user ok Checking for prepared transactions ok Checking oldestXID and oldestMultiXid consistency ok Checking for contrib/isn with bigint-passing mismatch ok Checking logical replication slots ok Checking subscription state ok Checking data type usage ok Checking for objects affected by Unicode update ok Checking for not-null constraint inconsistencies ok Checking for virtual generated column inconsistencies fatal Your installation contains partitions whose virtual generated columns have a different generation expression than the partitioned table. This is no longer allowed, so the upgrade would fail. You can fix this by running ALTER TABLE parent ALTER COLUMN column SET EXPRESSION AS (...); on the partitioned table of each column. In version 18 this is not allowed on a table with CHECK constraints, so drop them first and add them back afterwards. A list of the problem columns is in the file: <tmp>/new/pg_upgrade_output.d/20261113T214026.674/partition_virtual_generated_columns.txt Failure, exiting contents of partition_virtual_generated_columns.txt: In database: case_b public.tb1.v In database: case_c public.tc1.v In database: case_d public.td1.v In database: case_e public.te1a.v $ pg_upgrade --check (postgres (PostgreSQL) 18.7 -> TARGET2) Performing Consistency Checks ----------------------------- Checking cluster versions ok Checking database connection settings ok Checking for unsupported encodings ok Checking names of databases, roles, and tablespaces ok Checking database user is the install user ok Checking for prepared transactions ok Checking oldestXID and oldestMultiXid consistency ok Checking for contrib/isn with bigint-passing mismatch ok Checking logical replication slots ok Checking subscription state ok Checking data type usage ok Checking for objects affected by Unicode update ok Checking for not-null constraint inconsistencies ok Checking for virtual generated column inconsistencies fatal Your installation contains partitions whose virtual generated columns have a different generation expression than the partitioned table. This is no longer allowed, so the upgrade would fail. You can fix this by running ALTER TABLE parent ALTER COLUMN column SET EXPRESSION AS (...); on the partitioned table of each column. In version 18 this is not allowed on a table with CHECK constraints, so drop them first and add them back afterwards. A list of the problem columns is in the file: <tmp>/new/pg_upgrade_output.d/20261113T214028.369/partition_virtual_generated_columns.txt Failure, exiting contents of partition_virtual_generated_columns.txt: In database: case_b public.tb1.v In database: case_c public.tc1.v In database: case_d public.td1.v In database: case_e public.te1a.v ### 5. what the message does not say: the remaining cases by hand [case_b] the rows do not meet the CHECK with the parent's expression select x, v as v_via_partition, -x as v_via_parent from tb1 x | v_via_partition | v_via_parent ---+-----------------+-------------- 5 | 5 | -5 (1 row) [case_c] drop the CHECK of the partition instead, then add it back begin BEGIN alter table tc1 drop constraint tc1_x_check ALTER TABLE alter table tc alter column v set expression as (x * 2) ALTER TABLE alter table tc1 add constraint tc1_x_check check (x > 0) ALTER TABLE commit COMMIT [case_e] SET EXPRESSION on the root instead of the listed partition's parent alter table te alter column v set expression as (x * 2) ALTER TABLE [case_d] the row is NULL with the parent's expression select x, v as v_via_partition, nullif(x, 0) as v_via_parent from td1 x | v_via_partition | v_via_parent ---+-----------------+-------------- 0 | 1 | (1 row) $ pg_upgrade --check (postgres (PostgreSQL) 18.7 -> TARGET) Performing Consistency Checks ----------------------------- Checking cluster versions ok Checking database connection settings ok Checking for unsupported encodings ok Checking names of databases, roles, and tablespaces ok Checking database user is the install user ok Checking for prepared transactions ok Checking oldestXID and oldestMultiXid consistency ok Checking for contrib/isn with bigint-passing mismatch ok Checking logical replication slots ok Checking subscription state ok Checking data type usage ok Checking for objects affected by Unicode update ok Checking for not-null constraint inconsistencies ok Checking for virtual generated column inconsistencies fatal Your installation contains partitions whose virtual generated columns have a different generation expression than the partitioned table. This is no longer allowed, so the upgrade would fail. You can fix this by running ALTER TABLE parent ALTER COLUMN column SET EXPRESSION AS (...); on the partitioned table of each column. In version 18 this is not allowed on a table with CHECK constraints, so drop them first and add them back afterwards. A list of the problem columns is in the file: <tmp>/new/pg_upgrade_output.d/20261113T214030.304/partition_virtual_generated_columns.txt Failure, exiting contents of partition_virtual_generated_columns.txt: In database: case_b public.tb1.v In database: case_d public.td1.v ### 6. real pg_upgrade -> TARGET, without case_b and case_d pg_upgrade exit 0: Upgrade Complete each leaf: rows read through the root, rows read directly, its expression ta/ta1|1=2|1=2|(x * 2) tc/tc1|1=2|1=2|(x * 2) te/te1a|1=2|1=2|(x * 2) tf/tf1a|1=2|1=2|(x * 2) count(*) where v = 2 through each root, constraint_exclusion on / partition ta on|1 ta partition|1 tc on|1 tc partition|1 te on|1 te partition|1 tf on|1 tf partition|1 repro-ce-on.sql in a new database of the upgraded cluster Null display is "(null)". server_version ---------------- 20devel (1 row) CREATE TABLE psql:repro:15: ERROR: virtual generated column "v" of partition "p1" must have the same generation expression as the partitioned table psql:repro:16: ERROR: no partition of relation "p" found for row DETAIL: Partition key of the failing row contains (a) = (0). CREATE TABLE psql:repro:22: ERROR: virtual generated column "v" of partition "c1" must have the same generation expression as the partitioned table psql:repro:23: ERROR: no partition of relation "c" found for row DETAIL: Partition key of the failing row contains (a) = (5). a | v ---+--- (0 rows) SET p_null -------- 0 (1 row) c_neg ------- 0 (1 row) SET p_null -------- 0 (1 row) c_neg ------- 0 (1 row) QUERY PLAN -------------------------------- Aggregate -> Result Replaces: Scan on p One-Time Filter: false (4 rows) RESET ================================================================ RUN: REL_19_STABLE unpatched creates and fixes; --check to master ================================================================ ### 0. builds OLD postgres (PostgreSQL) 19rc2 FIX postgres (PostgreSQL) 19rc2 TARGET postgres (PostgreSQL) 20devel ### 1. create the cases with the unpatched server case_a: partitions created: 1 case_b: partitions created: 1 case_c: partitions created: 1 case_d: partitions created: 1 case_e: partitions created: 2 case_f: partitions created: 2 ### 2. pg_upgrade --check before any fix $ pg_upgrade --check (postgres (PostgreSQL) 19rc2 -> TARGET) Performing Consistency Checks ----------------------------- Checking cluster versions ok Checking database connection settings ok Checking for unsupported encodings ok Checking database user is the install user ok Checking for prepared transactions ok Checking oldestXID and oldestMultiXid consistency ok Checking for contrib/isn with bigint-passing mismatch ok Checking logical replication slots ok Checking subscription state ok Checking data type usage ok Checking for objects affected by Unicode update ok Checking for virtual generated column inconsistencies fatal Your installation contains partitions whose virtual generated columns have a different generation expression than the partitioned table. This is no longer allowed, so the upgrade would fail. You can fix this by running ALTER TABLE parent ALTER COLUMN column SET EXPRESSION AS (...); on the partitioned table of each column. In version 18 this is not allowed on a table with CHECK constraints, so drop them first and add them back afterwards. A list of the problem columns is in the file: <tmp>/new/pg_upgrade_output.d/20261113T214042.235/partition_virtual_generated_columns.txt Failure, exiting contents of partition_virtual_generated_columns.txt: In database: case_a public.ta1.v In database: case_b public.tb1.v In database: case_c public.tc1.v In database: case_d public.td1.v In database: case_e public.te1a.v In database: case_f public.tf1.v ### 3. follow the message on postgres (PostgreSQL) 19rc2 [case_a] file lists public.ta1.v; its partitioned table is ta, expression (x * 2) begin BEGIN alter table ta alter column v set expression as ((x * 2)) ALTER TABLE commit COMMIT [case_b] file lists public.tb1.v; its partitioned table is tb, expression (- x) begin BEGIN alter table tb alter column v set expression as ((- x)) ERROR: check constraint "tb_v_check" of relation "tb1" is violated by some row commit ROLLBACK [case_c] file lists public.tc1.v; its partitioned table is tc, expression (x * 2) begin BEGIN alter table tc alter column v set expression as ((x * 2)) ALTER TABLE commit COMMIT [case_d] file lists public.td1.v; its partitioned table is td, expression NULLIF(x, 0) begin BEGIN alter table td alter column v set expression as (NULLIF(x, 0)) ERROR: column "v" of relation "td1" contains null values commit ROLLBACK [case_e] file lists public.te1a.v; its partitioned table is te1, expression (x * 2) begin BEGIN alter table te1 alter column v set expression as ((x * 2)) ALTER TABLE commit COMMIT [case_f] file lists public.tf1.v; its partitioned table is tf, expression (x * 2) begin BEGIN alter table tf alter column v set expression as ((x * 2)) ALTER TABLE commit COMMIT ### 4. pg_upgrade --check after following the message $ pg_upgrade --check (postgres (PostgreSQL) 19rc2 -> TARGET) Performing Consistency Checks ----------------------------- Checking cluster versions ok Checking database connection settings ok Checking for unsupported encodings ok Checking database user is the install user ok Checking for prepared transactions ok Checking oldestXID and oldestMultiXid consistency ok Checking for contrib/isn with bigint-passing mismatch ok Checking logical replication slots ok Checking subscription state ok Checking data type usage ok Checking for objects affected by Unicode update ok Checking for virtual generated column inconsistencies fatal Your installation contains partitions whose virtual generated columns have a different generation expression than the partitioned table. This is no longer allowed, so the upgrade would fail. You can fix this by running ALTER TABLE parent ALTER COLUMN column SET EXPRESSION AS (...); on the partitioned table of each column. In version 18 this is not allowed on a table with CHECK constraints, so drop them first and add them back afterwards. A list of the problem columns is in the file: <tmp>/new/pg_upgrade_output.d/20261113T214043.753/partition_virtual_generated_columns.txt Failure, exiting contents of partition_virtual_generated_columns.txt: In database: case_b public.tb1.v In database: case_d public.td1.v ### 5. what the message does not say: the remaining cases by hand [case_b] the rows do not meet the CHECK with the parent's expression select x, v as v_via_partition, -x as v_via_parent from tb1 x | v_via_partition | v_via_parent ---+-----------------+-------------- 5 | 5 | -5 (1 row) [case_e] SET EXPRESSION on the root instead of the listed partition's parent alter table te alter column v set expression as (x * 2) ALTER TABLE [case_d] the row is NULL with the parent's expression select x, v as v_via_partition, nullif(x, 0) as v_via_parent from td1 x | v_via_partition | v_via_parent ---+-----------------+-------------- 0 | 1 | (1 row) $ pg_upgrade --check (postgres (PostgreSQL) 19rc2 -> TARGET) Performing Consistency Checks ----------------------------- Checking cluster versions ok Checking database connection settings ok Checking for unsupported encodings ok Checking database user is the install user ok Checking for prepared transactions ok Checking oldestXID and oldestMultiXid consistency ok Checking for contrib/isn with bigint-passing mismatch ok Checking logical replication slots ok Checking subscription state ok Checking data type usage ok Checking for objects affected by Unicode update ok Checking for virtual generated column inconsistencies fatal Your installation contains partitions whose virtual generated columns have a different generation expression than the partitioned table. This is no longer allowed, so the upgrade would fail. You can fix this by running ALTER TABLE parent ALTER COLUMN column SET EXPRESSION AS (...); on the partitioned table of each column. In version 18 this is not allowed on a table with CHECK constraints, so drop them first and add them back afterwards. A list of the problem columns is in the file: <tmp>/new/pg_upgrade_output.d/20261113T214045.632/partition_virtual_generated_columns.txt Failure, exiting contents of partition_virtual_generated_columns.txt: In database: case_b public.tb1.v In database: case_d public.td1.v ### 6. real pg_upgrade -> TARGET, without case_b and case_d pg_upgrade exit 0: Upgrade Complete each leaf: rows read through the root, rows read directly, its expression ta/ta1|1=2|1=2|(x * 2) tc/tc1|1=2|1=2|(x * 2) te/te1a|1=2|1=2|(x * 2) tf/tf1a|1=2|1=2|(x * 2) count(*) where v = 2 through each root, constraint_exclusion on / partition ta on|1 ta partition|1 tc on|1 tc partition|1 te on|1 te partition|1 tf on|1 tf partition|1 repro-ce-on.sql in a new database of the upgraded cluster Null display is "(null)". server_version ---------------- 20devel (1 row) CREATE TABLE psql:repro:15: ERROR: virtual generated column "v" of partition "p1" must have the same generation expression as the partitioned table psql:repro:16: ERROR: no partition of relation "p" found for row DETAIL: Partition key of the failing row contains (a) = (0). CREATE TABLE psql:repro:22: ERROR: virtual generated column "v" of partition "c1" must have the same generation expression as the partitioned table psql:repro:23: ERROR: no partition of relation "c" found for row DETAIL: Partition key of the failing row contains (a) = (5). a | v ---+--- (0 rows) SET p_null -------- 0 (1 row) c_neg ------- 0 (1 row) SET p_null -------- 0 (1 row) c_neg ------- 0 (1 row) QUERY PLAN -------------------------------- Aggregate -> Result Replaces: Scan on p One-Time Filter: false (4 rows) RESET
^ permalink raw reply [nested|flat] 24+ messages in thread

* Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned
  2026-10-10 00:23 pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Richard Guo <rguo@postgresql.org>
  2026-10-13 12:42 ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-10-13 14:34   ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Richard Guo <guofenglinux@gmail.com>
  2026-10-13 15:41     ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-10-13 16:00       ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-10-14 04:39         ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-10-26 17:40           ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Manu <manuelreyesbravo@gmail.com>
  2026-10-27 03:10             ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-11-11 15:41               ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-11-11 15:47                 ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-11-12 04:36                   ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-11-14 01:12                     ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Manu <manuelreyesbravo@gmail.com>
@ 2026-11-15 03:36                       ` shihao zhong <zhong950419@gmail.com>
  2026-11-15 21:15                         ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Zsolt Parragi <zsolt.parragi@percona.com>
  0 siblings, 1 reply; 24+ messages in thread

From: shihao zhong @ 2026-11-15 03:36 UTC (permalink / raw)
  To: Manu <manuelreyesbravo@gmail.com>; +Cc: Álvaro Herrera <alvherre@kurilemu.de>; Richard Guo <guofenglinux@gmail.com>; Richard Guo <rguo@postgresql.org>; pgsql-hackers@lists.postgresql.org

Hi Manu,

Thanks for trying both cases on 18 and for the new text. v4 uses your
pg_upgrade text as is.

Thanks,
Shihao

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

v4-0001-Require-partitions-to-use-the-parent-s-virtual-gener.patch (application/octet-stream, 29.2K) download From 5124be1926789465c45c4ed78d1ebcca28b50de7 Mon Sep 17 00:00:00 2001 From: shihao zhong <zhong950419@gmail.com> Date: Tue, 13 Oct 2026 23:22:52 -0400 Subject: [PATCH] Require partitions to use the parent's virtual generation expression MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Otherwise a NOT NULL column can read as NULL through the parent. Suggested-by: Álvaro Herrera <alvherre@kurilemu.de> Discussion: https://postgr.es/m/E1xFKs5-0000000116b-2Cge@gemulon.postgresql.org --- doc/src/sgml/ddl.sgml | 7 +- doc/src/sgml/ref/alter_table.sgml | 3 + src/backend/commands/tablecmds.c | 114 +++++++++++++++++- src/bin/pg_upgrade/check.c | 74 ++++++++++++ .../regress/expected/generated_virtual.out | 110 +++++++---------- src/test/regress/sql/generated_virtual.sql | 44 +++---- 6 files changed, 259 insertions(+), 93 deletions(-) diff --git a/doc/src/sgml/ddl.sgml b/doc/src/sgml/ddl.sgml index d78d986756e..e8489824f9d 100644 --- a/doc/src/sgml/ddl.sgml +++ b/doc/src/sgml/ddl.sgml @@ -451,8 +451,11 @@ CREATE TABLE people ( <listitem> <para> If a parent column is a generated column, its child column must also - be a generated column of the same kind (stored or virtual); however, - the child column can have a different generation expression. + be a generated column of the same kind (stored or virtual). + In addition, for virtual generated columns of a partition, the + generation expression must be identical to that of the partitioned + table. In all other cases, the child column can have a different + generation expression. </para> <para> diff --git a/doc/src/sgml/ref/alter_table.sgml b/doc/src/sgml/ref/alter_table.sgml index 0f9d698d170..d4156cc4253 100644 --- a/doc/src/sgml/ref/alter_table.sgml +++ b/doc/src/sgml/ref/alter_table.sgml @@ -276,6 +276,9 @@ WITH ( MODULUS <replaceable class="parameter">numeric_literal</replaceable>, REM Replacing the expression of a virtual generated column does not require a table rewrite, but if the column is used in a constraint, the table will be scanned to check that existing rows meet the constraint. + The expression of a virtual generated column cannot be changed for a + partition alone, or with <literal>ONLY</literal> for a partitioned table + that has partitions. </para> <para> diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index b6700929459..cf3fc8e2c68 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -383,6 +383,7 @@ static List *MergeCheckConstraint(List *constraints, const char *name, Node *exp static void MergeChildAttribute(List *inh_columns, int exist_attno, int newcol_attno, const ColumnDef *newdef); static ColumnDef *MergeInheritedAttribute(List *inh_columns, int exist_attno, const ColumnDef *newdef); static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispartition); +static void CheckPartitionVirtualGeneratedExprs(Relation partrel, Relation parentrel); static void MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel); static void StoreCatalogInheritance(Oid relationId, List *supers, bool child_is_partition); @@ -553,6 +554,7 @@ static ObjectAddress ATExecDropIdentity(Relation rel, const char *colName, bool bool recurse, bool recursing); static ObjectAddress ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName, Node *newExpr, LOCKMODE lockmode); +static void ATPrepSetExpression(Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing); static void ATPrepDropExpression(Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode); static ObjectAddress ATExecDropExpression(Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode); static ObjectAddress ATExecSetStatistics(Relation rel, const char *colName, int16 colNum, @@ -1175,6 +1177,8 @@ DefineRelation(CreateStmt *stmt, char relkind, Oid ownerId, errmsg("\"%s\" is not partitioned", RelationGetRelationName(parent)))); + CheckPartitionVirtualGeneratedExprs(rel, parent); + /* * The partition constraint of the default partition depends on the * partition bounds of every other partition. It is possible that @@ -3109,8 +3113,8 @@ MergeAttributes(List *columns, const List *supers, char relpersistence, * Check for conflicts related to generated columns. * * Same rules as above: generated-ness has to match the - * parent, but the contents of the generation expression - * can be different. + * parent. We don't check the expression itself here; + * CheckPartitionVirtualGeneratedExprs will do so. */ if (coldef->generated) { @@ -5100,6 +5104,7 @@ ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd, case AT_SetExpression: /* ALTER COLUMN SET EXPRESSION */ ATSimplePermissions(cmd->subtype, rel, ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE); + ATPrepSetExpression(rel, cmd, recurse, recursing); ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context); pass = AT_PASS_SET_EXPRESSION; break; @@ -9409,6 +9414,45 @@ ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName, return address; } +/* + * ALTER TABLE ALTER COLUMN SET EXPRESSION + * + * The expression of a virtual generated column can only be changed for a + * whole partition tree. See CheckPartitionVirtualGeneratedExprs. + */ +static void +ATPrepSetExpression(Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing) +{ + HeapTuple tuple; + char attgenerated; + + if (recursing) + return; + + tuple = SearchSysCacheAttName(RelationGetRelid(rel), cmd->name); + if (!HeapTupleIsValid(tuple)) + return; /* error will be reported later */ + attgenerated = ((Form_pg_attribute) GETSTRUCT(tuple))->attgenerated; + ReleaseSysCache(tuple); + + if (attgenerated != ATTRIBUTE_GENERATED_VIRTUAL) + return; + + if (rel->rd_rel->relispartition) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("cannot alter generation expression of virtual generated column \"%s\" of partition \"%s\"", + cmd->name, RelationGetRelationName(rel)), + errhint("Alter the generation expression of the top-level partitioned table instead."))); + + if (!recurse && + rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE && + find_inheritance_children(RelationGetRelid(rel), NoLock) != NIL) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("ALTER TABLE / SET EXPRESSION must be applied to child tables too"))); +} + /* * ALTER TABLE ALTER COLUMN DROP EXPRESSION */ @@ -18854,7 +18898,9 @@ constraints_equivalent(HeapTuple a, HeapTuple b, TupleDesc tupleDesc) * partitioned tables it's a foot-gun. * * The data type must match exactly. If the parent column is NOT NULL then - * the child must be as well. Defaults are not compared, however. + * the child must be as well. Defaults are not compared, however, and neither + * are generation expressions, except for virtual generated columns of a + * partition. */ static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispartition) @@ -18975,6 +19021,68 @@ MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispart } table_close(attrrel, RowExclusiveLock); + + if (ispartition) + CheckPartitionVirtualGeneratedExprs(child_rel, parent_rel); +} + +/* + * CheckPartitionVirtualGeneratedExprs + * Check that each virtual generated column of a partition has the same + * generation expression as in the partitioned table. + * + * Reading through the partitioned table computes the parent's expression, + * while constraints on the partition are checked with its own, so they must + * be the same. + */ +static void +CheckPartitionVirtualGeneratedExprs(Relation partrel, Relation parentrel) +{ + TupleDesc parent_desc = RelationGetDescr(parentrel); + TupleDesc part_desc = RelationGetDescr(partrel); + AttrMap *attmap; + + if (parent_desc->constr == NULL || + !parent_desc->constr->has_generated_virtual) + return; + + attmap = build_attrmap_by_name(part_desc, parent_desc, false); + + for (AttrNumber parent_attno = 1; parent_attno <= parent_desc->natts; parent_attno++) + { + Form_pg_attribute parent_att = TupleDescAttr(parent_desc, parent_attno - 1); + AttrNumber part_attno; + Node *parent_expr; + Node *part_expr; + bool found_whole_row; + + if (parent_att->attisdropped || + parent_att->attgenerated != ATTRIBUTE_GENERATED_VIRTUAL) + continue; + + part_attno = attmap->attnums[parent_attno - 1]; + Assert(part_attno > 0); + + parent_expr = TupleDescGetDefault(parent_desc, parent_attno); + part_expr = TupleDescGetDefault(part_desc, part_attno); + if (parent_expr == NULL || part_expr == NULL) + elog(ERROR, "missing generation expression for column \"%s\"", + NameStr(parent_att->attname)); + + parent_expr = map_variable_attnos(parent_expr, 1, 0, attmap, + InvalidOid, &found_whole_row); + /* generation expressions cannot contain whole-row Vars */ + Assert(!found_whole_row); + + if (!equal(parent_expr, part_expr)) + ereport(ERROR, + (errcode(ERRCODE_INVALID_COLUMN_DEFINITION), + errmsg("virtual generated column \"%s\" of partition \"%s\" must have the same generation expression as the partitioned table", + NameStr(parent_att->attname), + RelationGetRelationName(partrel)))); + } + + free_attrmap(attmap); } /* diff --git a/src/bin/pg_upgrade/check.c b/src/bin/pg_upgrade/check.c index 2d4aaf22a0f..32bc2bda1d6 100644 --- a/src/bin/pg_upgrade/check.c +++ b/src/bin/pg_upgrade/check.c @@ -29,6 +29,7 @@ static void check_for_user_defined_postfix_ops(ClusterInfo *cluster); static void check_for_incompatible_polymorphics(ClusterInfo *cluster); static void check_for_tables_with_oids(ClusterInfo *cluster); static void check_for_not_null_inheritance(ClusterInfo *cluster); +static void check_for_partition_virtual_generated_exprs(ClusterInfo *cluster); static void check_for_gist_inet_ops(ClusterInfo *cluster); static void check_for_new_tablespace_dir(void); static void check_for_user_defined_encoding_conversions(ClusterInfo *cluster); @@ -673,6 +674,15 @@ check_and_dump_old_cluster(void) if (GET_MAJOR_VERSION(old_cluster.major_version) <= 1800) check_for_not_null_inheritance(&old_cluster); + /* + * Virtual generated columns (new in PG 18) of a partition used to be + * allowed to have a different generation expression than the partitioned + * table, but schema restore fails for them now. Verify there are none. + */ + if (GET_MAJOR_VERSION(old_cluster.major_version) >= 1800 && + GET_MAJOR_VERSION(old_cluster.major_version) <= 1900) + check_for_partition_virtual_generated_exprs(&old_cluster); + /* * The btree_gist extension contains gist_inet_ops and gist_cidr_ops * opclasses that do not reliably give correct answers. We want to @@ -1733,6 +1743,70 @@ check_for_not_null_inheritance(ClusterInfo *cluster) check_ok(); } +/* + * check_for_partition_virtual_generated_exprs() + * + * A virtual generated column of a partition must have the same generation + * expression as the partitioned table. Check that the cluster to be upgraded + * has no partitions that differ, which older versions allowed. + */ +static void +check_for_partition_virtual_generated_exprs(ClusterInfo *cluster) +{ + UpgradeTaskReport report; + UpgradeTask *task; + const char *query; + + prep_status("Checking for virtual generated column inconsistencies"); + + report.file = NULL; + snprintf(report.path, sizeof(report.path), "%s/%s", + log_opts.basedir, + "partition_virtual_generated_columns.txt"); + + query = "SELECT nc.nspname, cc.relname, ac.attname " + "FROM pg_catalog.pg_class cc " + " JOIN pg_catalog.pg_namespace nc ON nc.oid = cc.relnamespace " + " JOIN pg_catalog.pg_inherits i ON i.inhrelid = cc.oid " + " JOIN pg_catalog.pg_attribute ac ON ac.attrelid = cc.oid " + " JOIN pg_catalog.pg_attribute ap ON ap.attrelid = i.inhparent " + " AND ap.attname = ac.attname " + " JOIN pg_catalog.pg_attrdef dc ON dc.adrelid = ac.attrelid " + " AND dc.adnum = ac.attnum " + " JOIN pg_catalog.pg_attrdef dp ON dp.adrelid = ap.attrelid " + " AND dp.adnum = ap.attnum " + "WHERE cc.relispartition AND ac.attgenerated = 'v' " + " AND pg_catalog.pg_get_expr(dc.adbin, dc.adrelid) <> " + " pg_catalog.pg_get_expr(dp.adbin, dp.adrelid)"; + + task = upgrade_task_create(); + /* the not-null check's callback reports the same columns */ + upgrade_task_add_step(task, query, + process_inconsistent_notnull, + true, &report); + upgrade_task_run(task, cluster); + upgrade_task_free(task); + + if (report.file) + { + fclose(report.file); + pg_log(PG_REPORT, "fatal"); + pg_fatal("Your installation contains partitions whose virtual generated columns\n" + "have a different generation expression than the partitioned table.\n" + "This is no longer allowed, so the upgrade would fail. You can fix\n" + "this by running\n" + " ALTER TABLE parent ALTER COLUMN column SET EXPRESSION AS (...);\n" + "on the top-level partitioned table of each column. In version 18\n" + "this is not allowed if any table in that partition tree has CHECK\n" + "constraints, so drop them first and add them back afterwards. Rows\n" + "that violate NOT NULL or CHECK with the new expression must be fixed\n" + "first. A list of the problem columns is in the file:\n" + " %s", report.path); + } + else + check_ok(); +} + /* * Callback function for processing results of query for * check_for_gist_inet_ops()'s UpgradeTask. If the query returned any rows diff --git a/src/test/regress/expected/generated_virtual.out b/src/test/regress/expected/generated_virtual.out index b14e10fb5a0..9161647f958 100644 --- a/src/test/regress/expected/generated_virtual.out +++ b/src/test/regress/expected/generated_virtual.out @@ -912,7 +912,11 @@ CREATE TABLE gtest_parent (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWA CREATE TABLE gtest_child PARTITION OF gtest_parent FOR VALUES FROM ('2016-07-01') TO ('2016-08-01'); -- inherits gen expr CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( - f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- overrides gen expr + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- error, must match parent +) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); +ERROR: virtual generated column "f3" of partition "gtest_child2" must have the same generation expression as the partitioned table +CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 2) VIRTUAL -- same as parent, ok ) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); CREATE TABLE gtest_child3 PARTITION OF gtest_parent ( f3 DEFAULT 42 -- error @@ -946,6 +950,11 @@ ERROR: column "f3" inherits from generated column of different kind DETAIL: Parent column is VIRTUAL, child column is STORED. DROP TABLE gtest_child3; CREATE TABLE gtest_child3 (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWAYS AS (f2 * 33) VIRTUAL); +ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); -- error +ERROR: virtual generated column "f3" of partition "gtest_child3" must have the same generation expression as the partitioned table +DROP TABLE gtest_child3; +-- different column order, so the parent's expression has to be mapped +CREATE TABLE gtest_child3 (f3 bigint GENERATED ALWAYS AS (f2 * 2) VIRTUAL, f2 bigint, f1 date NOT NULL); ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); \d gtest_child Table "generated_virtual_tests.gtest_child" @@ -957,21 +966,21 @@ ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09 Partition of: gtest_parent FOR VALUES FROM ('07-01-2016') TO ('08-01-2016') \d gtest_child2 - Table "generated_virtual_tests.gtest_child2" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- + Table "generated_virtual_tests.gtest_child2" + Column | Type | Collation | Nullable | Default +--------+--------+-----------+----------+------------------------------ f1 | date | | not null | f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 22) + f3 | bigint | | | generated always as (f2 * 2) Partition of: gtest_parent FOR VALUES FROM ('08-01-2016') TO ('09-01-2016') \d gtest_child3 - Table "generated_virtual_tests.gtest_child3" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | + Table "generated_virtual_tests.gtest_child3" + Column | Type | Collation | Nullable | Default +--------+--------+-----------+----------+------------------------------ + f3 | bigint | | | generated always as (f2 * 2) f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 33) + f1 | date | | not null | Partition of: gtest_parent FOR VALUES FROM ('09-01-2016') TO ('10-01-2016') INSERT INTO gtest_parent (f1, f2) VALUES ('2016-07-15', 1); @@ -992,14 +1001,14 @@ SELECT tableoid::regclass, * FROM gtest_child ORDER BY 1, 2, 3; gtest_child | 07-15-2016 | 2 | 4 (2 rows) -SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; -- uses child's generation expression, not parent's +SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; tableoid | f1 | f2 | f3 --------------+------------+----+---- - gtest_child2 | 08-15-2016 | 3 | 66 + gtest_child2 | 08-15-2016 | 3 | 6 (1 row) SELECT tableoid::regclass, * FROM gtest_child3 ORDER BY 1, 2, 3; - tableoid | f1 | f2 | f3 + tableoid | f3 | f2 | f1 ----------+----+----+---- (0 rows) @@ -1012,46 +1021,14 @@ SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; gtest_child3 | 09-13-2016 | 1 | 2 (3 rows) --- alter only parent's and one child's generation expression -ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -\d gtest_parent - Partitioned table "generated_virtual_tests.gtest_parent" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------ - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 4) -Partition key: RANGE (f1) -Number of partitions: 3 (Use \d+ to list them.) - -\d gtest_child - Table "generated_virtual_tests.gtest_child" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 10) -Partition of: gtest_parent FOR VALUES FROM ('07-01-2016') TO ('08-01-2016') - -\d gtest_child2 - Table "generated_virtual_tests.gtest_child2" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 22) -Partition of: gtest_parent FOR VALUES FROM ('08-01-2016') TO ('09-01-2016') - -\d gtest_child3 - Table "generated_virtual_tests.gtest_child3" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 33) -Partition of: gtest_parent FOR VALUES FROM ('09-01-2016') TO ('10-01-2016') - +-- cannot alter only parent's or one partition's generation expression +ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -- error +ERROR: ALTER TABLE / SET EXPRESSION must be applied to child tables too +ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -- error +ERROR: cannot alter generation expression of virtual generated column "f3" of partition "gtest_child" +HINT: Alter the generation expression of the top-level partitioned table instead. +-- alter generation expression of parent and all its children altogether +ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; tableoid | f1 | f2 | f3 --------------+------------+----+---- @@ -1060,16 +1037,10 @@ SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; gtest_child3 | 09-13-2016 | 1 | 4 (3 rows) --- check constraint was validated based on each partitions's generation expression -ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 19); -- error -ERROR: check constraint "cc1" of relation "gtest_child" is violated by some row -ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 66); -- error +ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 12); -- error ERROR: check constraint "cc1" of relation "gtest_child2" is violated by some row -ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 <> 33); -- error -ERROR: check constraint "cc1" of relation "gtest_child3" is violated by some row -ALTER TABLE gtest_parent ADD CONSTRAINT cc CHECK (f3 < 67); -- ok +ALTER TABLE gtest_parent ADD CONSTRAINT cc CHECK (f3 < 13); -- ok ALTER TABLE gtest_parent DROP CONSTRAINT cc; --- alter generation expression of parent and all its children altogether ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 2); \d gtest_parent Partitioned table "generated_virtual_tests.gtest_parent" @@ -1103,9 +1074,9 @@ Partition of: gtest_parent FOR VALUES FROM ('08-01-2016') TO ('09-01-2016') Table "generated_virtual_tests.gtest_child3" Column | Type | Collation | Nullable | Default --------+--------+-----------+----------+------------------------------ - f1 | date | | not null | - f2 | bigint | | | f3 | bigint | | | generated always as (f2 * 2) + f2 | bigint | | | + f1 | date | | not null | Partition of: gtest_parent FOR VALUES FROM ('09-01-2016') TO ('10-01-2016') SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; @@ -1894,11 +1865,16 @@ select * from gtest_cursor order by id; commit; drop table gtest_cursor; --- NOT NULL on a partitioned table's virtual column does not prove non-nullness, --- because a partition can have a different generation expression +-- a partition cannot have a different generation expression, which would let +-- the partitioned table's NOT NULL virtual column read as NULL CREATE TABLE gtestnn_parent2 (a int NOT NULL, b int GENERATED ALWAYS AS (nullif(a, 0)) VIRTUAL NOT NULL) PARTITION BY LIST (a); -CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 (b GENERATED ALWAYS AS (a + 1) VIRTUAL) FOR VALUES IN (0); -INSERT INTO gtestnn_parent2 VALUES (0); +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 (b GENERATED ALWAYS AS (a + 1) VIRTUAL) FOR VALUES IN (0); -- error +ERROR: virtual generated column "b" of partition "gtestnn_child2" must have the same generation expression as the partitioned table +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 FOR VALUES IN (0, 1); +INSERT INTO gtestnn_parent2 VALUES (0); -- error +ERROR: null value in column "b" of relation "gtestnn_child2" violates not-null constraint +DETAIL: Failing row contains (0, virtual). +INSERT INTO gtestnn_parent2 VALUES (1); EXPLAIN (COSTS OFF) SELECT a FROM gtestnn_parent2 WHERE a NOT IN (SELECT b FROM gtestnn_parent2); QUERY PLAN diff --git a/src/test/regress/sql/generated_virtual.sql b/src/test/regress/sql/generated_virtual.sql index e62880f941a..c13ff5eb4c6 100644 --- a/src/test/regress/sql/generated_virtual.sql +++ b/src/test/regress/sql/generated_virtual.sql @@ -529,7 +529,10 @@ CREATE TABLE gtest_parent (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWA CREATE TABLE gtest_child PARTITION OF gtest_parent FOR VALUES FROM ('2016-07-01') TO ('2016-08-01'); -- inherits gen expr CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( - f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- overrides gen expr + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- error, must match parent +) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); +CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 2) VIRTUAL -- same as parent, ok ) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); CREATE TABLE gtest_child3 PARTITION OF gtest_parent ( f3 DEFAULT 42 -- error @@ -553,6 +556,10 @@ CREATE TABLE gtest_child3 (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWA ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); -- error DROP TABLE gtest_child3; CREATE TABLE gtest_child3 (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWAYS AS (f2 * 33) VIRTUAL); +ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); -- error +DROP TABLE gtest_child3; +-- different column order, so the parent's expression has to be mapped +CREATE TABLE gtest_child3 (f3 bigint GENERATED ALWAYS AS (f2 * 2) VIRTUAL, f2 bigint, f1 date NOT NULL); ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); \d gtest_child \d gtest_child2 @@ -562,28 +569,21 @@ INSERT INTO gtest_parent (f1, f2) VALUES ('2016-07-15', 2); INSERT INTO gtest_parent (f1, f2) VALUES ('2016-08-15', 3); SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; SELECT tableoid::regclass, * FROM gtest_child ORDER BY 1, 2, 3; -SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; -- uses child's generation expression, not parent's +SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; SELECT tableoid::regclass, * FROM gtest_child3 ORDER BY 1, 2, 3; UPDATE gtest_parent SET f1 = f1 + 60 WHERE f2 = 1; SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; --- alter only parent's and one child's generation expression -ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -\d gtest_parent -\d gtest_child -\d gtest_child2 -\d gtest_child3 -SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; - --- check constraint was validated based on each partitions's generation expression -ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 19); -- error -ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 66); -- error -ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 <> 33); -- error -ALTER TABLE gtest_parent ADD CONSTRAINT cc CHECK (f3 < 67); -- ok -ALTER TABLE gtest_parent DROP CONSTRAINT cc; +-- cannot alter only parent's or one partition's generation expression +ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -- error +ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -- error -- alter generation expression of parent and all its children altogether +ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); +SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; +ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 12); -- error +ALTER TABLE gtest_parent ADD CONSTRAINT cc CHECK (f3 < 13); -- ok +ALTER TABLE gtest_parent DROP CONSTRAINT cc; ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 2); \d gtest_parent \d gtest_child @@ -1012,11 +1012,13 @@ commit; drop table gtest_cursor; --- NOT NULL on a partitioned table's virtual column does not prove non-nullness, --- because a partition can have a different generation expression +-- a partition cannot have a different generation expression, which would let +-- the partitioned table's NOT NULL virtual column read as NULL CREATE TABLE gtestnn_parent2 (a int NOT NULL, b int GENERATED ALWAYS AS (nullif(a, 0)) VIRTUAL NOT NULL) PARTITION BY LIST (a); -CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 (b GENERATED ALWAYS AS (a + 1) VIRTUAL) FOR VALUES IN (0); -INSERT INTO gtestnn_parent2 VALUES (0); +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 (b GENERATED ALWAYS AS (a + 1) VIRTUAL) FOR VALUES IN (0); -- error +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 FOR VALUES IN (0, 1); +INSERT INTO gtestnn_parent2 VALUES (0); -- error +INSERT INTO gtestnn_parent2 VALUES (1); EXPLAIN (COSTS OFF) SELECT a FROM gtestnn_parent2 WHERE a NOT IN (SELECT b FROM gtestnn_parent2); SELECT a FROM gtestnn_parent2 WHERE a NOT IN (SELECT b FROM gtestnn_parent2); -- 2.37.1 (Apple Git-137.1)
nocfbot-v4-REL_18-0001-Require-partitions-to-use-the-parent-s-virtual-gen.patch (application/octet-stream, 23.3K) download From 48980aba1fa531e3a8358c177071d6c18ec0b7c1 Mon Sep 17 00:00:00 2001 From: shihao zhong <zhong950419@gmail.com> Date: Wed, 11 Nov 2026 23:00:18 -0500 Subject: [PATCH v4 REL_18] Require partitions to use the parent's virtual generation expression MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Otherwise a NOT NULL column can read as NULL through the parent. Suggested-by: Álvaro Herrera <alvherre@kurilemu.de> Discussion: https://postgr.es/m/E1xFKs5-0000000116b-2Cge@gemulon.postgresql.org --- doc/src/sgml/ddl.sgml | 7 +- doc/src/sgml/ref/alter_table.sgml | 3 + src/backend/commands/tablecmds.c | 114 +++++++++++++++++- .../regress/expected/generated_virtual.out | 109 ++++++++--------- src/test/regress/sql/generated_virtual.sql | 37 ++++-- 5 files changed, 199 insertions(+), 71 deletions(-) diff --git a/doc/src/sgml/ddl.sgml b/doc/src/sgml/ddl.sgml index ddd7096f6b2..40c66370a3c 100644 --- a/doc/src/sgml/ddl.sgml +++ b/doc/src/sgml/ddl.sgml @@ -451,8 +451,11 @@ CREATE TABLE people ( <listitem> <para> If a parent column is a generated column, its child column must also - be a generated column of the same kind (stored or virtual); however, - the child column can have a different generation expression. + be a generated column of the same kind (stored or virtual). + In addition, for virtual generated columns of a partition, the + generation expression must be identical to that of the partitioned + table. In all other cases, the child column can have a different + generation expression. </para> <para> diff --git a/doc/src/sgml/ref/alter_table.sgml b/doc/src/sgml/ref/alter_table.sgml index 31f2d91418b..d6a009a54a3 100644 --- a/doc/src/sgml/ref/alter_table.sgml +++ b/doc/src/sgml/ref/alter_table.sgml @@ -272,6 +272,9 @@ WITH ( MODULUS <replaceable class="parameter">numeric_literal</replaceable>, REM This form replaces the expression of a generated column. Existing data in a stored generated column is rewritten and all the future changes will apply the new generation expression. + The expression of a virtual generated column cannot be changed for a + partition alone, or with <literal>ONLY</literal> for a partitioned table + that has partitions. </para> <para> diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 5059909833e..04c51def0e4 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -378,6 +378,7 @@ static List *MergeCheckConstraint(List *constraints, const char *name, Node *exp static void MergeChildAttribute(List *inh_columns, int exist_attno, int newcol_attno, const ColumnDef *newdef); static ColumnDef *MergeInheritedAttribute(List *inh_columns, int exist_attno, const ColumnDef *newdef); static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispartition); +static void CheckPartitionVirtualGeneratedExprs(Relation partrel, Relation parentrel); static void MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel); static void StoreCatalogInheritance(Oid relationId, List *supers, bool child_is_partition); @@ -522,6 +523,7 @@ static ObjectAddress ATExecDropIdentity(Relation rel, const char *colName, bool bool recurse, bool recursing); static ObjectAddress ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName, Node *newExpr, LOCKMODE lockmode); +static void ATPrepSetExpression(Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing); static void ATPrepDropExpression(Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode); static ObjectAddress ATExecDropExpression(Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode); static ObjectAddress ATExecSetStatistics(Relation rel, const char *colName, int16 colNum, @@ -1142,6 +1144,8 @@ DefineRelation(CreateStmt *stmt, char relkind, Oid ownerId, errmsg("\"%s\" is not partitioned", RelationGetRelationName(parent)))); + CheckPartitionVirtualGeneratedExprs(rel, parent); + /* * The partition constraint of the default partition depends on the * partition bounds of every other partition. It is possible that @@ -3058,8 +3062,8 @@ MergeAttributes(List *columns, const List *supers, char relpersistence, * Check for conflicts related to generated columns. * * Same rules as above: generated-ness has to match the - * parent, but the contents of the generation expression - * can be different. + * parent. We don't check the expression itself here; + * CheckPartitionVirtualGeneratedExprs will do so. */ if (coldef->generated) { @@ -5036,6 +5040,7 @@ ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd, case AT_SetExpression: /* ALTER COLUMN SET EXPRESSION */ ATSimplePermissions(cmd->subtype, rel, ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE); + ATPrepSetExpression(rel, cmd, recurse, recursing); ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context); pass = AT_PASS_SET_EXPRESSION; break; @@ -8774,6 +8779,45 @@ ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName, return address; } +/* + * ALTER TABLE ALTER COLUMN SET EXPRESSION + * + * The expression of a virtual generated column can only be changed for a + * whole partition tree. See CheckPartitionVirtualGeneratedExprs. + */ +static void +ATPrepSetExpression(Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing) +{ + HeapTuple tuple; + char attgenerated; + + if (recursing) + return; + + tuple = SearchSysCacheAttName(RelationGetRelid(rel), cmd->name); + if (!HeapTupleIsValid(tuple)) + return; /* error will be reported later */ + attgenerated = ((Form_pg_attribute) GETSTRUCT(tuple))->attgenerated; + ReleaseSysCache(tuple); + + if (attgenerated != ATTRIBUTE_GENERATED_VIRTUAL) + return; + + if (rel->rd_rel->relispartition) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("cannot alter generation expression of virtual generated column \"%s\" of partition \"%s\"", + cmd->name, RelationGetRelationName(rel)), + errhint("Alter the generation expression of the top-level partitioned table instead."))); + + if (!recurse && + rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE && + find_inheritance_children(RelationGetRelid(rel), NoLock) != NIL) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("ALTER TABLE / SET EXPRESSION must be applied to child tables too"))); +} + /* * ALTER TABLE ALTER COLUMN DROP EXPRESSION */ @@ -17551,7 +17595,9 @@ constraints_equivalent(HeapTuple a, HeapTuple b, TupleDesc tupleDesc) * partitioned tables it's a foot-gun. * * The data type must match exactly. If the parent column is NOT NULL then - * the child must be as well. Defaults are not compared, however. + * the child must be as well. Defaults are not compared, however, and neither + * are generation expressions, except for virtual generated columns of a + * partition. */ static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispartition) @@ -17672,6 +17718,68 @@ MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispart } table_close(attrrel, RowExclusiveLock); + + if (ispartition) + CheckPartitionVirtualGeneratedExprs(child_rel, parent_rel); +} + +/* + * CheckPartitionVirtualGeneratedExprs + * Check that each virtual generated column of a partition has the same + * generation expression as in the partitioned table. + * + * Reading through the partitioned table computes the parent's expression, + * while constraints on the partition are checked with its own, so they must + * be the same. + */ +static void +CheckPartitionVirtualGeneratedExprs(Relation partrel, Relation parentrel) +{ + TupleDesc parent_desc = RelationGetDescr(parentrel); + TupleDesc part_desc = RelationGetDescr(partrel); + AttrMap *attmap; + + if (parent_desc->constr == NULL || + !parent_desc->constr->has_generated_virtual) + return; + + attmap = build_attrmap_by_name(part_desc, parent_desc, false); + + for (AttrNumber parent_attno = 1; parent_attno <= parent_desc->natts; parent_attno++) + { + Form_pg_attribute parent_att = TupleDescAttr(parent_desc, parent_attno - 1); + AttrNumber part_attno; + Node *parent_expr; + Node *part_expr; + bool found_whole_row; + + if (parent_att->attisdropped || + parent_att->attgenerated != ATTRIBUTE_GENERATED_VIRTUAL) + continue; + + part_attno = attmap->attnums[parent_attno - 1]; + Assert(part_attno > 0); + + parent_expr = TupleDescGetDefault(parent_desc, parent_attno); + part_expr = TupleDescGetDefault(part_desc, part_attno); + if (parent_expr == NULL || part_expr == NULL) + elog(ERROR, "missing generation expression for column \"%s\"", + NameStr(parent_att->attname)); + + parent_expr = map_variable_attnos(parent_expr, 1, 0, attmap, + InvalidOid, &found_whole_row); + /* generation expressions cannot contain whole-row Vars */ + Assert(!found_whole_row); + + if (!equal(parent_expr, part_expr)) + ereport(ERROR, + (errcode(ERRCODE_INVALID_COLUMN_DEFINITION), + errmsg("virtual generated column \"%s\" of partition \"%s\" must have the same generation expression as the partitioned table", + NameStr(parent_att->attname), + RelationGetRelationName(partrel)))); + } + + free_attrmap(attmap); } /* diff --git a/src/test/regress/expected/generated_virtual.out b/src/test/regress/expected/generated_virtual.out index 03698488907..5eb3222d9d4 100644 --- a/src/test/regress/expected/generated_virtual.out +++ b/src/test/regress/expected/generated_virtual.out @@ -882,7 +882,11 @@ CREATE TABLE gtest_parent (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWA CREATE TABLE gtest_child PARTITION OF gtest_parent FOR VALUES FROM ('2016-07-01') TO ('2016-08-01'); -- inherits gen expr CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( - f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- overrides gen expr + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- error, must match parent +) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); +ERROR: virtual generated column "f3" of partition "gtest_child2" must have the same generation expression as the partitioned table +CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 2) VIRTUAL -- same as parent, ok ) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); CREATE TABLE gtest_child3 PARTITION OF gtest_parent ( f3 DEFAULT 42 -- error @@ -916,6 +920,11 @@ ERROR: column "f3" inherits from generated column of different kind DETAIL: Parent column is VIRTUAL, child column is STORED. DROP TABLE gtest_child3; CREATE TABLE gtest_child3 (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWAYS AS (f2 * 33) VIRTUAL); +ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); -- error +ERROR: virtual generated column "f3" of partition "gtest_child3" must have the same generation expression as the partitioned table +DROP TABLE gtest_child3; +-- different column order, so the parent's expression has to be mapped +CREATE TABLE gtest_child3 (f3 bigint GENERATED ALWAYS AS (f2 * 2) VIRTUAL, f2 bigint, f1 date NOT NULL); ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); \d gtest_child Table "generated_virtual_tests.gtest_child" @@ -927,21 +936,21 @@ ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09 Partition of: gtest_parent FOR VALUES FROM ('07-01-2016') TO ('08-01-2016') \d gtest_child2 - Table "generated_virtual_tests.gtest_child2" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- + Table "generated_virtual_tests.gtest_child2" + Column | Type | Collation | Nullable | Default +--------+--------+-----------+----------+------------------------------ f1 | date | | not null | f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 22) + f3 | bigint | | | generated always as (f2 * 2) Partition of: gtest_parent FOR VALUES FROM ('08-01-2016') TO ('09-01-2016') \d gtest_child3 - Table "generated_virtual_tests.gtest_child3" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | + Table "generated_virtual_tests.gtest_child3" + Column | Type | Collation | Nullable | Default +--------+--------+-----------+----------+------------------------------ + f3 | bigint | | | generated always as (f2 * 2) f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 33) + f1 | date | | not null | Partition of: gtest_parent FOR VALUES FROM ('09-01-2016') TO ('10-01-2016') INSERT INTO gtest_parent (f1, f2) VALUES ('2016-07-15', 1); @@ -962,14 +971,14 @@ SELECT tableoid::regclass, * FROM gtest_child ORDER BY 1, 2, 3; gtest_child | 07-15-2016 | 2 | 4 (2 rows) -SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; -- uses child's generation expression, not parent's +SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; tableoid | f1 | f2 | f3 --------------+------------+----+---- - gtest_child2 | 08-15-2016 | 3 | 66 + gtest_child2 | 08-15-2016 | 3 | 6 (1 row) SELECT tableoid::regclass, * FROM gtest_child3 ORDER BY 1, 2, 3; - tableoid | f1 | f2 | f3 + tableoid | f3 | f2 | f1 ----------+----+----+---- (0 rows) @@ -982,46 +991,14 @@ SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; gtest_child3 | 09-13-2016 | 1 | 2 (3 rows) --- alter only parent's and one child's generation expression -ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -\d gtest_parent - Partitioned table "generated_virtual_tests.gtest_parent" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------ - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 4) -Partition key: RANGE (f1) -Number of partitions: 3 (Use \d+ to list them.) - -\d gtest_child - Table "generated_virtual_tests.gtest_child" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 10) -Partition of: gtest_parent FOR VALUES FROM ('07-01-2016') TO ('08-01-2016') - -\d gtest_child2 - Table "generated_virtual_tests.gtest_child2" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 22) -Partition of: gtest_parent FOR VALUES FROM ('08-01-2016') TO ('09-01-2016') - -\d gtest_child3 - Table "generated_virtual_tests.gtest_child3" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 33) -Partition of: gtest_parent FOR VALUES FROM ('09-01-2016') TO ('10-01-2016') - +-- cannot alter only parent's or one partition's generation expression +ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -- error +ERROR: ALTER TABLE / SET EXPRESSION must be applied to child tables too +ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -- error +ERROR: cannot alter generation expression of virtual generated column "f3" of partition "gtest_child" +HINT: Alter the generation expression of the top-level partitioned table instead. +-- alter generation expression of parent and all its children altogether +ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; tableoid | f1 | f2 | f3 --------------+------------+----+---- @@ -1030,7 +1007,10 @@ SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; gtest_child3 | 09-13-2016 | 1 | 4 (3 rows) --- alter generation expression of parent and all its children altogether +ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 12); -- error +ERROR: check constraint "cc1" of relation "gtest_child2" is violated by some row +ALTER TABLE gtest_parent ADD CONSTRAINT cc CHECK (f3 < 13); -- ok +ALTER TABLE gtest_parent DROP CONSTRAINT cc; ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 2); \d gtest_parent Partitioned table "generated_virtual_tests.gtest_parent" @@ -1064,9 +1044,9 @@ Partition of: gtest_parent FOR VALUES FROM ('08-01-2016') TO ('09-01-2016') Table "generated_virtual_tests.gtest_child3" Column | Type | Collation | Nullable | Default --------+--------+-----------+----------+------------------------------ - f1 | date | | not null | - f2 | bigint | | | f3 | bigint | | | generated always as (f2 * 2) + f2 | bigint | | | + f1 | date | | not null | Partition of: gtest_parent FOR VALUES FROM ('09-01-2016') TO ('10-01-2016') SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; @@ -1812,3 +1792,20 @@ select * from gtest_cursor order by id; commit; drop table gtest_cursor; +-- a partition cannot have a different generation expression, which would let +-- the partitioned table's NOT NULL virtual column read as NULL +CREATE TABLE gtestnn_parent2 (a int NOT NULL, b int GENERATED ALWAYS AS (nullif(a, 0)) VIRTUAL NOT NULL) PARTITION BY LIST (a); +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 (b GENERATED ALWAYS AS (a + 1) VIRTUAL) FOR VALUES IN (0); -- error +ERROR: virtual generated column "b" of partition "gtestnn_child2" must have the same generation expression as the partitioned table +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 FOR VALUES IN (0, 1); +INSERT INTO gtestnn_parent2 VALUES (0); -- error +ERROR: null value in column "b" of relation "gtestnn_child2" violates not-null constraint +DETAIL: Failing row contains (0, virtual). +INSERT INTO gtestnn_parent2 VALUES (1); +SELECT a, b FROM gtestnn_parent2; + a | b +---+--- + 1 | 1 +(1 row) + +DROP TABLE gtestnn_parent2; diff --git a/src/test/regress/sql/generated_virtual.sql b/src/test/regress/sql/generated_virtual.sql index b1b92b2ced5..d1bbf9352d7 100644 --- a/src/test/regress/sql/generated_virtual.sql +++ b/src/test/regress/sql/generated_virtual.sql @@ -514,7 +514,10 @@ CREATE TABLE gtest_parent (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWA CREATE TABLE gtest_child PARTITION OF gtest_parent FOR VALUES FROM ('2016-07-01') TO ('2016-08-01'); -- inherits gen expr CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( - f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- overrides gen expr + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- error, must match parent +) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); +CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 2) VIRTUAL -- same as parent, ok ) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); CREATE TABLE gtest_child3 PARTITION OF gtest_parent ( f3 DEFAULT 42 -- error @@ -538,6 +541,10 @@ CREATE TABLE gtest_child3 (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWA ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); -- error DROP TABLE gtest_child3; CREATE TABLE gtest_child3 (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWAYS AS (f2 * 33) VIRTUAL); +ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); -- error +DROP TABLE gtest_child3; +-- different column order, so the parent's expression has to be mapped +CREATE TABLE gtest_child3 (f3 bigint GENERATED ALWAYS AS (f2 * 2) VIRTUAL, f2 bigint, f1 date NOT NULL); ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); \d gtest_child \d gtest_child2 @@ -547,21 +554,21 @@ INSERT INTO gtest_parent (f1, f2) VALUES ('2016-07-15', 2); INSERT INTO gtest_parent (f1, f2) VALUES ('2016-08-15', 3); SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; SELECT tableoid::regclass, * FROM gtest_child ORDER BY 1, 2, 3; -SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; -- uses child's generation expression, not parent's +SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; SELECT tableoid::regclass, * FROM gtest_child3 ORDER BY 1, 2, 3; UPDATE gtest_parent SET f1 = f1 + 60 WHERE f2 = 1; SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; --- alter only parent's and one child's generation expression -ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -\d gtest_parent -\d gtest_child -\d gtest_child2 -\d gtest_child3 -SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; +-- cannot alter only parent's or one partition's generation expression +ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -- error +ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -- error -- alter generation expression of parent and all its children altogether +ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); +SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; +ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 12); -- error +ALTER TABLE gtest_parent ADD CONSTRAINT cc CHECK (f3 < 13); -- ok +ALTER TABLE gtest_parent DROP CONSTRAINT cc; ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 2); \d gtest_parent \d gtest_child @@ -969,3 +976,13 @@ select * from gtest_cursor order by id; commit; drop table gtest_cursor; + +-- a partition cannot have a different generation expression, which would let +-- the partitioned table's NOT NULL virtual column read as NULL +CREATE TABLE gtestnn_parent2 (a int NOT NULL, b int GENERATED ALWAYS AS (nullif(a, 0)) VIRTUAL NOT NULL) PARTITION BY LIST (a); +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 (b GENERATED ALWAYS AS (a + 1) VIRTUAL) FOR VALUES IN (0); -- error +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 FOR VALUES IN (0, 1); +INSERT INTO gtestnn_parent2 VALUES (0); -- error +INSERT INTO gtestnn_parent2 VALUES (1); +SELECT a, b FROM gtestnn_parent2; +DROP TABLE gtestnn_parent2; -- 2.37.1 (Apple Git-137.1)
^ permalink raw reply [nested|flat] 24+ messages in thread

* Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned
  2026-10-10 00:23 pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Richard Guo <rguo@postgresql.org>
  2026-10-13 12:42 ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-10-13 14:34   ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Richard Guo <guofenglinux@gmail.com>
  2026-10-13 15:41     ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-10-13 16:00       ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-10-14 04:39         ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-10-26 17:40           ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Manu <manuelreyesbravo@gmail.com>
  2026-10-27 03:10             ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-11-11 15:41               ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-11-11 15:47                 ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-11-12 04:36                   ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-11-14 01:12                     ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Manu <manuelreyesbravo@gmail.com>
  2026-11-15 03:36                       ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
@ 2026-11-15 21:15                         ` Zsolt Parragi <zsolt.parragi@percona.com>
  2026-11-17 01:43                           ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  0 siblings, 1 reply; 24+ messages in thread

From: Zsolt Parragi @ 2026-11-15 21:15 UTC (permalink / raw)
  To: shihao zhong <zhong950419@gmail.com>; +Cc: pgsql-hackers@lists.postgresql.org, Manu <manuelreyesbravo@gmail.com>; Álvaro Herrera <alvherre@kurilemu.de>; Richard Guo <guofenglinux@gmail.com>

Hello

With this restriction master can't create divergent partitions
anymore, and pg_upgrade refuses them, so is d8444163d still needed on
master after this patch?

There are still at least two ways to still end up with a problematic
partition. In both cases the new check then rejects a pg_dump of the
cluster at restore:

1. Explicit vs implicit cast

    CREATE TABLE q (k int, x numeric, b numeric(10,0) GENERATED ALWAYS
AS (x) VIRTUAL) PARTITION BY RANGE (k);
    CREATE TABLE q1 (k int, x numeric, b numeric(10,0) GENERATED
ALWAYS AS (x::numeric(10,0)) VIRTUAL);
    ALTER TABLE q ATTACH PARTITION q1 FOR VALUES FROM (0) TO (10);   -- accepted
    INSERT INTO q VALUES (1, 1.25);
    ALTER TABLE q ALTER COLUMN b TYPE numeric(10,2);
    SELECT (SELECT b FROM q) AS via_parent, (SELECT b FROM q1) AS direct;
     via_parent | direct
    ------------+--------
           1.25 |   1.00

After this q has "x" and q1 has "(x)::numeric(10,0)", and restoring
pg_dump -t q -t q1 fails:

    ERROR:  virtual generated column "b" of partition "q1" must have
the same generation expression as the partitioned table

equal() ignores CoercionForm, so the check accepts the pair, but ALTER
TYPE re-coerces each table after strip_implicit_coercions(), which
only removes the parent's cast.

2. ONLY with a detach-pending partition

+	if (!recurse &&
+		rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE &&
+		find_inheritance_children(RelationGetRelid(rel), NoLock) != NIL)

find_inheritance_children() skips detach-pending partitions.

After a DETACH PARTITION f1 CONCURRENTLY that got cancelled, ALTER
TABLE ONLY f ALTER COLUMN b SET EXPRESSION AS (a3) succeeds while f1
keeps a2.

Also, the documentation has one more leftover:

ddl.sgml, a few lines below the paragraph v4 changes, still says:

    from the parent.  <command>ALTER TABLE ... ATTACH PARTITION</command>
    will insist that parent and child columns already match as to
    generation status, but it will not require their generation
    expressions to match.


And there's a similar issue which I think also needs a fix together with this:
Plain inheritance has the same wrong results, both on master and with the patch:

CREATE TABLE cp (a int, b int GENERATED ALWAYS AS (a - 10) VIRTUAL
CHECK (b > 0));
CREATE TABLE cc (b int GENERATED ALWAYS AS (a + 100) VIRTUAL) INHERITS (cp);
INSERT INTO cc VALUES (1);
SELECT a, b FROM cp; -- 1 | -9
SET constraint_exclusion = on;
SELECT a, b FROM cp WHERE b < 0; -- 0 rows






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

* Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned
  2026-10-10 00:23 pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Richard Guo <rguo@postgresql.org>
  2026-10-13 12:42 ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-10-13 14:34   ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Richard Guo <guofenglinux@gmail.com>
  2026-10-13 15:41     ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-10-13 16:00       ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-10-14 04:39         ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-10-26 17:40           ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Manu <manuelreyesbravo@gmail.com>
  2026-10-27 03:10             ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-11-11 15:41               ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-11-11 15:47                 ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-11-12 04:36                   ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-11-14 01:12                     ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Manu <manuelreyesbravo@gmail.com>
  2026-11-15 03:36                       ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-11-15 21:15                         ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Zsolt Parragi <zsolt.parragi@percona.com>
@ 2026-11-17 01:43                           ` shihao zhong <zhong950419@gmail.com>
  2026-11-17 19:26                             ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Zsolt Parragi <zsolt.parragi@percona.com>
  0 siblings, 1 reply; 24+ messages in thread

From: shihao zhong @ 2026-11-17 01:43 UTC (permalink / raw)
  To: Zsolt Parragi <zsolt.parragi@percona.com>; +Cc: pgsql-hackers@lists.postgresql.org, Manu <manuelreyesbravo@gmail.com>; Álvaro Herrera <alvherre@kurilemu.de>; Richard Guo <guofenglinux@gmail.com>

Hi Zsolt,

Thanks for your review, I appreciate it.

> With this restriction master can't create divergent partitions
> anymore, and pg_upgrade refuses them, so is d8444163d still needed on
> master after this patch?

19 still needs it. A 19 cluster may already have such partitions,
and a minor update does not run pg_upgrade.

> 1. Explicit vs implicit cast

v5 compares the deparsed text, which is what pg_dump writes.

> 2. ONLY with a detach-pending partition

The recursive SET EXPRESSION skipped those partitions too.
ONLY now counts them as children. Without ONLY, the command asks to
finish the detach first.

> ddl.sgml, a few lines below the paragraph
fixed.

> Plain inheritance has the same wrong results, both on master and with
> the patch:

v5 applies the same rule to plain inheritance, so your cc example now
fails at CREATE TABLE. pg_upgrade refuses such children too.

I also found CREATE TABLE ... (LIKE ...) INHERITS skips these checks.
I think it needs to have its own thread.

Thanks,
Shihao

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

nocfbot-v5-REL_18-0001-Require-child-tables-to-use-the-parent-s-virtual-gen.patch (application/octet-stream, 38.5K) download From a408b462103c1f26788510d99016ca9a04073d60 Mon Sep 17 00:00:00 2001 From: shihao zhong <zhong950419@gmail.com> Date: Mon, 16 Nov 2026 08:04:02 -0500 Subject: [PATCH v5] Require child tables to use the parent's virtual generation expression MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Otherwise a NOT NULL or CHECK constraint can be wrong for rows read through the parent. Suggested-by: Álvaro Herrera <alvherre@kurilemu.de> Discussion: https://postgr.es/m/E1xFKs5-0000000116b-2Cge@gemulon.postgresql.org --- doc/src/sgml/ddl.sgml | 18 +- doc/src/sgml/ref/alter_table.sgml | 4 + src/backend/commands/tablecmds.c | 219 +++++++++++++++++- .../regress/expected/generated_virtual.out | 175 ++++++++------ src/test/regress/sql/generated_virtual.sql | 65 ++++-- 5 files changed, 376 insertions(+), 105 deletions(-) diff --git a/doc/src/sgml/ddl.sgml b/doc/src/sgml/ddl.sgml index ddd7096f6b2..ad416a2bdf7 100644 --- a/doc/src/sgml/ddl.sgml +++ b/doc/src/sgml/ddl.sgml @@ -451,8 +451,10 @@ CREATE TABLE people ( <listitem> <para> If a parent column is a generated column, its child column must also - be a generated column of the same kind (stored or virtual); however, - the child column can have a different generation expression. + be a generated column of the same kind (stored or virtual). + A virtual generated child column must have the same generation + expression as the parent column. A stored generated child column + can have a different generation expression. </para> <para> @@ -478,8 +480,9 @@ CREATE TABLE people ( ... INHERITS</command>, then its <literal>GENERATED</literal> clause will automatically be copied from the parent. <command>ALTER TABLE ... INHERIT</command> will insist that parent and child columns - already match as to generation status, but it will not require their - generation expressions to match. + already match as to generation status, but it will only require + their generation expressions to match for virtual generated + columns. </para> </listitem> <listitem> @@ -490,8 +493,8 @@ CREATE TABLE people ( its <literal>GENERATED</literal> clause will automatically be copied from the parent. <command>ALTER TABLE ... ATTACH PARTITION</command> will insist that parent and child columns already match as to - generation status, but it will not require their generation - expressions to match. + generation status, but it will only require their generation + expressions to match for virtual generated columns. </para> </listitem> <listitem> @@ -499,7 +502,8 @@ CREATE TABLE people ( In case of multiple inheritance, if one parent column is a generated column, then all parent columns must be generated columns. If they do not all have the same generation expression, then the desired - expression for the child must be specified explicitly. + expression for the child must be specified explicitly. For virtual + generated columns, they must all have the same generation expression. </para> </listitem> </itemizedlist> diff --git a/doc/src/sgml/ref/alter_table.sgml b/doc/src/sgml/ref/alter_table.sgml index 31f2d91418b..982524eee2d 100644 --- a/doc/src/sgml/ref/alter_table.sgml +++ b/doc/src/sgml/ref/alter_table.sgml @@ -272,6 +272,10 @@ WITH ( MODULUS <replaceable class="parameter">numeric_literal</replaceable>, REM This form replaces the expression of a generated column. Existing data in a stored generated column is rewritten and all the future changes will apply the new generation expression. + The expression of a virtual generated column cannot be changed for an + inherited column, or with <literal>ONLY</literal> for a table that has + child tables. It has to be changed for the whole inheritance tree, + from the top. </para> <para> diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 5059909833e..0782a3ff535 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -378,6 +378,7 @@ static List *MergeCheckConstraint(List *constraints, const char *name, Node *exp static void MergeChildAttribute(List *inh_columns, int exist_attno, int newcol_attno, const ColumnDef *newdef); static ColumnDef *MergeInheritedAttribute(List *inh_columns, int exist_attno, const ColumnDef *newdef); static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispartition); +static void CheckVirtualGeneratedExprs(Relation childrel, Relation parentrel); static void MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel); static void StoreCatalogInheritance(Oid relationId, List *supers, bool child_is_partition); @@ -522,6 +523,8 @@ static ObjectAddress ATExecDropIdentity(Relation rel, const char *colName, bool bool recurse, bool recursing); static ObjectAddress ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName, Node *newExpr, LOCKMODE lockmode); +static void ATPrepSetExpression(Relation rel, AlterTableCmd *cmd, bool recurse, + bool recursing, LOCKMODE lockmode); static void ATPrepDropExpression(Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode); static ObjectAddress ATExecDropExpression(Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode); static ObjectAddress ATExecSetStatistics(Relation rel, const char *colName, int16 colNum, @@ -1118,6 +1121,15 @@ DefineRelation(CreateStmt *stmt, char relkind, Oid ownerId, */ CommandCounterIncrement(); + /* Virtual generated columns must use the parents' expressions */ + foreach_oid(parentId, inheritOids) + { + Relation parent = table_open(parentId, NoLock); + + CheckVirtualGeneratedExprs(rel, parent); + table_close(parent, NoLock); + } + /* Process and store partition bound, if any. */ if (stmt->partbound) { @@ -3058,8 +3070,8 @@ MergeAttributes(List *columns, const List *supers, char relpersistence, * Check for conflicts related to generated columns. * * Same rules as above: generated-ness has to match the - * parent, but the contents of the generation expression - * can be different. + * parent. For virtual generated columns, + * CheckVirtualGeneratedExprs checks the expression later. */ if (coldef->generated) { @@ -3138,7 +3150,8 @@ MergeAttributes(List *columns, const List *supers, char relpersistence, (errcode(ERRCODE_INVALID_COLUMN_DEFINITION), errmsg("column \"%s\" inherits conflicting generation expressions", def->colname), - errhint("To resolve the conflict, specify a generation expression explicitly."))); + def->generated == ATTRIBUTE_GENERATED_STORED ? + errhint("To resolve the conflict, specify a generation expression explicitly.") : 0)); else ereport(ERROR, (errcode(ERRCODE_INVALID_COLUMN_DEFINITION), @@ -3346,10 +3359,11 @@ MergeChildAttribute(List *inh_columns, int exist_attno, int newcol_attno, const * * If the parent column is generated, the child column will be made a * generated column if it isn't already. If it is a generated column, - * we'll take its generation expression in preference to the parent's. We - * must check that the child column doesn't specify a default value or - * identity, which matches the rules for a single column in - * parse_utilcmd.c. + * we'll take its generation expression in preference to the parent's, + * though for a virtual generated column CheckVirtualGeneratedExprs later + * requires the two to match. We must check that the child column doesn't + * specify a default value or identity, which matches the rules for a + * single column in parse_utilcmd.c. * * Conversely, if the parent column is not generated, the child column * can't be either. (We used to allow that, but it results in being able @@ -5036,6 +5050,7 @@ ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd, case AT_SetExpression: /* ALTER COLUMN SET EXPRESSION */ ATSimplePermissions(cmd->subtype, rel, ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE); + ATPrepSetExpression(rel, cmd, recurse, recursing, lockmode); ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context); pass = AT_PASS_SET_EXPRESSION; break; @@ -7310,6 +7325,33 @@ ATExecAddColumn(List **wqueue, AlteredTableInfo *tab, Relation rel, get_collation_name(ccollid), get_collation_name(childatt->attcollation)))); + /* + * Child column must be virtual generated if and only if parent + * column is. Our caller checks the expression. + */ + if ((colDef->generated == ATTRIBUTE_GENERATED_VIRTUAL) != + (childatt->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)) + { + if (!childatt->attgenerated) + ereport(ERROR, + (errcode(ERRCODE_DATATYPE_MISMATCH), + errmsg("column \"%s\" in child table must be a generated column", + colDef->colname))); + else if (!colDef->generated) + ereport(ERROR, + (errcode(ERRCODE_DATATYPE_MISMATCH), + errmsg("column \"%s\" in child table must not be a generated column", + colDef->colname))); + else + ereport(ERROR, + (errcode(ERRCODE_DATATYPE_MISMATCH), + errmsg("column \"%s\" inherits from generated column of different kind", + colDef->colname), + errdetail("Parent column is %s, child column is %s.", + colDef->generated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL", + childatt->attgenerated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL"))); + } + /* Bump the existing child att's inhcount */ if (pg_add_s16_overflow(childatt->attinhcount, 1, &childatt->attinhcount)) @@ -7653,6 +7695,13 @@ ATExecAddColumn(List **wqueue, AlteredTableInfo *tab, Relation rel, &childcmd, recurse, true, lockmode, cur_pass, context); + /* The child may have had the column already */ + if (colDef->generated == ATTRIBUTE_GENERATED_VIRTUAL) + { + CommandCounterIncrement(); + CheckVirtualGeneratedExprs(childrel, rel); + } + table_close(childrel, NoLock); } @@ -8774,6 +8823,94 @@ ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName, return address; } +/* + * ALTER TABLE ALTER COLUMN SET EXPRESSION + * + * A virtual generated column must have the same expression in a table and in + * all its parents and children, see CheckVirtualGeneratedExprs. So the + * expression can only be changed for a whole inheritance tree, from the top. + */ +static void +ATPrepSetExpression(Relation rel, AlterTableCmd *cmd, bool recurse, + bool recursing, LOCKMODE lockmode) +{ + HeapTuple tuple; + Form_pg_attribute attTup; + char attgenerated; + int16 attinhcount; + List *children; + List *numparents; + ListCell *lc; + ListCell *lc2; + + if (recursing) + return; + + tuple = SearchSysCacheAttName(RelationGetRelid(rel), cmd->name); + if (!HeapTupleIsValid(tuple)) + return; /* error will be reported later */ + attTup = (Form_pg_attribute) GETSTRUCT(tuple); + attgenerated = attTup->attgenerated; + attinhcount = attTup->attinhcount; + ReleaseSysCache(tuple); + + if (attgenerated != ATTRIBUTE_GENERATED_VIRTUAL) + return; + + if (attinhcount > 0) + ereport(ERROR, + (errcode(ERRCODE_INVALID_TABLE_DEFINITION), + errmsg("cannot alter inherited column \"%s\"", cmd->name), + errhint("Alter the generation expression of the top-level parent table instead."))); + + /* Partitions pending detach count here, as they still have the column */ + if (!recurse) + { + if (find_inheritance_children_extended(RelationGetRelid(rel), false, + NoLock, NULL, NULL) != NIL) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("ALTER TABLE / SET EXPRESSION must be applied to child tables too"))); + return; + } + + /* + * Recursion skips partitions pending detach, so they would keep the old + * expression. Also, a child with another parent outside this tree would + * end up with a different expression than that parent. + */ + children = find_all_inheritors(RelationGetRelid(rel), lockmode, &numparents); + forboth(lc, children, lc2, numparents) + { + Oid childrelid = lfirst_oid(lc); + bool detached_exist = false; + + (void) find_inheritance_children_extended(childrelid, true, NoLock, + &detached_exist, NULL); + if (detached_exist) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), + errmsg("cannot alter generation expression of column \"%s\" while a partition of \"%s\" is pending detach", + cmd->name, get_rel_name(childrelid)), + errhint("Use ALTER TABLE ... DETACH PARTITION ... FINALIZE to complete the pending detach operation."))); + + if (childrelid == RelationGetRelid(rel)) + continue; + + tuple = SearchSysCacheAttName(childrelid, cmd->name); + if (!HeapTupleIsValid(tuple)) + continue; /* error will be reported later */ + attinhcount = ((Form_pg_attribute) GETSTRUCT(tuple))->attinhcount; + ReleaseSysCache(tuple); + + if (attinhcount > lfirst_int(lc2)) + ereport(ERROR, + (errcode(ERRCODE_INVALID_TABLE_DEFINITION), + errmsg("cannot alter inherited column \"%s\" of relation \"%s\"", + cmd->name, get_rel_name(childrelid)))); + } +} + /* * ALTER TABLE ALTER COLUMN DROP EXPRESSION */ @@ -17551,7 +17688,8 @@ constraints_equivalent(HeapTuple a, HeapTuple b, TupleDesc tupleDesc) * partitioned tables it's a foot-gun. * * The data type must match exactly. If the parent column is NOT NULL then - * the child must be as well. Defaults are not compared, however. + * the child must be as well. Defaults are not compared, however, and neither + * are generation expressions, except for virtual generated columns. */ static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispartition) @@ -17672,6 +17810,71 @@ MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispart } table_close(attrrel, RowExclusiveLock); + + CheckVirtualGeneratedExprs(child_rel, parent_rel); +} + +/* + * CheckVirtualGeneratedExprs + * Check that each virtual generated column of a child table has the same + * generation expression as in the parent. + * + * Reading through the parent computes the parent's expression, while + * constraints on the child are checked with its own, so they must be the + * same. As in constraints_equivalent, we compare the deparsed expressions. + * That is what pg_dump restores, and unlike equal() it also catches an + * implicit cast in one and an explicit cast in the other, which + * ALTER COLUMN TYPE treats differently. + */ +static void +CheckVirtualGeneratedExprs(Relation childrel, Relation parentrel) +{ + TupleDesc parent_desc = RelationGetDescr(parentrel); + TupleDesc child_desc = RelationGetDescr(childrel); + List *parent_context; + List *child_context; + + if (parent_desc->constr == NULL || + !parent_desc->constr->has_generated_virtual) + return; + + parent_context = deparse_context_for(RelationGetRelationName(parentrel), + RelationGetRelid(parentrel)); + child_context = deparse_context_for(RelationGetRelationName(childrel), + RelationGetRelid(childrel)); + + for (int i = 0; i < parent_desc->natts; i++) + { + Form_pg_attribute parent_att = TupleDescAttr(parent_desc, i); + AttrNumber child_attno; + Node *parent_expr; + Node *child_expr; + + if (parent_att->attisdropped || + parent_att->attgenerated != ATTRIBUTE_GENERATED_VIRTUAL) + continue; + + child_attno = get_attnum(RelationGetRelid(childrel), + NameStr(parent_att->attname)); + if (child_attno == InvalidAttrNumber) + elog(ERROR, "cache lookup failed for attribute \"%s\" of relation %u", + NameStr(parent_att->attname), RelationGetRelid(childrel)); + + parent_expr = TupleDescGetDefault(parent_desc, i + 1); + child_expr = TupleDescGetDefault(child_desc, child_attno); + if (parent_expr == NULL || child_expr == NULL) + elog(ERROR, "missing generation expression for column \"%s\"", + NameStr(parent_att->attname)); + + if (strcmp(deparse_expression(parent_expr, parent_context, false, false), + deparse_expression(child_expr, child_context, false, false)) != 0) + ereport(ERROR, + (errcode(ERRCODE_INVALID_COLUMN_DEFINITION), + errmsg("column \"%s\" of relation \"%s\" must have the same generation expression as in parent relation \"%s\"", + NameStr(parent_att->attname), + RelationGetRelationName(childrel), + RelationGetRelationName(parentrel)))); + } } /* diff --git a/src/test/regress/expected/generated_virtual.out b/src/test/regress/expected/generated_virtual.out index 03698488907..1ba32a391cd 100644 --- a/src/test/regress/expected/generated_virtual.out +++ b/src/test/regress/expected/generated_virtual.out @@ -356,15 +356,18 @@ CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 22) STORED) INHERITS NOTICE: merging column "b" with inherited definition ERROR: column "b" inherits from generated column of different kind DETAIL: Parent column is VIRTUAL, child column is STORED. -CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 22) VIRTUAL) INHERITS (gtest1); -- ok, overrides parent +CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 22) VIRTUAL) INHERITS (gtest1); -- error +NOTICE: merging column "b" with inherited definition +ERROR: column "b" of relation "gtestx" must have the same generation expression as in parent relation "gtest1" +CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL) INHERITS (gtest1); -- ok NOTICE: merging column "b" with inherited definition \d+ gtestx Table "generated_virtual_tests.gtestx" - Column | Type | Collation | Nullable | Default | Storage | Stats target | Description ---------+---------+-----------+----------+------------------------------+---------+--------------+------------- - a | integer | | not null | | plain | | - b | integer | | | generated always as (a * 22) | plain | | - x | integer | | | | plain | | + Column | Type | Collation | Nullable | Default | Storage | Stats target | Description +--------+---------+-----------+----------+-----------------------------+---------+--------------+------------- + a | integer | | not null | | plain | | + b | integer | | | generated always as (a * 2) | plain | | + x | integer | | | | plain | | Not-null constraints: "gtest1_a_not_null" NOT NULL "a" (inherited) Inherits: gtest1 @@ -379,9 +382,9 @@ SELECT * FROM gtest1; (3 rows) SELECT * FROM gtestx; - a | b | x -----+-----+---- - 11 | 242 | 22 + a | b | x +----+----+---- + 11 | 22 | 22 (1 row) CREATE TABLE gtestxx_1 (a int NOT NULL, b int); @@ -406,21 +409,36 @@ CREATE TABLE gtesty (x int, b int GENERATED ALWAYS AS (x * 22) VIRTUAL); CREATE TABLE gtest1_y () INHERITS (gtest1, gtesty); -- error NOTICE: merging multiple inherited definitions of column "b" ERROR: column "b" inherits conflicting generation expressions -HINT: To resolve the conflict, specify a generation expression explicitly. -CREATE TABLE gtest1_y (b int GENERATED ALWAYS AS (x + 1) VIRTUAL) INHERITS (gtest1, gtesty); -- ok +CREATE TABLE gtest1_y (b int GENERATED ALWAYS AS (x + 1) VIRTUAL) INHERITS (gtest1, gtesty); -- error NOTICE: merging multiple inherited definitions of column "b" NOTICE: moving and merging column "b" with inherited definition DETAIL: User-specified column moved to the position of the inherited column. -\d gtest1_y - Table "generated_virtual_tests.gtest1_y" - Column | Type | Collation | Nullable | Default ---------+---------+-----------+----------+----------------------------- - a | integer | | not null | - b | integer | | | generated always as (x + 1) - x | integer | | | -Inherits: gtest1, - gtesty - +ERROR: column "b" of relation "gtest1_y" must have the same generation expression as in parent relation "gtest1" +DROP TABLE gtesty; +-- adding a column merges it into an existing child column +CREATE TABLE gtesty (a int); +CREATE TABLE gtesty_1 (a int, b int GENERATED ALWAYS AS (a * 3) VIRTUAL) INHERITS (gtesty); +NOTICE: merging column "a" with inherited definition +CREATE TABLE gtesty_2 (a int, b int) INHERITS (gtesty); +NOTICE: merging column "a" with inherited definition +ALTER TABLE gtesty ADD COLUMN b int GENERATED ALWAYS AS (a * 2) VIRTUAL; -- error +NOTICE: merging definition of column "b" for child "gtesty_1" +ERROR: column "b" of relation "gtesty_1" must have the same generation expression as in parent relation "gtesty" +DROP TABLE gtesty_1; +ALTER TABLE gtesty ADD COLUMN b int GENERATED ALWAYS AS (a * 2) VIRTUAL; -- error +ERROR: column "b" in child table must be a generated column +DROP TABLE gtesty CASCADE; +NOTICE: drop cascades to table gtesty_2 +-- a child with two parents cannot have its expression changed through one +CREATE TABLE gtesty (a int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL); +CREATE TABLE gtestz (a int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL); +CREATE TABLE gtestyz () INHERITS (gtesty, gtestz); +NOTICE: merging multiple inherited definitions of column "a" +NOTICE: merging multiple inherited definitions of column "b" +ALTER TABLE gtesty ALTER COLUMN b SET EXPRESSION AS (a * 3); -- error +ERROR: cannot alter inherited column "b" of relation "gtestyz" +DROP TABLE gtesty, gtestz CASCADE; +NOTICE: drop cascades to table gtestyz -- test correct handling of GENERATED column that's only in child CREATE TABLE gtestp (f1 int); CREATE TABLE gtestc (f2 int GENERATED ALWAYS AS (f1+1) VIRTUAL) INHERITS(gtestp); @@ -882,7 +900,11 @@ CREATE TABLE gtest_parent (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWA CREATE TABLE gtest_child PARTITION OF gtest_parent FOR VALUES FROM ('2016-07-01') TO ('2016-08-01'); -- inherits gen expr CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( - f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- overrides gen expr + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- error, must match parent +) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); +ERROR: column "f3" of relation "gtest_child2" must have the same generation expression as in parent relation "gtest_parent" +CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 2) VIRTUAL -- same as parent, ok ) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); CREATE TABLE gtest_child3 PARTITION OF gtest_parent ( f3 DEFAULT 42 -- error @@ -916,6 +938,17 @@ ERROR: column "f3" inherits from generated column of different kind DETAIL: Parent column is VIRTUAL, child column is STORED. DROP TABLE gtest_child3; CREATE TABLE gtest_child3 (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWAYS AS (f2 * 33) VIRTUAL); +ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); -- error +ERROR: column "f3" of relation "gtest_child3" must have the same generation expression as in parent relation "gtest_parent" +DROP TABLE gtest_child3; +-- an explicit cast is not the same as an implicit one +CREATE TABLE gtest_cast (a int, b numeric(10,0) GENERATED ALWAYS AS (a) VIRTUAL) PARTITION BY RANGE (a); +CREATE TABLE gtest_cast_1 (a int, b numeric(10,0) GENERATED ALWAYS AS (a::numeric(10,0)) VIRTUAL); +ALTER TABLE gtest_cast ATTACH PARTITION gtest_cast_1 FOR VALUES FROM (0) TO (10); -- error +ERROR: column "b" of relation "gtest_cast_1" must have the same generation expression as in parent relation "gtest_cast" +DROP TABLE gtest_cast, gtest_cast_1; +-- different column order, so the parent's expression has to be mapped +CREATE TABLE gtest_child3 (f3 bigint GENERATED ALWAYS AS (f2 * 2) VIRTUAL, f2 bigint, f1 date NOT NULL); ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); \d gtest_child Table "generated_virtual_tests.gtest_child" @@ -927,21 +960,21 @@ ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09 Partition of: gtest_parent FOR VALUES FROM ('07-01-2016') TO ('08-01-2016') \d gtest_child2 - Table "generated_virtual_tests.gtest_child2" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- + Table "generated_virtual_tests.gtest_child2" + Column | Type | Collation | Nullable | Default +--------+--------+-----------+----------+------------------------------ f1 | date | | not null | f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 22) + f3 | bigint | | | generated always as (f2 * 2) Partition of: gtest_parent FOR VALUES FROM ('08-01-2016') TO ('09-01-2016') \d gtest_child3 - Table "generated_virtual_tests.gtest_child3" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | + Table "generated_virtual_tests.gtest_child3" + Column | Type | Collation | Nullable | Default +--------+--------+-----------+----------+------------------------------ + f3 | bigint | | | generated always as (f2 * 2) f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 33) + f1 | date | | not null | Partition of: gtest_parent FOR VALUES FROM ('09-01-2016') TO ('10-01-2016') INSERT INTO gtest_parent (f1, f2) VALUES ('2016-07-15', 1); @@ -962,14 +995,14 @@ SELECT tableoid::regclass, * FROM gtest_child ORDER BY 1, 2, 3; gtest_child | 07-15-2016 | 2 | 4 (2 rows) -SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; -- uses child's generation expression, not parent's +SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; tableoid | f1 | f2 | f3 --------------+------------+----+---- - gtest_child2 | 08-15-2016 | 3 | 66 + gtest_child2 | 08-15-2016 | 3 | 6 (1 row) SELECT tableoid::regclass, * FROM gtest_child3 ORDER BY 1, 2, 3; - tableoid | f1 | f2 | f3 + tableoid | f3 | f2 | f1 ----------+----+----+---- (0 rows) @@ -982,46 +1015,14 @@ SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; gtest_child3 | 09-13-2016 | 1 | 2 (3 rows) --- alter only parent's and one child's generation expression -ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -\d gtest_parent - Partitioned table "generated_virtual_tests.gtest_parent" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------ - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 4) -Partition key: RANGE (f1) -Number of partitions: 3 (Use \d+ to list them.) - -\d gtest_child - Table "generated_virtual_tests.gtest_child" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 10) -Partition of: gtest_parent FOR VALUES FROM ('07-01-2016') TO ('08-01-2016') - -\d gtest_child2 - Table "generated_virtual_tests.gtest_child2" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 22) -Partition of: gtest_parent FOR VALUES FROM ('08-01-2016') TO ('09-01-2016') - -\d gtest_child3 - Table "generated_virtual_tests.gtest_child3" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 33) -Partition of: gtest_parent FOR VALUES FROM ('09-01-2016') TO ('10-01-2016') - +-- cannot alter only parent's or one partition's generation expression +ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -- error +ERROR: ALTER TABLE / SET EXPRESSION must be applied to child tables too +ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -- error +ERROR: cannot alter inherited column "f3" +HINT: Alter the generation expression of the top-level parent table instead. +-- alter generation expression of parent and all its children altogether +ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; tableoid | f1 | f2 | f3 --------------+------------+----+---- @@ -1030,7 +1031,10 @@ SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; gtest_child3 | 09-13-2016 | 1 | 4 (3 rows) --- alter generation expression of parent and all its children altogether +ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 12); -- error +ERROR: check constraint "cc1" of relation "gtest_child2" is violated by some row +ALTER TABLE gtest_parent ADD CONSTRAINT cc CHECK (f3 < 13); -- ok +ALTER TABLE gtest_parent DROP CONSTRAINT cc; ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 2); \d gtest_parent Partitioned table "generated_virtual_tests.gtest_parent" @@ -1064,9 +1068,9 @@ Partition of: gtest_parent FOR VALUES FROM ('08-01-2016') TO ('09-01-2016') Table "generated_virtual_tests.gtest_child3" Column | Type | Collation | Nullable | Default --------+--------+-----------+----------+------------------------------ - f1 | date | | not null | - f2 | bigint | | | f3 | bigint | | | generated always as (f2 * 2) + f2 | bigint | | | + f1 | date | | not null | Partition of: gtest_parent FOR VALUES FROM ('09-01-2016') TO ('10-01-2016') SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; @@ -1812,3 +1816,20 @@ select * from gtest_cursor order by id; commit; drop table gtest_cursor; +-- a partition cannot have a different generation expression, which would let +-- the partitioned table's NOT NULL virtual column read as NULL +CREATE TABLE gtestnn_parent2 (a int NOT NULL, b int GENERATED ALWAYS AS (nullif(a, 0)) VIRTUAL NOT NULL) PARTITION BY LIST (a); +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 (b GENERATED ALWAYS AS (a + 1) VIRTUAL) FOR VALUES IN (0); -- error +ERROR: column "b" of relation "gtestnn_child2" must have the same generation expression as in parent relation "gtestnn_parent2" +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 FOR VALUES IN (0, 1); +INSERT INTO gtestnn_parent2 VALUES (0); -- error +ERROR: null value in column "b" of relation "gtestnn_child2" violates not-null constraint +DETAIL: Failing row contains (0, virtual). +INSERT INTO gtestnn_parent2 VALUES (1); +SELECT a, b FROM gtestnn_parent2; + a | b +---+--- + 1 | 1 +(1 row) + +DROP TABLE gtestnn_parent2; diff --git a/src/test/regress/sql/generated_virtual.sql b/src/test/regress/sql/generated_virtual.sql index b1b92b2ced5..b916a400031 100644 --- a/src/test/regress/sql/generated_virtual.sql +++ b/src/test/regress/sql/generated_virtual.sql @@ -153,7 +153,8 @@ DROP TABLE gtest_normal, gtest_normal_child; CREATE TABLE gtestx (x int, b int DEFAULT 10) INHERITS (gtest1); -- error CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS IDENTITY) INHERITS (gtest1); -- error CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 22) STORED) INHERITS (gtest1); -- error -CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 22) VIRTUAL) INHERITS (gtest1); -- ok, overrides parent +CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 22) VIRTUAL) INHERITS (gtest1); -- error +CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL) INHERITS (gtest1); -- ok \d+ gtestx INSERT INTO gtestx (a, x) VALUES (11, 22); SELECT * FROM gtest1; @@ -177,8 +178,24 @@ DROP TABLE gtesty; CREATE TABLE gtesty (x int, b int GENERATED ALWAYS AS (x * 22) VIRTUAL); CREATE TABLE gtest1_y () INHERITS (gtest1, gtesty); -- error -CREATE TABLE gtest1_y (b int GENERATED ALWAYS AS (x + 1) VIRTUAL) INHERITS (gtest1, gtesty); -- ok -\d gtest1_y +CREATE TABLE gtest1_y (b int GENERATED ALWAYS AS (x + 1) VIRTUAL) INHERITS (gtest1, gtesty); -- error +DROP TABLE gtesty; + +-- adding a column merges it into an existing child column +CREATE TABLE gtesty (a int); +CREATE TABLE gtesty_1 (a int, b int GENERATED ALWAYS AS (a * 3) VIRTUAL) INHERITS (gtesty); +CREATE TABLE gtesty_2 (a int, b int) INHERITS (gtesty); +ALTER TABLE gtesty ADD COLUMN b int GENERATED ALWAYS AS (a * 2) VIRTUAL; -- error +DROP TABLE gtesty_1; +ALTER TABLE gtesty ADD COLUMN b int GENERATED ALWAYS AS (a * 2) VIRTUAL; -- error +DROP TABLE gtesty CASCADE; + +-- a child with two parents cannot have its expression changed through one +CREATE TABLE gtesty (a int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL); +CREATE TABLE gtestz (a int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL); +CREATE TABLE gtestyz () INHERITS (gtesty, gtestz); +ALTER TABLE gtesty ALTER COLUMN b SET EXPRESSION AS (a * 3); -- error +DROP TABLE gtesty, gtestz CASCADE; -- test correct handling of GENERATED column that's only in child CREATE TABLE gtestp (f1 int); @@ -514,7 +531,10 @@ CREATE TABLE gtest_parent (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWA CREATE TABLE gtest_child PARTITION OF gtest_parent FOR VALUES FROM ('2016-07-01') TO ('2016-08-01'); -- inherits gen expr CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( - f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- overrides gen expr + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- error, must match parent +) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); +CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 2) VIRTUAL -- same as parent, ok ) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); CREATE TABLE gtest_child3 PARTITION OF gtest_parent ( f3 DEFAULT 42 -- error @@ -538,6 +558,15 @@ CREATE TABLE gtest_child3 (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWA ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); -- error DROP TABLE gtest_child3; CREATE TABLE gtest_child3 (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWAYS AS (f2 * 33) VIRTUAL); +ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); -- error +DROP TABLE gtest_child3; +-- an explicit cast is not the same as an implicit one +CREATE TABLE gtest_cast (a int, b numeric(10,0) GENERATED ALWAYS AS (a) VIRTUAL) PARTITION BY RANGE (a); +CREATE TABLE gtest_cast_1 (a int, b numeric(10,0) GENERATED ALWAYS AS (a::numeric(10,0)) VIRTUAL); +ALTER TABLE gtest_cast ATTACH PARTITION gtest_cast_1 FOR VALUES FROM (0) TO (10); -- error +DROP TABLE gtest_cast, gtest_cast_1; +-- different column order, so the parent's expression has to be mapped +CREATE TABLE gtest_child3 (f3 bigint GENERATED ALWAYS AS (f2 * 2) VIRTUAL, f2 bigint, f1 date NOT NULL); ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); \d gtest_child \d gtest_child2 @@ -547,21 +576,21 @@ INSERT INTO gtest_parent (f1, f2) VALUES ('2016-07-15', 2); INSERT INTO gtest_parent (f1, f2) VALUES ('2016-08-15', 3); SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; SELECT tableoid::regclass, * FROM gtest_child ORDER BY 1, 2, 3; -SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; -- uses child's generation expression, not parent's +SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; SELECT tableoid::regclass, * FROM gtest_child3 ORDER BY 1, 2, 3; UPDATE gtest_parent SET f1 = f1 + 60 WHERE f2 = 1; SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; --- alter only parent's and one child's generation expression -ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -\d gtest_parent -\d gtest_child -\d gtest_child2 -\d gtest_child3 -SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; +-- cannot alter only parent's or one partition's generation expression +ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -- error +ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -- error -- alter generation expression of parent and all its children altogether +ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); +SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; +ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 12); -- error +ALTER TABLE gtest_parent ADD CONSTRAINT cc CHECK (f3 < 13); -- ok +ALTER TABLE gtest_parent DROP CONSTRAINT cc; ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 2); \d gtest_parent \d gtest_child @@ -969,3 +998,13 @@ select * from gtest_cursor order by id; commit; drop table gtest_cursor; + +-- a partition cannot have a different generation expression, which would let +-- the partitioned table's NOT NULL virtual column read as NULL +CREATE TABLE gtestnn_parent2 (a int NOT NULL, b int GENERATED ALWAYS AS (nullif(a, 0)) VIRTUAL NOT NULL) PARTITION BY LIST (a); +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 (b GENERATED ALWAYS AS (a + 1) VIRTUAL) FOR VALUES IN (0); -- error +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 FOR VALUES IN (0, 1); +INSERT INTO gtestnn_parent2 VALUES (0); -- error +INSERT INTO gtestnn_parent2 VALUES (1); +SELECT a, b FROM gtestnn_parent2; +DROP TABLE gtestnn_parent2; base-commit: dc7efdf14f67283359923348e843a8c571aff3e0 -- 2.37.1 (Apple Git-137.1)
v5-0001-Require-child-tables-to-use-the-parent-s-virtual-gen.patch (application/octet-stream, 45.1K) download From d6d2736da80f880597ef9b80870b71c8ba977066 Mon Sep 17 00:00:00 2001 From: shihao zhong <zhong950419@gmail.com> Date: Tue, 13 Oct 2026 23:22:52 -0400 Subject: [PATCH v5] Require child tables to use the parent's virtual generation expression MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Otherwise a NOT NULL or CHECK constraint can be wrong for rows read through the parent. Suggested-by: Álvaro Herrera <alvherre@kurilemu.de> Discussion: https://postgr.es/m/E1xFKs5-0000000116b-2Cge@gemulon.postgresql.org --- doc/src/sgml/ddl.sgml | 18 +- doc/src/sgml/ref/alter_table.sgml | 4 + src/backend/commands/tablecmds.c | 219 +++++++++++++++++- src/bin/pg_upgrade/check.c | 75 ++++++ .../perl/PostgreSQL/Test/AdjustUpgrade.pm | 10 + .../regress/expected/generated_virtual.out | 177 +++++++------- src/test/regress/sql/generated_virtual.sql | 72 ++++-- 7 files changed, 447 insertions(+), 128 deletions(-) diff --git a/doc/src/sgml/ddl.sgml b/doc/src/sgml/ddl.sgml index d78d986756e..2f117a5940b 100644 --- a/doc/src/sgml/ddl.sgml +++ b/doc/src/sgml/ddl.sgml @@ -451,8 +451,10 @@ CREATE TABLE people ( <listitem> <para> If a parent column is a generated column, its child column must also - be a generated column of the same kind (stored or virtual); however, - the child column can have a different generation expression. + be a generated column of the same kind (stored or virtual). + A virtual generated child column must have the same generation + expression as the parent column. A stored generated child column + can have a different generation expression. </para> <para> @@ -478,8 +480,9 @@ CREATE TABLE people ( ... INHERITS</command>, then its <literal>GENERATED</literal> clause will automatically be copied from the parent. <command>ALTER TABLE ... INHERIT</command> will insist that parent and child columns - already match as to generation status, but it will not require their - generation expressions to match. + already match as to generation status, but it will only require + their generation expressions to match for virtual generated + columns. </para> </listitem> <listitem> @@ -490,8 +493,8 @@ CREATE TABLE people ( its <literal>GENERATED</literal> clause will automatically be copied from the parent. <command>ALTER TABLE ... ATTACH PARTITION</command> will insist that parent and child columns already match as to - generation status, but it will not require their generation - expressions to match. + generation status, but it will only require their generation + expressions to match for virtual generated columns. </para> </listitem> <listitem> @@ -499,7 +502,8 @@ CREATE TABLE people ( In case of multiple inheritance, if one parent column is a generated column, then all parent columns must be generated columns. If they do not all have the same generation expression, then the desired - expression for the child must be specified explicitly. + expression for the child must be specified explicitly. For virtual + generated columns, they must all have the same generation expression. </para> </listitem> </itemizedlist> diff --git a/doc/src/sgml/ref/alter_table.sgml b/doc/src/sgml/ref/alter_table.sgml index 0f9d698d170..4c57f3631af 100644 --- a/doc/src/sgml/ref/alter_table.sgml +++ b/doc/src/sgml/ref/alter_table.sgml @@ -276,6 +276,10 @@ WITH ( MODULUS <replaceable class="parameter">numeric_literal</replaceable>, REM Replacing the expression of a virtual generated column does not require a table rewrite, but if the column is used in a constraint, the table will be scanned to check that existing rows meet the constraint. + The expression of a virtual generated column cannot be changed for an + inherited column, or with <literal>ONLY</literal> for a table that has + child tables. It has to be changed for the whole inheritance tree, + from the top. </para> <para> diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index b6700929459..f0dc0ba21c1 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -383,6 +383,7 @@ static List *MergeCheckConstraint(List *constraints, const char *name, Node *exp static void MergeChildAttribute(List *inh_columns, int exist_attno, int newcol_attno, const ColumnDef *newdef); static ColumnDef *MergeInheritedAttribute(List *inh_columns, int exist_attno, const ColumnDef *newdef); static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispartition); +static void CheckVirtualGeneratedExprs(Relation childrel, Relation parentrel); static void MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel); static void StoreCatalogInheritance(Oid relationId, List *supers, bool child_is_partition); @@ -553,6 +554,8 @@ static ObjectAddress ATExecDropIdentity(Relation rel, const char *colName, bool bool recurse, bool recursing); static ObjectAddress ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName, Node *newExpr, LOCKMODE lockmode); +static void ATPrepSetExpression(Relation rel, AlterTableCmd *cmd, bool recurse, + bool recursing, LOCKMODE lockmode); static void ATPrepDropExpression(Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode); static ObjectAddress ATExecDropExpression(Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode); static ObjectAddress ATExecSetStatistics(Relation rel, const char *colName, int16 colNum, @@ -1151,6 +1154,15 @@ DefineRelation(CreateStmt *stmt, char relkind, Oid ownerId, */ CommandCounterIncrement(); + /* Virtual generated columns must use the parents' expressions */ + foreach_oid(parentId, inheritOids) + { + Relation parent = table_open(parentId, NoLock); + + CheckVirtualGeneratedExprs(rel, parent); + table_close(parent, NoLock); + } + /* Process and store partition bound, if any. */ if (stmt->partbound) { @@ -3109,8 +3121,8 @@ MergeAttributes(List *columns, const List *supers, char relpersistence, * Check for conflicts related to generated columns. * * Same rules as above: generated-ness has to match the - * parent, but the contents of the generation expression - * can be different. + * parent. For virtual generated columns, + * CheckVirtualGeneratedExprs checks the expression later. */ if (coldef->generated) { @@ -3189,7 +3201,8 @@ MergeAttributes(List *columns, const List *supers, char relpersistence, (errcode(ERRCODE_INVALID_COLUMN_DEFINITION), errmsg("column \"%s\" inherits conflicting generation expressions", def->colname), - errhint("To resolve the conflict, specify a generation expression explicitly."))); + def->generated == ATTRIBUTE_GENERATED_STORED ? + errhint("To resolve the conflict, specify a generation expression explicitly.") : 0)); else ereport(ERROR, (errcode(ERRCODE_INVALID_COLUMN_DEFINITION), @@ -3397,10 +3410,11 @@ MergeChildAttribute(List *inh_columns, int exist_attno, int newcol_attno, const * * If the parent column is generated, the child column will be made a * generated column if it isn't already. If it is a generated column, - * we'll take its generation expression in preference to the parent's. We - * must check that the child column doesn't specify a default value or - * identity, which matches the rules for a single column in - * parse_utilcmd.c. + * we'll take its generation expression in preference to the parent's, + * though for a virtual generated column CheckVirtualGeneratedExprs later + * requires the two to match. We must check that the child column doesn't + * specify a default value or identity, which matches the rules for a + * single column in parse_utilcmd.c. * * Conversely, if the parent column is not generated, the child column * can't be either. (We used to allow that, but it results in being able @@ -5100,6 +5114,7 @@ ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd, case AT_SetExpression: /* ALTER COLUMN SET EXPRESSION */ ATSimplePermissions(cmd->subtype, rel, ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE); + ATPrepSetExpression(rel, cmd, recurse, recursing, lockmode); ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context); pass = AT_PASS_SET_EXPRESSION; break; @@ -7932,6 +7947,33 @@ ATExecAddColumn(List **wqueue, AlteredTableInfo *tab, Relation rel, get_collation_name(ccollid), get_collation_name(childatt->attcollation)))); + /* + * Child column must be virtual generated if and only if parent + * column is. Our caller checks the expression. + */ + if ((colDef->generated == ATTRIBUTE_GENERATED_VIRTUAL) != + (childatt->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)) + { + if (!childatt->attgenerated) + ereport(ERROR, + (errcode(ERRCODE_DATATYPE_MISMATCH), + errmsg("column \"%s\" in child table must be a generated column", + colDef->colname))); + else if (!colDef->generated) + ereport(ERROR, + (errcode(ERRCODE_DATATYPE_MISMATCH), + errmsg("column \"%s\" in child table must not be a generated column", + colDef->colname))); + else + ereport(ERROR, + (errcode(ERRCODE_DATATYPE_MISMATCH), + errmsg("column \"%s\" inherits from generated column of different kind", + colDef->colname), + errdetail("Parent column is %s, child column is %s.", + colDef->generated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL", + childatt->attgenerated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL"))); + } + /* Bump the existing child att's inhcount */ if (pg_add_s16_overflow(childatt->attinhcount, 1, &childatt->attinhcount)) @@ -8294,6 +8336,13 @@ ATExecAddColumn(List **wqueue, AlteredTableInfo *tab, Relation rel, &childcmd, recurse, true, lockmode, cur_pass, context); + /* The child may have had the column already */ + if (colDef->generated == ATTRIBUTE_GENERATED_VIRTUAL) + { + CommandCounterIncrement(); + CheckVirtualGeneratedExprs(childrel, rel); + } + table_close(childrel, NoLock); } @@ -9409,6 +9458,94 @@ ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName, return address; } +/* + * ALTER TABLE ALTER COLUMN SET EXPRESSION + * + * A virtual generated column must have the same expression in a table and in + * all its parents and children, see CheckVirtualGeneratedExprs. So the + * expression can only be changed for a whole inheritance tree, from the top. + */ +static void +ATPrepSetExpression(Relation rel, AlterTableCmd *cmd, bool recurse, + bool recursing, LOCKMODE lockmode) +{ + HeapTuple tuple; + Form_pg_attribute attTup; + char attgenerated; + int16 attinhcount; + List *children; + List *numparents; + ListCell *lc; + ListCell *lc2; + + if (recursing) + return; + + tuple = SearchSysCacheAttName(RelationGetRelid(rel), cmd->name); + if (!HeapTupleIsValid(tuple)) + return; /* error will be reported later */ + attTup = (Form_pg_attribute) GETSTRUCT(tuple); + attgenerated = attTup->attgenerated; + attinhcount = attTup->attinhcount; + ReleaseSysCache(tuple); + + if (attgenerated != ATTRIBUTE_GENERATED_VIRTUAL) + return; + + if (attinhcount > 0) + ereport(ERROR, + (errcode(ERRCODE_INVALID_TABLE_DEFINITION), + errmsg("cannot alter inherited column \"%s\"", cmd->name), + errhint("Alter the generation expression of the top-level parent table instead."))); + + /* Partitions pending detach count here, as they still have the column */ + if (!recurse) + { + if (find_inheritance_children_extended(RelationGetRelid(rel), false, + NoLock, NULL, NULL) != NIL) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("ALTER TABLE / SET EXPRESSION must be applied to child tables too"))); + return; + } + + /* + * Recursion skips partitions pending detach, so they would keep the old + * expression. Also, a child with another parent outside this tree would + * end up with a different expression than that parent. + */ + children = find_all_inheritors(RelationGetRelid(rel), lockmode, &numparents); + forboth(lc, children, lc2, numparents) + { + Oid childrelid = lfirst_oid(lc); + bool detached_exist = false; + + (void) find_inheritance_children_extended(childrelid, true, NoLock, + &detached_exist, NULL); + if (detached_exist) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), + errmsg("cannot alter generation expression of column \"%s\" while a partition of \"%s\" is pending detach", + cmd->name, get_rel_name(childrelid)), + errhint("Use ALTER TABLE ... DETACH PARTITION ... FINALIZE to complete the pending detach operation."))); + + if (childrelid == RelationGetRelid(rel)) + continue; + + tuple = SearchSysCacheAttName(childrelid, cmd->name); + if (!HeapTupleIsValid(tuple)) + continue; /* error will be reported later */ + attinhcount = ((Form_pg_attribute) GETSTRUCT(tuple))->attinhcount; + ReleaseSysCache(tuple); + + if (attinhcount > lfirst_int(lc2)) + ereport(ERROR, + (errcode(ERRCODE_INVALID_TABLE_DEFINITION), + errmsg("cannot alter inherited column \"%s\" of relation \"%s\"", + cmd->name, get_rel_name(childrelid)))); + } +} + /* * ALTER TABLE ALTER COLUMN DROP EXPRESSION */ @@ -18854,7 +18991,8 @@ constraints_equivalent(HeapTuple a, HeapTuple b, TupleDesc tupleDesc) * partitioned tables it's a foot-gun. * * The data type must match exactly. If the parent column is NOT NULL then - * the child must be as well. Defaults are not compared, however. + * the child must be as well. Defaults are not compared, however, and neither + * are generation expressions, except for virtual generated columns. */ static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispartition) @@ -18975,6 +19113,71 @@ MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispart } table_close(attrrel, RowExclusiveLock); + + CheckVirtualGeneratedExprs(child_rel, parent_rel); +} + +/* + * CheckVirtualGeneratedExprs + * Check that each virtual generated column of a child table has the same + * generation expression as in the parent. + * + * Reading through the parent computes the parent's expression, while + * constraints on the child are checked with its own, so they must be the + * same. As in constraints_equivalent, we compare the deparsed expressions. + * That is what pg_dump restores, and unlike equal() it also catches an + * implicit cast in one and an explicit cast in the other, which + * ALTER COLUMN TYPE treats differently. + */ +static void +CheckVirtualGeneratedExprs(Relation childrel, Relation parentrel) +{ + TupleDesc parent_desc = RelationGetDescr(parentrel); + TupleDesc child_desc = RelationGetDescr(childrel); + List *parent_context; + List *child_context; + + if (parent_desc->constr == NULL || + !parent_desc->constr->has_generated_virtual) + return; + + parent_context = deparse_context_for(RelationGetRelationName(parentrel), + RelationGetRelid(parentrel)); + child_context = deparse_context_for(RelationGetRelationName(childrel), + RelationGetRelid(childrel)); + + for (int i = 0; i < parent_desc->natts; i++) + { + Form_pg_attribute parent_att = TupleDescAttr(parent_desc, i); + AttrNumber child_attno; + Node *parent_expr; + Node *child_expr; + + if (parent_att->attisdropped || + parent_att->attgenerated != ATTRIBUTE_GENERATED_VIRTUAL) + continue; + + child_attno = get_attnum(RelationGetRelid(childrel), + NameStr(parent_att->attname)); + if (child_attno == InvalidAttrNumber) + elog(ERROR, "cache lookup failed for attribute \"%s\" of relation %u", + NameStr(parent_att->attname), RelationGetRelid(childrel)); + + parent_expr = TupleDescGetDefault(parent_desc, i + 1); + child_expr = TupleDescGetDefault(child_desc, child_attno); + if (parent_expr == NULL || child_expr == NULL) + elog(ERROR, "missing generation expression for column \"%s\"", + NameStr(parent_att->attname)); + + if (strcmp(deparse_expression(parent_expr, parent_context, false, false), + deparse_expression(child_expr, child_context, false, false)) != 0) + ereport(ERROR, + (errcode(ERRCODE_INVALID_COLUMN_DEFINITION), + errmsg("column \"%s\" of relation \"%s\" must have the same generation expression as in parent relation \"%s\"", + NameStr(parent_att->attname), + RelationGetRelationName(childrel), + RelationGetRelationName(parentrel)))); + } } /* diff --git a/src/bin/pg_upgrade/check.c b/src/bin/pg_upgrade/check.c index 2d4aaf22a0f..36ec01d8f53 100644 --- a/src/bin/pg_upgrade/check.c +++ b/src/bin/pg_upgrade/check.c @@ -29,6 +29,7 @@ static void check_for_user_defined_postfix_ops(ClusterInfo *cluster); static void check_for_incompatible_polymorphics(ClusterInfo *cluster); static void check_for_tables_with_oids(ClusterInfo *cluster); static void check_for_not_null_inheritance(ClusterInfo *cluster); +static void check_for_virtual_generated_exprs(ClusterInfo *cluster); static void check_for_gist_inet_ops(ClusterInfo *cluster); static void check_for_new_tablespace_dir(void); static void check_for_user_defined_encoding_conversions(ClusterInfo *cluster); @@ -673,6 +674,15 @@ check_and_dump_old_cluster(void) if (GET_MAJOR_VERSION(old_cluster.major_version) <= 1800) check_for_not_null_inheritance(&old_cluster); + /* + * Virtual generated columns (new in PG 18) of a child table used to be + * allowed to have a different generation expression than the parent, but + * schema restore fails for them now. Verify there are none. + */ + if (GET_MAJOR_VERSION(old_cluster.major_version) >= 1800 && + GET_MAJOR_VERSION(old_cluster.major_version) <= 1900) + check_for_virtual_generated_exprs(&old_cluster); + /* * The btree_gist extension contains gist_inet_ops and gist_cidr_ops * opclasses that do not reliably give correct answers. We want to @@ -1733,6 +1743,71 @@ check_for_not_null_inheritance(ClusterInfo *cluster) check_ok(); } +/* + * check_for_virtual_generated_exprs() + * + * A virtual generated column of a child table, including a partition, must + * have the same generation expression as the parent. Check that the cluster + * to be upgraded has no child tables that differ, which older versions + * allowed. + */ +static void +check_for_virtual_generated_exprs(ClusterInfo *cluster) +{ + UpgradeTaskReport report; + UpgradeTask *task; + const char *query; + + prep_status("Checking for virtual generated column inconsistencies"); + + report.file = NULL; + snprintf(report.path, sizeof(report.path), "%s/%s", + log_opts.basedir, + "virtual_generated_columns.txt"); + + query = "SELECT nc.nspname, cc.relname, ac.attname " + "FROM pg_catalog.pg_class cc " + " JOIN pg_catalog.pg_namespace nc ON nc.oid = cc.relnamespace " + " JOIN pg_catalog.pg_inherits i ON i.inhrelid = cc.oid " + " JOIN pg_catalog.pg_attribute ac ON ac.attrelid = cc.oid " + " JOIN pg_catalog.pg_attribute ap ON ap.attrelid = i.inhparent " + " AND ap.attname = ac.attname " + " JOIN pg_catalog.pg_attrdef dc ON dc.adrelid = ac.attrelid " + " AND dc.adnum = ac.attnum " + " JOIN pg_catalog.pg_attrdef dp ON dp.adrelid = ap.attrelid " + " AND dp.adnum = ap.attnum " + "WHERE ac.attgenerated = 'v' " + " AND pg_catalog.pg_get_expr(dc.adbin, dc.adrelid) <> " + " pg_catalog.pg_get_expr(dp.adbin, dp.adrelid)"; + + task = upgrade_task_create(); + /* the not-null check's callback reports the same columns */ + upgrade_task_add_step(task, query, + process_inconsistent_notnull, + true, &report); + upgrade_task_run(task, cluster); + upgrade_task_free(task); + + if (report.file) + { + fclose(report.file); + pg_log(PG_REPORT, "fatal"); + pg_fatal("Your installation contains child tables or partitions whose virtual\n" + "generated columns have a different generation expression than the\n" + "parent table. This is no longer allowed, so the upgrade would fail.\n" + "You can fix this by running\n" + " ALTER TABLE parent ALTER COLUMN column SET EXPRESSION AS (...);\n" + "on the top-level parent table of each column. In version 18 this\n" + "is not allowed if any table in that inheritance tree has CHECK\n" + "constraints, so drop them first and add them back afterwards. Rows\n" + "that violate NOT NULL or CHECK with the new expression must be fixed\n" + "first. A list of the problem columns is in the file:\n" + " %s", report.path); + } + else + check_ok(); +} + /* * Callback function for processing results of query for * check_for_gist_inet_ops()'s UpgradeTask. If the query returned any rows diff --git a/src/test/perl/PostgreSQL/Test/AdjustUpgrade.pm b/src/test/perl/PostgreSQL/Test/AdjustUpgrade.pm index 7bea8db8e61..7c3629338e6 100644 --- a/src/test/perl/PostgreSQL/Test/AdjustUpgrade.pm +++ b/src/test/perl/PostgreSQL/Test/AdjustUpgrade.pm @@ -156,6 +156,16 @@ sub adjust_database_contents } } + # Child tables whose virtual generated column has a different expression + # than the parent's cannot be upgraded to v20. + if ($old_version >= 18 && $old_version < 20) + { + _add_st( + $result, 'regression', + 'drop table if exists generated_virtual_tests.gtest1_y', + 'drop table if exists generated_virtual_tests.gtestx'); + } + # we removed these test-support functions in v18 if ($old_version < 18) { diff --git a/src/test/regress/expected/generated_virtual.out b/src/test/regress/expected/generated_virtual.out index b14e10fb5a0..7b58fb273ef 100644 --- a/src/test/regress/expected/generated_virtual.out +++ b/src/test/regress/expected/generated_virtual.out @@ -357,15 +357,18 @@ CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 22) STORED) INHERITS NOTICE: merging column "b" with inherited definition ERROR: column "b" inherits from generated column of different kind DETAIL: Parent column is VIRTUAL, child column is STORED. -CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 22) VIRTUAL) INHERITS (gtest1); -- ok, overrides parent +CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 22) VIRTUAL) INHERITS (gtest1); -- error +NOTICE: merging column "b" with inherited definition +ERROR: column "b" of relation "gtestx" must have the same generation expression as in parent relation "gtest1" +CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL) INHERITS (gtest1); -- ok NOTICE: merging column "b" with inherited definition \d+ gtestx Table "generated_virtual_tests.gtestx" - Column | Type | Collation | Nullable | Default | Storage | Stats target | Description ---------+---------+-----------+----------+------------------------------+---------+--------------+------------- - a | integer | | not null | | plain | | - b | integer | | | generated always as (a * 22) | plain | | - x | integer | | | | plain | | + Column | Type | Collation | Nullable | Default | Storage | Stats target | Description +--------+---------+-----------+----------+-----------------------------+---------+--------------+------------- + a | integer | | not null | | plain | | + b | integer | | | generated always as (a * 2) | plain | | + x | integer | | | | plain | | Not-null constraints: "gtest1_a_not_null" NOT NULL "a" (inherited) Inherits: @@ -381,9 +384,9 @@ SELECT * FROM gtest1; (3 rows) SELECT * FROM gtestx; - a | b | x -----+-----+---- - 11 | 242 | 22 + a | b | x +----+----+---- + 11 | 22 | 22 (1 row) CREATE TABLE gtestxx_1 (a int NOT NULL, b int); @@ -408,22 +411,36 @@ CREATE TABLE gtesty (x int, b int GENERATED ALWAYS AS (x * 22) VIRTUAL); CREATE TABLE gtest1_y () INHERITS (gtest1, gtesty); -- error NOTICE: merging multiple inherited definitions of column "b" ERROR: column "b" inherits conflicting generation expressions -HINT: To resolve the conflict, specify a generation expression explicitly. -CREATE TABLE gtest1_y (b int GENERATED ALWAYS AS (x + 1) VIRTUAL) INHERITS (gtest1, gtesty); -- ok +CREATE TABLE gtest1_y (b int GENERATED ALWAYS AS (x + 1) VIRTUAL) INHERITS (gtest1, gtesty); -- error NOTICE: merging multiple inherited definitions of column "b" NOTICE: moving and merging column "b" with inherited definition DETAIL: User-specified column moved to the position of the inherited column. -\d gtest1_y - Table "generated_virtual_tests.gtest1_y" - Column | Type | Collation | Nullable | Default ---------+---------+-----------+----------+----------------------------- - a | integer | | not null | - b | integer | | | generated always as (x + 1) - x | integer | | | -Inherits: - gtest1 - gtesty - +ERROR: column "b" of relation "gtest1_y" must have the same generation expression as in parent relation "gtest1" +DROP TABLE gtesty; +-- adding a column merges it into an existing child column +CREATE TABLE gtesty (a int); +CREATE TABLE gtesty_1 (a int, b int GENERATED ALWAYS AS (a * 3) VIRTUAL) INHERITS (gtesty); +NOTICE: merging column "a" with inherited definition +CREATE TABLE gtesty_2 (a int, b int) INHERITS (gtesty); +NOTICE: merging column "a" with inherited definition +ALTER TABLE gtesty ADD COLUMN b int GENERATED ALWAYS AS (a * 2) VIRTUAL; -- error +NOTICE: merging definition of column "b" for child "gtesty_1" +ERROR: column "b" of relation "gtesty_1" must have the same generation expression as in parent relation "gtesty" +DROP TABLE gtesty_1; +ALTER TABLE gtesty ADD COLUMN b int GENERATED ALWAYS AS (a * 2) VIRTUAL; -- error +ERROR: column "b" in child table must be a generated column +DROP TABLE gtesty CASCADE; +NOTICE: drop cascades to table gtesty_2 +-- a child with two parents cannot have its expression changed through one +CREATE TABLE gtesty (a int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL); +CREATE TABLE gtestz (a int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL); +CREATE TABLE gtestyz () INHERITS (gtesty, gtestz); +NOTICE: merging multiple inherited definitions of column "a" +NOTICE: merging multiple inherited definitions of column "b" +ALTER TABLE gtesty ALTER COLUMN b SET EXPRESSION AS (a * 3); -- error +ERROR: cannot alter inherited column "b" of relation "gtestyz" +DROP TABLE gtesty, gtestz CASCADE; +NOTICE: drop cascades to table gtestyz -- test correct handling of GENERATED column that's only in child CREATE TABLE gtestp (f1 int); CREATE TABLE gtestc (f2 int GENERATED ALWAYS AS (f1+1) VIRTUAL) INHERITS(gtestp); @@ -912,7 +929,11 @@ CREATE TABLE gtest_parent (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWA CREATE TABLE gtest_child PARTITION OF gtest_parent FOR VALUES FROM ('2016-07-01') TO ('2016-08-01'); -- inherits gen expr CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( - f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- overrides gen expr + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- error, must match parent +) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); +ERROR: column "f3" of relation "gtest_child2" must have the same generation expression as in parent relation "gtest_parent" +CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 2) VIRTUAL -- same as parent, ok ) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); CREATE TABLE gtest_child3 PARTITION OF gtest_parent ( f3 DEFAULT 42 -- error @@ -946,6 +967,17 @@ ERROR: column "f3" inherits from generated column of different kind DETAIL: Parent column is VIRTUAL, child column is STORED. DROP TABLE gtest_child3; CREATE TABLE gtest_child3 (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWAYS AS (f2 * 33) VIRTUAL); +ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); -- error +ERROR: column "f3" of relation "gtest_child3" must have the same generation expression as in parent relation "gtest_parent" +DROP TABLE gtest_child3; +-- an explicit cast is not the same as an implicit one +CREATE TABLE gtest_cast (a int, b numeric(10,0) GENERATED ALWAYS AS (a) VIRTUAL) PARTITION BY RANGE (a); +CREATE TABLE gtest_cast_1 (a int, b numeric(10,0) GENERATED ALWAYS AS (a::numeric(10,0)) VIRTUAL); +ALTER TABLE gtest_cast ATTACH PARTITION gtest_cast_1 FOR VALUES FROM (0) TO (10); -- error +ERROR: column "b" of relation "gtest_cast_1" must have the same generation expression as in parent relation "gtest_cast" +DROP TABLE gtest_cast, gtest_cast_1; +-- different column order, so the parent's expression has to be mapped +CREATE TABLE gtest_child3 (f3 bigint GENERATED ALWAYS AS (f2 * 2) VIRTUAL, f2 bigint, f1 date NOT NULL); ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); \d gtest_child Table "generated_virtual_tests.gtest_child" @@ -957,21 +989,21 @@ ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09 Partition of: gtest_parent FOR VALUES FROM ('07-01-2016') TO ('08-01-2016') \d gtest_child2 - Table "generated_virtual_tests.gtest_child2" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- + Table "generated_virtual_tests.gtest_child2" + Column | Type | Collation | Nullable | Default +--------+--------+-----------+----------+------------------------------ f1 | date | | not null | f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 22) + f3 | bigint | | | generated always as (f2 * 2) Partition of: gtest_parent FOR VALUES FROM ('08-01-2016') TO ('09-01-2016') \d gtest_child3 - Table "generated_virtual_tests.gtest_child3" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | + Table "generated_virtual_tests.gtest_child3" + Column | Type | Collation | Nullable | Default +--------+--------+-----------+----------+------------------------------ + f3 | bigint | | | generated always as (f2 * 2) f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 33) + f1 | date | | not null | Partition of: gtest_parent FOR VALUES FROM ('09-01-2016') TO ('10-01-2016') INSERT INTO gtest_parent (f1, f2) VALUES ('2016-07-15', 1); @@ -992,14 +1024,14 @@ SELECT tableoid::regclass, * FROM gtest_child ORDER BY 1, 2, 3; gtest_child | 07-15-2016 | 2 | 4 (2 rows) -SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; -- uses child's generation expression, not parent's +SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; tableoid | f1 | f2 | f3 --------------+------------+----+---- - gtest_child2 | 08-15-2016 | 3 | 66 + gtest_child2 | 08-15-2016 | 3 | 6 (1 row) SELECT tableoid::regclass, * FROM gtest_child3 ORDER BY 1, 2, 3; - tableoid | f1 | f2 | f3 + tableoid | f3 | f2 | f1 ----------+----+----+---- (0 rows) @@ -1012,46 +1044,14 @@ SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; gtest_child3 | 09-13-2016 | 1 | 2 (3 rows) --- alter only parent's and one child's generation expression -ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -\d gtest_parent - Partitioned table "generated_virtual_tests.gtest_parent" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------ - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 4) -Partition key: RANGE (f1) -Number of partitions: 3 (Use \d+ to list them.) - -\d gtest_child - Table "generated_virtual_tests.gtest_child" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 10) -Partition of: gtest_parent FOR VALUES FROM ('07-01-2016') TO ('08-01-2016') - -\d gtest_child2 - Table "generated_virtual_tests.gtest_child2" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 22) -Partition of: gtest_parent FOR VALUES FROM ('08-01-2016') TO ('09-01-2016') - -\d gtest_child3 - Table "generated_virtual_tests.gtest_child3" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 33) -Partition of: gtest_parent FOR VALUES FROM ('09-01-2016') TO ('10-01-2016') - +-- cannot alter only parent's or one partition's generation expression +ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -- error +ERROR: ALTER TABLE / SET EXPRESSION must be applied to child tables too +ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -- error +ERROR: cannot alter inherited column "f3" +HINT: Alter the generation expression of the top-level parent table instead. +-- alter generation expression of parent and all its children altogether +ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; tableoid | f1 | f2 | f3 --------------+------------+----+---- @@ -1060,16 +1060,10 @@ SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; gtest_child3 | 09-13-2016 | 1 | 4 (3 rows) --- check constraint was validated based on each partitions's generation expression -ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 19); -- error -ERROR: check constraint "cc1" of relation "gtest_child" is violated by some row -ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 66); -- error +ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 12); -- error ERROR: check constraint "cc1" of relation "gtest_child2" is violated by some row -ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 <> 33); -- error -ERROR: check constraint "cc1" of relation "gtest_child3" is violated by some row -ALTER TABLE gtest_parent ADD CONSTRAINT cc CHECK (f3 < 67); -- ok +ALTER TABLE gtest_parent ADD CONSTRAINT cc CHECK (f3 < 13); -- ok ALTER TABLE gtest_parent DROP CONSTRAINT cc; --- alter generation expression of parent and all its children altogether ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 2); \d gtest_parent Partitioned table "generated_virtual_tests.gtest_parent" @@ -1103,9 +1097,9 @@ Partition of: gtest_parent FOR VALUES FROM ('08-01-2016') TO ('09-01-2016') Table "generated_virtual_tests.gtest_child3" Column | Type | Collation | Nullable | Default --------+--------+-----------+----------+------------------------------ - f1 | date | | not null | - f2 | bigint | | | f3 | bigint | | | generated always as (f2 * 2) + f2 | bigint | | | + f1 | date | | not null | Partition of: gtest_parent FOR VALUES FROM ('09-01-2016') TO ('10-01-2016') SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; @@ -1894,11 +1888,16 @@ select * from gtest_cursor order by id; commit; drop table gtest_cursor; --- NOT NULL on a partitioned table's virtual column does not prove non-nullness, --- because a partition can have a different generation expression +-- a partition cannot have a different generation expression, which would let +-- the partitioned table's NOT NULL virtual column read as NULL CREATE TABLE gtestnn_parent2 (a int NOT NULL, b int GENERATED ALWAYS AS (nullif(a, 0)) VIRTUAL NOT NULL) PARTITION BY LIST (a); -CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 (b GENERATED ALWAYS AS (a + 1) VIRTUAL) FOR VALUES IN (0); -INSERT INTO gtestnn_parent2 VALUES (0); +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 (b GENERATED ALWAYS AS (a + 1) VIRTUAL) FOR VALUES IN (0); -- error +ERROR: column "b" of relation "gtestnn_child2" must have the same generation expression as in parent relation "gtestnn_parent2" +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 FOR VALUES IN (0, 1); +INSERT INTO gtestnn_parent2 VALUES (0); -- error +ERROR: null value in column "b" of relation "gtestnn_child2" violates not-null constraint +DETAIL: Failing row contains (0, virtual). +INSERT INTO gtestnn_parent2 VALUES (1); EXPLAIN (COSTS OFF) SELECT a FROM gtestnn_parent2 WHERE a NOT IN (SELECT b FROM gtestnn_parent2); QUERY PLAN diff --git a/src/test/regress/sql/generated_virtual.sql b/src/test/regress/sql/generated_virtual.sql index e62880f941a..27a863acbb2 100644 --- a/src/test/regress/sql/generated_virtual.sql +++ b/src/test/regress/sql/generated_virtual.sql @@ -153,7 +153,8 @@ DROP TABLE gtest_normal, gtest_normal_child; CREATE TABLE gtestx (x int, b int DEFAULT 10) INHERITS (gtest1); -- error CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS IDENTITY) INHERITS (gtest1); -- error CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 22) STORED) INHERITS (gtest1); -- error -CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 22) VIRTUAL) INHERITS (gtest1); -- ok, overrides parent +CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 22) VIRTUAL) INHERITS (gtest1); -- error +CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL) INHERITS (gtest1); -- ok \d+ gtestx INSERT INTO gtestx (a, x) VALUES (11, 22); SELECT * FROM gtest1; @@ -177,8 +178,24 @@ DROP TABLE gtesty; CREATE TABLE gtesty (x int, b int GENERATED ALWAYS AS (x * 22) VIRTUAL); CREATE TABLE gtest1_y () INHERITS (gtest1, gtesty); -- error -CREATE TABLE gtest1_y (b int GENERATED ALWAYS AS (x + 1) VIRTUAL) INHERITS (gtest1, gtesty); -- ok -\d gtest1_y +CREATE TABLE gtest1_y (b int GENERATED ALWAYS AS (x + 1) VIRTUAL) INHERITS (gtest1, gtesty); -- error +DROP TABLE gtesty; + +-- adding a column merges it into an existing child column +CREATE TABLE gtesty (a int); +CREATE TABLE gtesty_1 (a int, b int GENERATED ALWAYS AS (a * 3) VIRTUAL) INHERITS (gtesty); +CREATE TABLE gtesty_2 (a int, b int) INHERITS (gtesty); +ALTER TABLE gtesty ADD COLUMN b int GENERATED ALWAYS AS (a * 2) VIRTUAL; -- error +DROP TABLE gtesty_1; +ALTER TABLE gtesty ADD COLUMN b int GENERATED ALWAYS AS (a * 2) VIRTUAL; -- error +DROP TABLE gtesty CASCADE; + +-- a child with two parents cannot have its expression changed through one +CREATE TABLE gtesty (a int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL); +CREATE TABLE gtestz (a int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL); +CREATE TABLE gtestyz () INHERITS (gtesty, gtestz); +ALTER TABLE gtesty ALTER COLUMN b SET EXPRESSION AS (a * 3); -- error +DROP TABLE gtesty, gtestz CASCADE; -- test correct handling of GENERATED column that's only in child CREATE TABLE gtestp (f1 int); @@ -529,7 +546,10 @@ CREATE TABLE gtest_parent (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWA CREATE TABLE gtest_child PARTITION OF gtest_parent FOR VALUES FROM ('2016-07-01') TO ('2016-08-01'); -- inherits gen expr CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( - f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- overrides gen expr + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- error, must match parent +) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); +CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 2) VIRTUAL -- same as parent, ok ) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); CREATE TABLE gtest_child3 PARTITION OF gtest_parent ( f3 DEFAULT 42 -- error @@ -553,6 +573,15 @@ CREATE TABLE gtest_child3 (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWA ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); -- error DROP TABLE gtest_child3; CREATE TABLE gtest_child3 (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWAYS AS (f2 * 33) VIRTUAL); +ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); -- error +DROP TABLE gtest_child3; +-- an explicit cast is not the same as an implicit one +CREATE TABLE gtest_cast (a int, b numeric(10,0) GENERATED ALWAYS AS (a) VIRTUAL) PARTITION BY RANGE (a); +CREATE TABLE gtest_cast_1 (a int, b numeric(10,0) GENERATED ALWAYS AS (a::numeric(10,0)) VIRTUAL); +ALTER TABLE gtest_cast ATTACH PARTITION gtest_cast_1 FOR VALUES FROM (0) TO (10); -- error +DROP TABLE gtest_cast, gtest_cast_1; +-- different column order, so the parent's expression has to be mapped +CREATE TABLE gtest_child3 (f3 bigint GENERATED ALWAYS AS (f2 * 2) VIRTUAL, f2 bigint, f1 date NOT NULL); ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); \d gtest_child \d gtest_child2 @@ -562,28 +591,21 @@ INSERT INTO gtest_parent (f1, f2) VALUES ('2016-07-15', 2); INSERT INTO gtest_parent (f1, f2) VALUES ('2016-08-15', 3); SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; SELECT tableoid::regclass, * FROM gtest_child ORDER BY 1, 2, 3; -SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; -- uses child's generation expression, not parent's +SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; SELECT tableoid::regclass, * FROM gtest_child3 ORDER BY 1, 2, 3; UPDATE gtest_parent SET f1 = f1 + 60 WHERE f2 = 1; SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; --- alter only parent's and one child's generation expression -ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -\d gtest_parent -\d gtest_child -\d gtest_child2 -\d gtest_child3 -SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; - --- check constraint was validated based on each partitions's generation expression -ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 19); -- error -ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 66); -- error -ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 <> 33); -- error -ALTER TABLE gtest_parent ADD CONSTRAINT cc CHECK (f3 < 67); -- ok -ALTER TABLE gtest_parent DROP CONSTRAINT cc; +-- cannot alter only parent's or one partition's generation expression +ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -- error +ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -- error -- alter generation expression of parent and all its children altogether +ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); +SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; +ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 12); -- error +ALTER TABLE gtest_parent ADD CONSTRAINT cc CHECK (f3 < 13); -- ok +ALTER TABLE gtest_parent DROP CONSTRAINT cc; ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 2); \d gtest_parent \d gtest_child @@ -1012,11 +1034,13 @@ commit; drop table gtest_cursor; --- NOT NULL on a partitioned table's virtual column does not prove non-nullness, --- because a partition can have a different generation expression +-- a partition cannot have a different generation expression, which would let +-- the partitioned table's NOT NULL virtual column read as NULL CREATE TABLE gtestnn_parent2 (a int NOT NULL, b int GENERATED ALWAYS AS (nullif(a, 0)) VIRTUAL NOT NULL) PARTITION BY LIST (a); -CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 (b GENERATED ALWAYS AS (a + 1) VIRTUAL) FOR VALUES IN (0); -INSERT INTO gtestnn_parent2 VALUES (0); +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 (b GENERATED ALWAYS AS (a + 1) VIRTUAL) FOR VALUES IN (0); -- error +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 FOR VALUES IN (0, 1); +INSERT INTO gtestnn_parent2 VALUES (0); -- error +INSERT INTO gtestnn_parent2 VALUES (1); EXPLAIN (COSTS OFF) SELECT a FROM gtestnn_parent2 WHERE a NOT IN (SELECT b FROM gtestnn_parent2); SELECT a FROM gtestnn_parent2 WHERE a NOT IN (SELECT b FROM gtestnn_parent2); base-commit: 7fc2f0423320e02beb8c44b863f1827604c47c75 -- 2.37.1 (Apple Git-137.1)
^ permalink raw reply [nested|flat] 24+ messages in thread

* Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned
  2026-10-10 00:23 pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Richard Guo <rguo@postgresql.org>
  2026-10-13 12:42 ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-10-13 14:34   ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Richard Guo <guofenglinux@gmail.com>
  2026-10-13 15:41     ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-10-13 16:00       ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-10-14 04:39         ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-10-26 17:40           ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Manu <manuelreyesbravo@gmail.com>
  2026-10-27 03:10             ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-11-11 15:41               ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-11-11 15:47                 ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-11-12 04:36                   ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-11-14 01:12                     ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Manu <manuelreyesbravo@gmail.com>
  2026-11-15 03:36                       ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-11-15 21:15                         ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Zsolt Parragi <zsolt.parragi@percona.com>
  2026-11-17 01:43                           ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
@ 2026-11-17 19:26                             ` Zsolt Parragi <zsolt.parragi@percona.com>
  2026-11-19 05:01                               ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  0 siblings, 1 reply; 24+ messages in thread

From: Zsolt Parragi @ 2026-11-17 19:26 UTC (permalink / raw)
  To: shihao zhong <zhong950419@gmail.com>; +Cc: pgsql-hackers@lists.postgresql.org, Manu <manuelreyesbravo@gmail.com>; Álvaro Herrera <alvherre@kurilemu.de>; Richard Guo <guofenglinux@gmail.com>

Thanks for the update!

+-- a child with two parents cannot have its expression changed through one
+CREATE TABLE gtesty (a int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL);
+CREATE TABLE gtestz (a int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL);
+CREATE TABLE gtestyz () INHERITS (gtesty, gtestz);
+NOTICE:  merging multiple inherited definitions of column "a"
+NOTICE:  merging multiple inherited definitions of column "b"
+ALTER TABLE gtesty ALTER COLUMN b SET EXPRESSION AS (a * 3);  -- error

But it can with a combined alter:

CREATE TABLE q (a int, b int GENERATED ALWAYS AS (nullif(a, 1))
VIRTUAL NOT NULL);
CREATE TABLE p (a int);
CREATE TABLE c () INHERITS (p, q);
ALTER TABLE p ADD COLUMN b int GENERATED ALWAYS AS (nullif(a, 1)) VIRTUAL,
              ALTER COLUMN b SET EXPRESSION AS (a);      -- accepted

Also, in the above example if we try to alter the child instead we get:

ALTER TABLE gtestyz ALTER COLUMN b SET EXPRESSION AS (a * 3);
-- ERROR:  cannot alter inherited column "b"
-- HINT:  Alter the generation expression of the top-level parent table instead.

But that hint won't work, as the testcase shows.






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

* Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned
  2026-10-10 00:23 pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Richard Guo <rguo@postgresql.org>
  2026-10-13 12:42 ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-10-13 14:34   ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Richard Guo <guofenglinux@gmail.com>
  2026-10-13 15:41     ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-10-13 16:00       ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-10-14 04:39         ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-10-26 17:40           ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Manu <manuelreyesbravo@gmail.com>
  2026-10-27 03:10             ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-11-11 15:41               ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-11-11 15:47                 ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-11-12 04:36                   ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-11-14 01:12                     ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Manu <manuelreyesbravo@gmail.com>
  2026-11-15 03:36                       ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-11-15 21:15                         ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Zsolt Parragi <zsolt.parragi@percona.com>
  2026-11-17 01:43                           ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-11-17 19:26                             ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Zsolt Parragi <zsolt.parragi@percona.com>
@ 2026-11-19 05:01                               ` shihao zhong <zhong950419@gmail.com>
  2026-11-19 19:08                                 ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Manu <manuelreyesbravo@gmail.com>
  0 siblings, 1 reply; 24+ messages in thread

From: shihao zhong @ 2026-11-19 05:01 UTC (permalink / raw)
  To: Zsolt Parragi <zsolt.parragi@percona.com>; +Cc: pgsql-hackers@lists.postgresql.org, Manu <manuelreyesbravo@gmail.com>; Álvaro Herrera <alvherre@kurilemu.de>; Richard Guo <guofenglinux@gmail.com>

Hi Zsolt,

Thanks for catching both, v6 attached.

> But it can with a combined alter:

The check ran before the ADD COLUMN, so the column did not exist yet.
v6 runs it when SET EXPRESSION executes, and your example now fails
like the two statement form.

> But that hint won't work, as the testcase shows.

v6 gives the hint only for partitions, since a partition always has a
single top-level parent.

A simpler option is to reject the combined command, as ALTER COLUMN
TYPE does for a column added by the same command. I'm happy to switch
if that is preferred.

Thanks,
Shihao

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

v6-0001-Require-child-tables-to-use-the-parent-s-virtual-gen.patch (application/octet-stream, 48.4K) download From be90a6b2ee6840aee5b6949afc4e4d5afe011c25 Mon Sep 17 00:00:00 2001 From: shihao zhong <zhong950419@gmail.com> Date: Tue, 13 Oct 2026 23:22:52 -0400 Subject: [PATCH v6] Require child tables to use the parent's virtual generation expression MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Otherwise a NOT NULL or CHECK constraint can be wrong for rows read through the parent. Suggested-by: Álvaro Herrera <alvherre@kurilemu.de> Discussion: https://postgr.es/m/E1xFKs5-0000000116b-2Cge@gemulon.postgresql.org --- doc/src/sgml/ddl.sgml | 18 +- doc/src/sgml/ref/alter_table.sgml | 5 + src/backend/commands/tablecmds.c | 249 +++++++++++++++++- src/bin/pg_upgrade/check.c | 75 ++++++ .../perl/PostgreSQL/Test/AdjustUpgrade.pm | 10 + .../regress/expected/generated_virtual.out | 190 ++++++------- src/test/regress/sql/generated_virtual.sql | 80 ++++-- 7 files changed, 496 insertions(+), 131 deletions(-) diff --git a/doc/src/sgml/ddl.sgml b/doc/src/sgml/ddl.sgml index d78d986756e..2f117a5940b 100644 --- a/doc/src/sgml/ddl.sgml +++ b/doc/src/sgml/ddl.sgml @@ -451,8 +451,10 @@ CREATE TABLE people ( <listitem> <para> If a parent column is a generated column, its child column must also - be a generated column of the same kind (stored or virtual); however, - the child column can have a different generation expression. + be a generated column of the same kind (stored or virtual). + A virtual generated child column must have the same generation + expression as the parent column. A stored generated child column + can have a different generation expression. </para> <para> @@ -478,8 +480,9 @@ CREATE TABLE people ( ... INHERITS</command>, then its <literal>GENERATED</literal> clause will automatically be copied from the parent. <command>ALTER TABLE ... INHERIT</command> will insist that parent and child columns - already match as to generation status, but it will not require their - generation expressions to match. + already match as to generation status, but it will only require + their generation expressions to match for virtual generated + columns. </para> </listitem> <listitem> @@ -490,8 +493,8 @@ CREATE TABLE people ( its <literal>GENERATED</literal> clause will automatically be copied from the parent. <command>ALTER TABLE ... ATTACH PARTITION</command> will insist that parent and child columns already match as to - generation status, but it will not require their generation - expressions to match. + generation status, but it will only require their generation + expressions to match for virtual generated columns. </para> </listitem> <listitem> @@ -499,7 +502,8 @@ CREATE TABLE people ( In case of multiple inheritance, if one parent column is a generated column, then all parent columns must be generated columns. If they do not all have the same generation expression, then the desired - expression for the child must be specified explicitly. + expression for the child must be specified explicitly. For virtual + generated columns, they must all have the same generation expression. </para> </listitem> </itemizedlist> diff --git a/doc/src/sgml/ref/alter_table.sgml b/doc/src/sgml/ref/alter_table.sgml index 0f9d698d170..dc1259ef8cc 100644 --- a/doc/src/sgml/ref/alter_table.sgml +++ b/doc/src/sgml/ref/alter_table.sgml @@ -276,6 +276,11 @@ WITH ( MODULUS <replaceable class="parameter">numeric_literal</replaceable>, REM Replacing the expression of a virtual generated column does not require a table rewrite, but if the column is used in a constraint, the table will be scanned to check that existing rows meet the constraint. + The expression of a virtual generated column cannot be changed for an + inherited column, or with <literal>ONLY</literal> for a table that has + child tables. It has to be changed for the whole inheritance tree, + from the top. If a child table inherits the column from more than one + parent, the expression cannot be changed while it does. </para> <para> diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index b6700929459..baf5996c325 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -383,6 +383,7 @@ static List *MergeCheckConstraint(List *constraints, const char *name, Node *exp static void MergeChildAttribute(List *inh_columns, int exist_attno, int newcol_attno, const ColumnDef *newdef); static ColumnDef *MergeInheritedAttribute(List *inh_columns, int exist_attno, const ColumnDef *newdef); static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispartition); +static void CheckVirtualGeneratedExprs(Relation childrel, Relation parentrel); static void MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel); static void StoreCatalogInheritance(Oid relationId, List *supers, bool child_is_partition); @@ -552,7 +553,11 @@ static ObjectAddress ATExecSetIdentity(Relation rel, const char *colName, static ObjectAddress ATExecDropIdentity(Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode, bool recurse, bool recursing); static ObjectAddress ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName, - Node *newExpr, LOCKMODE lockmode); + Node *newExpr, bool check_tree, LOCKMODE lockmode); +static void ATPrepSetExpression(Relation rel, AlterTableCmd *cmd, bool recurse, + bool recursing, LOCKMODE lockmode); +static void CheckSetExpressionTree(Relation rel, const char *colName, + LOCKMODE lockmode); static void ATPrepDropExpression(Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode); static ObjectAddress ATExecDropExpression(Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode); static ObjectAddress ATExecSetStatistics(Relation rel, const char *colName, int16 colNum, @@ -1151,6 +1156,15 @@ DefineRelation(CreateStmt *stmt, char relkind, Oid ownerId, */ CommandCounterIncrement(); + /* Virtual generated columns must use the parents' expressions */ + foreach_oid(parentId, inheritOids) + { + Relation parent = table_open(parentId, NoLock); + + CheckVirtualGeneratedExprs(rel, parent); + table_close(parent, NoLock); + } + /* Process and store partition bound, if any. */ if (stmt->partbound) { @@ -3109,8 +3123,8 @@ MergeAttributes(List *columns, const List *supers, char relpersistence, * Check for conflicts related to generated columns. * * Same rules as above: generated-ness has to match the - * parent, but the contents of the generation expression - * can be different. + * parent. For virtual generated columns, + * CheckVirtualGeneratedExprs checks the expression later. */ if (coldef->generated) { @@ -3189,7 +3203,8 @@ MergeAttributes(List *columns, const List *supers, char relpersistence, (errcode(ERRCODE_INVALID_COLUMN_DEFINITION), errmsg("column \"%s\" inherits conflicting generation expressions", def->colname), - errhint("To resolve the conflict, specify a generation expression explicitly."))); + def->generated == ATTRIBUTE_GENERATED_STORED ? + errhint("To resolve the conflict, specify a generation expression explicitly.") : 0)); else ereport(ERROR, (errcode(ERRCODE_INVALID_COLUMN_DEFINITION), @@ -3397,10 +3412,11 @@ MergeChildAttribute(List *inh_columns, int exist_attno, int newcol_attno, const * * If the parent column is generated, the child column will be made a * generated column if it isn't already. If it is a generated column, - * we'll take its generation expression in preference to the parent's. We - * must check that the child column doesn't specify a default value or - * identity, which matches the rules for a single column in - * parse_utilcmd.c. + * we'll take its generation expression in preference to the parent's, + * though for a virtual generated column CheckVirtualGeneratedExprs later + * requires the two to match. We must check that the child column doesn't + * specify a default value or identity, which matches the rules for a + * single column in parse_utilcmd.c. * * Conversely, if the parent column is not generated, the child column * can't be either. (We used to allow that, but it results in being able @@ -5100,6 +5116,7 @@ ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd, case AT_SetExpression: /* ALTER COLUMN SET EXPRESSION */ ATSimplePermissions(cmd->subtype, rel, ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE); + ATPrepSetExpression(rel, cmd, recurse, recursing, lockmode); ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context); pass = AT_PASS_SET_EXPRESSION; break; @@ -5501,7 +5518,9 @@ ATExecCmd(List **wqueue, AlteredTableInfo *tab, cmd->recurse, false, lockmode); break; case AT_SetExpression: - address = ATExecSetExpression(tab, rel, cmd->name, cmd->def, lockmode); + /* ATPrepSetExpression sets recurse for the top-level table */ + address = ATExecSetExpression(tab, rel, cmd->name, cmd->def, + cmd->recurse, lockmode); break; case AT_DropExpression: address = ATExecDropExpression(rel, cmd->name, cmd->missing_ok, lockmode); @@ -7932,6 +7951,33 @@ ATExecAddColumn(List **wqueue, AlteredTableInfo *tab, Relation rel, get_collation_name(ccollid), get_collation_name(childatt->attcollation)))); + /* + * Child column must be virtual generated if and only if parent + * column is. Our caller checks the expression. + */ + if ((colDef->generated == ATTRIBUTE_GENERATED_VIRTUAL) != + (childatt->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)) + { + if (!childatt->attgenerated) + ereport(ERROR, + (errcode(ERRCODE_DATATYPE_MISMATCH), + errmsg("column \"%s\" in child table must be a generated column", + colDef->colname))); + else if (!colDef->generated) + ereport(ERROR, + (errcode(ERRCODE_DATATYPE_MISMATCH), + errmsg("column \"%s\" in child table must not be a generated column", + colDef->colname))); + else + ereport(ERROR, + (errcode(ERRCODE_DATATYPE_MISMATCH), + errmsg("column \"%s\" inherits from generated column of different kind", + colDef->colname), + errdetail("Parent column is %s, child column is %s.", + colDef->generated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL", + childatt->attgenerated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL"))); + } + /* Bump the existing child att's inhcount */ if (pg_add_s16_overflow(childatt->attinhcount, 1, &childatt->attinhcount)) @@ -8294,6 +8340,13 @@ ATExecAddColumn(List **wqueue, AlteredTableInfo *tab, Relation rel, &childcmd, recurse, true, lockmode, cur_pass, context); + /* The child may have had the column already */ + if (colDef->generated == ATTRIBUTE_GENERATED_VIRTUAL) + { + CommandCounterIncrement(); + CheckVirtualGeneratedExprs(childrel, rel); + } + table_close(childrel, NoLock); } @@ -9266,7 +9319,7 @@ ATExecDropIdentity(Relation rel, const char *colName, bool missing_ok, LOCKMODE */ static ObjectAddress ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName, - Node *newExpr, LOCKMODE lockmode) + Node *newExpr, bool check_tree, LOCKMODE lockmode) { HeapTuple tuple; Form_pg_attribute attTup; @@ -9305,6 +9358,9 @@ ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName, if (attgenerated == ATTRIBUTE_GENERATED_VIRTUAL && attTup->attnotnull) tab->verify_new_notnull = true; + if (attgenerated == ATTRIBUTE_GENERATED_VIRTUAL && check_tree) + CheckSetExpressionTree(rel, colName, lockmode); + /* * We need to prevent this because a change of expression could affect a * row filter and inject expressions that are not permitted in a row @@ -9409,6 +9465,111 @@ ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName, return address; } +/* + * ALTER TABLE ALTER COLUMN SET EXPRESSION + * + * A virtual generated column must have the same expression in a table and in + * all its parents and children, see CheckVirtualGeneratedExprs. So the + * expression can only be changed for a whole inheritance tree, from the top. + */ +static void +ATPrepSetExpression(Relation rel, AlterTableCmd *cmd, bool recurse, + bool recursing, LOCKMODE lockmode) +{ + HeapTuple tuple; + Form_pg_attribute attTup; + char attgenerated; + int16 attinhcount; + + /* + * Check the whole tree in phase 2, once columns added by this command + * exist. See CheckSetExpressionTree. + */ + cmd->recurse = recurse && !recursing; + + if (recursing) + return; + + tuple = SearchSysCacheAttName(RelationGetRelid(rel), cmd->name); + if (!HeapTupleIsValid(tuple)) + return; /* error will be reported later */ + attTup = (Form_pg_attribute) GETSTRUCT(tuple); + attgenerated = attTup->attgenerated; + attinhcount = attTup->attinhcount; + ReleaseSysCache(tuple); + + if (attgenerated != ATTRIBUTE_GENERATED_VIRTUAL) + return; + + /* + * A partition has only one parent, so its column comes from a single + * top-level table. With plain inheritance it may come from several. + */ + if (attinhcount > 0) + ereport(ERROR, + (errcode(ERRCODE_INVALID_TABLE_DEFINITION), + errmsg("cannot alter inherited column \"%s\"", cmd->name), + rel->rd_rel->relispartition ? + errhint("Alter the generation expression of the top-level parent table instead.") : 0)); + + /* Partitions pending detach count here, as they still have the column */ + if (!recurse) + { + if (find_inheritance_children_extended(RelationGetRelid(rel), false, + NoLock, NULL, NULL) != NIL) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("ALTER TABLE / SET EXPRESSION must be applied to child tables too"))); + } +} + +/* + * Recursion skips partitions pending detach, so they would keep the old + * expression. Also, a child with another parent outside this tree would end + * up with a different expression than that parent. + */ +static void +CheckSetExpressionTree(Relation rel, const char *colName, LOCKMODE lockmode) +{ + HeapTuple tuple; + int16 attinhcount; + List *children; + List *numparents; + ListCell *lc; + ListCell *lc2; + + children = find_all_inheritors(RelationGetRelid(rel), lockmode, &numparents); + forboth(lc, children, lc2, numparents) + { + Oid childrelid = lfirst_oid(lc); + bool detached_exist = false; + + (void) find_inheritance_children_extended(childrelid, true, NoLock, + &detached_exist, NULL); + if (detached_exist) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), + errmsg("cannot alter generation expression of column \"%s\" while a partition of \"%s\" is pending detach", + colName, get_rel_name(childrelid)), + errhint("Use ALTER TABLE ... DETACH PARTITION ... FINALIZE to complete the pending detach operation."))); + + if (childrelid == RelationGetRelid(rel)) + continue; + + tuple = SearchSysCacheAttName(childrelid, colName); + if (!HeapTupleIsValid(tuple)) + continue; /* error will be reported later */ + attinhcount = ((Form_pg_attribute) GETSTRUCT(tuple))->attinhcount; + ReleaseSysCache(tuple); + + if (attinhcount > lfirst_int(lc2)) + ereport(ERROR, + (errcode(ERRCODE_INVALID_TABLE_DEFINITION), + errmsg("cannot alter inherited column \"%s\" of relation \"%s\"", + colName, get_rel_name(childrelid)))); + } +} + /* * ALTER TABLE ALTER COLUMN DROP EXPRESSION */ @@ -18854,7 +19015,8 @@ constraints_equivalent(HeapTuple a, HeapTuple b, TupleDesc tupleDesc) * partitioned tables it's a foot-gun. * * The data type must match exactly. If the parent column is NOT NULL then - * the child must be as well. Defaults are not compared, however. + * the child must be as well. Defaults are not compared, however, and neither + * are generation expressions, except for virtual generated columns. */ static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispartition) @@ -18975,6 +19137,71 @@ MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispart } table_close(attrrel, RowExclusiveLock); + + CheckVirtualGeneratedExprs(child_rel, parent_rel); +} + +/* + * CheckVirtualGeneratedExprs + * Check that each virtual generated column of a child table has the same + * generation expression as in the parent. + * + * Reading through the parent computes the parent's expression, while + * constraints on the child are checked with its own, so they must be the + * same. As in constraints_equivalent, we compare the deparsed expressions. + * That is what pg_dump restores, and unlike equal() it also catches an + * implicit cast in one and an explicit cast in the other, which + * ALTER COLUMN TYPE treats differently. + */ +static void +CheckVirtualGeneratedExprs(Relation childrel, Relation parentrel) +{ + TupleDesc parent_desc = RelationGetDescr(parentrel); + TupleDesc child_desc = RelationGetDescr(childrel); + List *parent_context; + List *child_context; + + if (parent_desc->constr == NULL || + !parent_desc->constr->has_generated_virtual) + return; + + parent_context = deparse_context_for(RelationGetRelationName(parentrel), + RelationGetRelid(parentrel)); + child_context = deparse_context_for(RelationGetRelationName(childrel), + RelationGetRelid(childrel)); + + for (int i = 0; i < parent_desc->natts; i++) + { + Form_pg_attribute parent_att = TupleDescAttr(parent_desc, i); + AttrNumber child_attno; + Node *parent_expr; + Node *child_expr; + + if (parent_att->attisdropped || + parent_att->attgenerated != ATTRIBUTE_GENERATED_VIRTUAL) + continue; + + child_attno = get_attnum(RelationGetRelid(childrel), + NameStr(parent_att->attname)); + if (child_attno == InvalidAttrNumber) + elog(ERROR, "cache lookup failed for attribute \"%s\" of relation %u", + NameStr(parent_att->attname), RelationGetRelid(childrel)); + + parent_expr = TupleDescGetDefault(parent_desc, i + 1); + child_expr = TupleDescGetDefault(child_desc, child_attno); + if (parent_expr == NULL || child_expr == NULL) + elog(ERROR, "missing generation expression for column \"%s\"", + NameStr(parent_att->attname)); + + if (strcmp(deparse_expression(parent_expr, parent_context, false, false), + deparse_expression(child_expr, child_context, false, false)) != 0) + ereport(ERROR, + (errcode(ERRCODE_INVALID_COLUMN_DEFINITION), + errmsg("column \"%s\" of relation \"%s\" must have the same generation expression as in parent relation \"%s\"", + NameStr(parent_att->attname), + RelationGetRelationName(childrel), + RelationGetRelationName(parentrel)))); + } } /* diff --git a/src/bin/pg_upgrade/check.c b/src/bin/pg_upgrade/check.c index 2d4aaf22a0f..36ec01d8f53 100644 --- a/src/bin/pg_upgrade/check.c +++ b/src/bin/pg_upgrade/check.c @@ -29,6 +29,7 @@ static void check_for_user_defined_postfix_ops(ClusterInfo *cluster); static void check_for_incompatible_polymorphics(ClusterInfo *cluster); static void check_for_tables_with_oids(ClusterInfo *cluster); static void check_for_not_null_inheritance(ClusterInfo *cluster); +static void check_for_virtual_generated_exprs(ClusterInfo *cluster); static void check_for_gist_inet_ops(ClusterInfo *cluster); static void check_for_new_tablespace_dir(void); static void check_for_user_defined_encoding_conversions(ClusterInfo *cluster); @@ -673,6 +674,15 @@ check_and_dump_old_cluster(void) if (GET_MAJOR_VERSION(old_cluster.major_version) <= 1800) check_for_not_null_inheritance(&old_cluster); + /* + * Virtual generated columns (new in PG 18) of a child table used to be + * allowed to have a different generation expression than the parent, but + * schema restore fails for them now. Verify there are none. + */ + if (GET_MAJOR_VERSION(old_cluster.major_version) >= 1800 && + GET_MAJOR_VERSION(old_cluster.major_version) <= 1900) + check_for_virtual_generated_exprs(&old_cluster); + /* * The btree_gist extension contains gist_inet_ops and gist_cidr_ops * opclasses that do not reliably give correct answers. We want to @@ -1733,6 +1743,71 @@ check_for_not_null_inheritance(ClusterInfo *cluster) check_ok(); } +/* + * check_for_virtual_generated_exprs() + * + * A virtual generated column of a child table, including a partition, must + * have the same generation expression as the parent. Check that the cluster + * to be upgraded has no child tables that differ, which older versions + * allowed. + */ +static void +check_for_virtual_generated_exprs(ClusterInfo *cluster) +{ + UpgradeTaskReport report; + UpgradeTask *task; + const char *query; + + prep_status("Checking for virtual generated column inconsistencies"); + + report.file = NULL; + snprintf(report.path, sizeof(report.path), "%s/%s", + log_opts.basedir, + "virtual_generated_columns.txt"); + + query = "SELECT nc.nspname, cc.relname, ac.attname " + "FROM pg_catalog.pg_class cc " + " JOIN pg_catalog.pg_namespace nc ON nc.oid = cc.relnamespace " + " JOIN pg_catalog.pg_inherits i ON i.inhrelid = cc.oid " + " JOIN pg_catalog.pg_attribute ac ON ac.attrelid = cc.oid " + " JOIN pg_catalog.pg_attribute ap ON ap.attrelid = i.inhparent " + " AND ap.attname = ac.attname " + " JOIN pg_catalog.pg_attrdef dc ON dc.adrelid = ac.attrelid " + " AND dc.adnum = ac.attnum " + " JOIN pg_catalog.pg_attrdef dp ON dp.adrelid = ap.attrelid " + " AND dp.adnum = ap.attnum " + "WHERE ac.attgenerated = 'v' " + " AND pg_catalog.pg_get_expr(dc.adbin, dc.adrelid) <> " + " pg_catalog.pg_get_expr(dp.adbin, dp.adrelid)"; + + task = upgrade_task_create(); + /* the not-null check's callback reports the same columns */ + upgrade_task_add_step(task, query, + process_inconsistent_notnull, + true, &report); + upgrade_task_run(task, cluster); + upgrade_task_free(task); + + if (report.file) + { + fclose(report.file); + pg_log(PG_REPORT, "fatal"); + pg_fatal("Your installation contains child tables or partitions whose virtual\n" + "generated columns have a different generation expression than the\n" + "parent table. This is no longer allowed, so the upgrade would fail.\n" + "You can fix this by running\n" + " ALTER TABLE parent ALTER COLUMN column SET EXPRESSION AS (...);\n" + "on the top-level parent table of each column. In version 18 this\n" + "is not allowed if any table in that inheritance tree has CHECK\n" + "constraints, so drop them first and add them back afterwards. Rows\n" + "that violate NOT NULL or CHECK with the new expression must be fixed\n" + "first. A list of the problem columns is in the file:\n" + " %s", report.path); + } + else + check_ok(); +} + /* * Callback function for processing results of query for * check_for_gist_inet_ops()'s UpgradeTask. If the query returned any rows diff --git a/src/test/perl/PostgreSQL/Test/AdjustUpgrade.pm b/src/test/perl/PostgreSQL/Test/AdjustUpgrade.pm index 7bea8db8e61..7c3629338e6 100644 --- a/src/test/perl/PostgreSQL/Test/AdjustUpgrade.pm +++ b/src/test/perl/PostgreSQL/Test/AdjustUpgrade.pm @@ -156,6 +156,16 @@ sub adjust_database_contents } } + # Child tables whose virtual generated column has a different expression + # than the parent's cannot be upgraded to v20. + if ($old_version >= 18 && $old_version < 20) + { + _add_st( + $result, 'regression', + 'drop table if exists generated_virtual_tests.gtest1_y', + 'drop table if exists generated_virtual_tests.gtestx'); + } + # we removed these test-support functions in v18 if ($old_version < 18) { diff --git a/src/test/regress/expected/generated_virtual.out b/src/test/regress/expected/generated_virtual.out index b14e10fb5a0..1cb239fafe8 100644 --- a/src/test/regress/expected/generated_virtual.out +++ b/src/test/regress/expected/generated_virtual.out @@ -357,15 +357,18 @@ CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 22) STORED) INHERITS NOTICE: merging column "b" with inherited definition ERROR: column "b" inherits from generated column of different kind DETAIL: Parent column is VIRTUAL, child column is STORED. -CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 22) VIRTUAL) INHERITS (gtest1); -- ok, overrides parent +CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 22) VIRTUAL) INHERITS (gtest1); -- error +NOTICE: merging column "b" with inherited definition +ERROR: column "b" of relation "gtestx" must have the same generation expression as in parent relation "gtest1" +CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL) INHERITS (gtest1); -- ok NOTICE: merging column "b" with inherited definition \d+ gtestx Table "generated_virtual_tests.gtestx" - Column | Type | Collation | Nullable | Default | Storage | Stats target | Description ---------+---------+-----------+----------+------------------------------+---------+--------------+------------- - a | integer | | not null | | plain | | - b | integer | | | generated always as (a * 22) | plain | | - x | integer | | | | plain | | + Column | Type | Collation | Nullable | Default | Storage | Stats target | Description +--------+---------+-----------+----------+-----------------------------+---------+--------------+------------- + a | integer | | not null | | plain | | + b | integer | | | generated always as (a * 2) | plain | | + x | integer | | | | plain | | Not-null constraints: "gtest1_a_not_null" NOT NULL "a" (inherited) Inherits: @@ -381,9 +384,9 @@ SELECT * FROM gtest1; (3 rows) SELECT * FROM gtestx; - a | b | x -----+-----+---- - 11 | 242 | 22 + a | b | x +----+----+---- + 11 | 22 | 22 (1 row) CREATE TABLE gtestxx_1 (a int NOT NULL, b int); @@ -408,22 +411,49 @@ CREATE TABLE gtesty (x int, b int GENERATED ALWAYS AS (x * 22) VIRTUAL); CREATE TABLE gtest1_y () INHERITS (gtest1, gtesty); -- error NOTICE: merging multiple inherited definitions of column "b" ERROR: column "b" inherits conflicting generation expressions -HINT: To resolve the conflict, specify a generation expression explicitly. -CREATE TABLE gtest1_y (b int GENERATED ALWAYS AS (x + 1) VIRTUAL) INHERITS (gtest1, gtesty); -- ok +CREATE TABLE gtest1_y (b int GENERATED ALWAYS AS (x + 1) VIRTUAL) INHERITS (gtest1, gtesty); -- error NOTICE: merging multiple inherited definitions of column "b" NOTICE: moving and merging column "b" with inherited definition DETAIL: User-specified column moved to the position of the inherited column. -\d gtest1_y - Table "generated_virtual_tests.gtest1_y" - Column | Type | Collation | Nullable | Default ---------+---------+-----------+----------+----------------------------- - a | integer | | not null | - b | integer | | | generated always as (x + 1) - x | integer | | | -Inherits: - gtest1 - gtesty - +ERROR: column "b" of relation "gtest1_y" must have the same generation expression as in parent relation "gtest1" +DROP TABLE gtesty; +-- adding a column merges it into an existing child column +CREATE TABLE gtesty (a int); +CREATE TABLE gtesty_1 (a int, b int GENERATED ALWAYS AS (a * 3) VIRTUAL) INHERITS (gtesty); +NOTICE: merging column "a" with inherited definition +CREATE TABLE gtesty_2 (a int, b int) INHERITS (gtesty); +NOTICE: merging column "a" with inherited definition +ALTER TABLE gtesty ADD COLUMN b int GENERATED ALWAYS AS (a * 2) VIRTUAL; -- error +NOTICE: merging definition of column "b" for child "gtesty_1" +ERROR: column "b" of relation "gtesty_1" must have the same generation expression as in parent relation "gtesty" +DROP TABLE gtesty_1; +ALTER TABLE gtesty ADD COLUMN b int GENERATED ALWAYS AS (a * 2) VIRTUAL; -- error +ERROR: column "b" in child table must be a generated column +DROP TABLE gtesty CASCADE; +NOTICE: drop cascades to table gtesty_2 +-- a child with two parents cannot have its expression changed through one +CREATE TABLE gtesty (a int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL); +CREATE TABLE gtestz (a int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL); +CREATE TABLE gtestyz () INHERITS (gtesty, gtestz); +NOTICE: merging multiple inherited definitions of column "a" +NOTICE: merging multiple inherited definitions of column "b" +ALTER TABLE gtesty ALTER COLUMN b SET EXPRESSION AS (a * 3); -- error +ERROR: cannot alter inherited column "b" of relation "gtestyz" +ALTER TABLE gtestyz ALTER COLUMN b SET EXPRESSION AS (a * 3); -- error, no hint +ERROR: cannot alter inherited column "b" +DROP TABLE gtesty, gtestz CASCADE; +NOTICE: drop cascades to table gtestyz +-- also when the column is added by the same command +CREATE TABLE gtestq (a int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL); +CREATE TABLE gtestp (a int); +CREATE TABLE gtestpq () INHERITS (gtestp, gtestq); +NOTICE: merging multiple inherited definitions of column "a" +ALTER TABLE gtestp ADD COLUMN b int GENERATED ALWAYS AS (a * 2) VIRTUAL, + ALTER COLUMN b SET EXPRESSION AS (a * 3); -- error +NOTICE: merging definition of column "b" for child "gtestpq" +ERROR: cannot alter inherited column "b" of relation "gtestpq" +DROP TABLE gtestp, gtestq CASCADE; +NOTICE: drop cascades to table gtestpq -- test correct handling of GENERATED column that's only in child CREATE TABLE gtestp (f1 int); CREATE TABLE gtestc (f2 int GENERATED ALWAYS AS (f1+1) VIRTUAL) INHERITS(gtestp); @@ -912,7 +942,11 @@ CREATE TABLE gtest_parent (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWA CREATE TABLE gtest_child PARTITION OF gtest_parent FOR VALUES FROM ('2016-07-01') TO ('2016-08-01'); -- inherits gen expr CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( - f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- overrides gen expr + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- error, must match parent +) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); +ERROR: column "f3" of relation "gtest_child2" must have the same generation expression as in parent relation "gtest_parent" +CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 2) VIRTUAL -- same as parent, ok ) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); CREATE TABLE gtest_child3 PARTITION OF gtest_parent ( f3 DEFAULT 42 -- error @@ -946,6 +980,17 @@ ERROR: column "f3" inherits from generated column of different kind DETAIL: Parent column is VIRTUAL, child column is STORED. DROP TABLE gtest_child3; CREATE TABLE gtest_child3 (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWAYS AS (f2 * 33) VIRTUAL); +ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); -- error +ERROR: column "f3" of relation "gtest_child3" must have the same generation expression as in parent relation "gtest_parent" +DROP TABLE gtest_child3; +-- an explicit cast is not the same as an implicit one +CREATE TABLE gtest_cast (a int, b numeric(10,0) GENERATED ALWAYS AS (a) VIRTUAL) PARTITION BY RANGE (a); +CREATE TABLE gtest_cast_1 (a int, b numeric(10,0) GENERATED ALWAYS AS (a::numeric(10,0)) VIRTUAL); +ALTER TABLE gtest_cast ATTACH PARTITION gtest_cast_1 FOR VALUES FROM (0) TO (10); -- error +ERROR: column "b" of relation "gtest_cast_1" must have the same generation expression as in parent relation "gtest_cast" +DROP TABLE gtest_cast, gtest_cast_1; +-- different column order, so the parent's expression has to be mapped +CREATE TABLE gtest_child3 (f3 bigint GENERATED ALWAYS AS (f2 * 2) VIRTUAL, f2 bigint, f1 date NOT NULL); ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); \d gtest_child Table "generated_virtual_tests.gtest_child" @@ -957,21 +1002,21 @@ ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09 Partition of: gtest_parent FOR VALUES FROM ('07-01-2016') TO ('08-01-2016') \d gtest_child2 - Table "generated_virtual_tests.gtest_child2" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- + Table "generated_virtual_tests.gtest_child2" + Column | Type | Collation | Nullable | Default +--------+--------+-----------+----------+------------------------------ f1 | date | | not null | f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 22) + f3 | bigint | | | generated always as (f2 * 2) Partition of: gtest_parent FOR VALUES FROM ('08-01-2016') TO ('09-01-2016') \d gtest_child3 - Table "generated_virtual_tests.gtest_child3" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | + Table "generated_virtual_tests.gtest_child3" + Column | Type | Collation | Nullable | Default +--------+--------+-----------+----------+------------------------------ + f3 | bigint | | | generated always as (f2 * 2) f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 33) + f1 | date | | not null | Partition of: gtest_parent FOR VALUES FROM ('09-01-2016') TO ('10-01-2016') INSERT INTO gtest_parent (f1, f2) VALUES ('2016-07-15', 1); @@ -992,14 +1037,14 @@ SELECT tableoid::regclass, * FROM gtest_child ORDER BY 1, 2, 3; gtest_child | 07-15-2016 | 2 | 4 (2 rows) -SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; -- uses child's generation expression, not parent's +SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; tableoid | f1 | f2 | f3 --------------+------------+----+---- - gtest_child2 | 08-15-2016 | 3 | 66 + gtest_child2 | 08-15-2016 | 3 | 6 (1 row) SELECT tableoid::regclass, * FROM gtest_child3 ORDER BY 1, 2, 3; - tableoid | f1 | f2 | f3 + tableoid | f3 | f2 | f1 ----------+----+----+---- (0 rows) @@ -1012,46 +1057,14 @@ SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; gtest_child3 | 09-13-2016 | 1 | 2 (3 rows) --- alter only parent's and one child's generation expression -ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -\d gtest_parent - Partitioned table "generated_virtual_tests.gtest_parent" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------ - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 4) -Partition key: RANGE (f1) -Number of partitions: 3 (Use \d+ to list them.) - -\d gtest_child - Table "generated_virtual_tests.gtest_child" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 10) -Partition of: gtest_parent FOR VALUES FROM ('07-01-2016') TO ('08-01-2016') - -\d gtest_child2 - Table "generated_virtual_tests.gtest_child2" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 22) -Partition of: gtest_parent FOR VALUES FROM ('08-01-2016') TO ('09-01-2016') - -\d gtest_child3 - Table "generated_virtual_tests.gtest_child3" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 33) -Partition of: gtest_parent FOR VALUES FROM ('09-01-2016') TO ('10-01-2016') - +-- cannot alter only parent's or one partition's generation expression +ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -- error +ERROR: ALTER TABLE / SET EXPRESSION must be applied to child tables too +ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -- error +ERROR: cannot alter inherited column "f3" +HINT: Alter the generation expression of the top-level parent table instead. +-- alter generation expression of parent and all its children altogether +ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; tableoid | f1 | f2 | f3 --------------+------------+----+---- @@ -1060,16 +1073,10 @@ SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; gtest_child3 | 09-13-2016 | 1 | 4 (3 rows) --- check constraint was validated based on each partitions's generation expression -ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 19); -- error -ERROR: check constraint "cc1" of relation "gtest_child" is violated by some row -ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 66); -- error +ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 12); -- error ERROR: check constraint "cc1" of relation "gtest_child2" is violated by some row -ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 <> 33); -- error -ERROR: check constraint "cc1" of relation "gtest_child3" is violated by some row -ALTER TABLE gtest_parent ADD CONSTRAINT cc CHECK (f3 < 67); -- ok +ALTER TABLE gtest_parent ADD CONSTRAINT cc CHECK (f3 < 13); -- ok ALTER TABLE gtest_parent DROP CONSTRAINT cc; --- alter generation expression of parent and all its children altogether ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 2); \d gtest_parent Partitioned table "generated_virtual_tests.gtest_parent" @@ -1103,9 +1110,9 @@ Partition of: gtest_parent FOR VALUES FROM ('08-01-2016') TO ('09-01-2016') Table "generated_virtual_tests.gtest_child3" Column | Type | Collation | Nullable | Default --------+--------+-----------+----------+------------------------------ - f1 | date | | not null | - f2 | bigint | | | f3 | bigint | | | generated always as (f2 * 2) + f2 | bigint | | | + f1 | date | | not null | Partition of: gtest_parent FOR VALUES FROM ('09-01-2016') TO ('10-01-2016') SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; @@ -1894,11 +1901,16 @@ select * from gtest_cursor order by id; commit; drop table gtest_cursor; --- NOT NULL on a partitioned table's virtual column does not prove non-nullness, --- because a partition can have a different generation expression +-- a partition cannot have a different generation expression, which would let +-- the partitioned table's NOT NULL virtual column read as NULL CREATE TABLE gtestnn_parent2 (a int NOT NULL, b int GENERATED ALWAYS AS (nullif(a, 0)) VIRTUAL NOT NULL) PARTITION BY LIST (a); -CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 (b GENERATED ALWAYS AS (a + 1) VIRTUAL) FOR VALUES IN (0); -INSERT INTO gtestnn_parent2 VALUES (0); +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 (b GENERATED ALWAYS AS (a + 1) VIRTUAL) FOR VALUES IN (0); -- error +ERROR: column "b" of relation "gtestnn_child2" must have the same generation expression as in parent relation "gtestnn_parent2" +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 FOR VALUES IN (0, 1); +INSERT INTO gtestnn_parent2 VALUES (0); -- error +ERROR: null value in column "b" of relation "gtestnn_child2" violates not-null constraint +DETAIL: Failing row contains (0, virtual). +INSERT INTO gtestnn_parent2 VALUES (1); EXPLAIN (COSTS OFF) SELECT a FROM gtestnn_parent2 WHERE a NOT IN (SELECT b FROM gtestnn_parent2); QUERY PLAN diff --git a/src/test/regress/sql/generated_virtual.sql b/src/test/regress/sql/generated_virtual.sql index e62880f941a..c846046a27c 100644 --- a/src/test/regress/sql/generated_virtual.sql +++ b/src/test/regress/sql/generated_virtual.sql @@ -153,7 +153,8 @@ DROP TABLE gtest_normal, gtest_normal_child; CREATE TABLE gtestx (x int, b int DEFAULT 10) INHERITS (gtest1); -- error CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS IDENTITY) INHERITS (gtest1); -- error CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 22) STORED) INHERITS (gtest1); -- error -CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 22) VIRTUAL) INHERITS (gtest1); -- ok, overrides parent +CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 22) VIRTUAL) INHERITS (gtest1); -- error +CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL) INHERITS (gtest1); -- ok \d+ gtestx INSERT INTO gtestx (a, x) VALUES (11, 22); SELECT * FROM gtest1; @@ -177,8 +178,32 @@ DROP TABLE gtesty; CREATE TABLE gtesty (x int, b int GENERATED ALWAYS AS (x * 22) VIRTUAL); CREATE TABLE gtest1_y () INHERITS (gtest1, gtesty); -- error -CREATE TABLE gtest1_y (b int GENERATED ALWAYS AS (x + 1) VIRTUAL) INHERITS (gtest1, gtesty); -- ok -\d gtest1_y +CREATE TABLE gtest1_y (b int GENERATED ALWAYS AS (x + 1) VIRTUAL) INHERITS (gtest1, gtesty); -- error +DROP TABLE gtesty; + +-- adding a column merges it into an existing child column +CREATE TABLE gtesty (a int); +CREATE TABLE gtesty_1 (a int, b int GENERATED ALWAYS AS (a * 3) VIRTUAL) INHERITS (gtesty); +CREATE TABLE gtesty_2 (a int, b int) INHERITS (gtesty); +ALTER TABLE gtesty ADD COLUMN b int GENERATED ALWAYS AS (a * 2) VIRTUAL; -- error +DROP TABLE gtesty_1; +ALTER TABLE gtesty ADD COLUMN b int GENERATED ALWAYS AS (a * 2) VIRTUAL; -- error +DROP TABLE gtesty CASCADE; + +-- a child with two parents cannot have its expression changed through one +CREATE TABLE gtesty (a int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL); +CREATE TABLE gtestz (a int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL); +CREATE TABLE gtestyz () INHERITS (gtesty, gtestz); +ALTER TABLE gtesty ALTER COLUMN b SET EXPRESSION AS (a * 3); -- error +ALTER TABLE gtestyz ALTER COLUMN b SET EXPRESSION AS (a * 3); -- error, no hint +DROP TABLE gtesty, gtestz CASCADE; +-- also when the column is added by the same command +CREATE TABLE gtestq (a int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL); +CREATE TABLE gtestp (a int); +CREATE TABLE gtestpq () INHERITS (gtestp, gtestq); +ALTER TABLE gtestp ADD COLUMN b int GENERATED ALWAYS AS (a * 2) VIRTUAL, + ALTER COLUMN b SET EXPRESSION AS (a * 3); -- error +DROP TABLE gtestp, gtestq CASCADE; -- test correct handling of GENERATED column that's only in child CREATE TABLE gtestp (f1 int); @@ -529,7 +554,10 @@ CREATE TABLE gtest_parent (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWA CREATE TABLE gtest_child PARTITION OF gtest_parent FOR VALUES FROM ('2016-07-01') TO ('2016-08-01'); -- inherits gen expr CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( - f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- overrides gen expr + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- error, must match parent +) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); +CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 2) VIRTUAL -- same as parent, ok ) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); CREATE TABLE gtest_child3 PARTITION OF gtest_parent ( f3 DEFAULT 42 -- error @@ -553,6 +581,15 @@ CREATE TABLE gtest_child3 (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWA ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); -- error DROP TABLE gtest_child3; CREATE TABLE gtest_child3 (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWAYS AS (f2 * 33) VIRTUAL); +ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); -- error +DROP TABLE gtest_child3; +-- an explicit cast is not the same as an implicit one +CREATE TABLE gtest_cast (a int, b numeric(10,0) GENERATED ALWAYS AS (a) VIRTUAL) PARTITION BY RANGE (a); +CREATE TABLE gtest_cast_1 (a int, b numeric(10,0) GENERATED ALWAYS AS (a::numeric(10,0)) VIRTUAL); +ALTER TABLE gtest_cast ATTACH PARTITION gtest_cast_1 FOR VALUES FROM (0) TO (10); -- error +DROP TABLE gtest_cast, gtest_cast_1; +-- different column order, so the parent's expression has to be mapped +CREATE TABLE gtest_child3 (f3 bigint GENERATED ALWAYS AS (f2 * 2) VIRTUAL, f2 bigint, f1 date NOT NULL); ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); \d gtest_child \d gtest_child2 @@ -562,28 +599,21 @@ INSERT INTO gtest_parent (f1, f2) VALUES ('2016-07-15', 2); INSERT INTO gtest_parent (f1, f2) VALUES ('2016-08-15', 3); SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; SELECT tableoid::regclass, * FROM gtest_child ORDER BY 1, 2, 3; -SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; -- uses child's generation expression, not parent's +SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; SELECT tableoid::regclass, * FROM gtest_child3 ORDER BY 1, 2, 3; UPDATE gtest_parent SET f1 = f1 + 60 WHERE f2 = 1; SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; --- alter only parent's and one child's generation expression -ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -\d gtest_parent -\d gtest_child -\d gtest_child2 -\d gtest_child3 -SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; - --- check constraint was validated based on each partitions's generation expression -ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 19); -- error -ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 66); -- error -ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 <> 33); -- error -ALTER TABLE gtest_parent ADD CONSTRAINT cc CHECK (f3 < 67); -- ok -ALTER TABLE gtest_parent DROP CONSTRAINT cc; +-- cannot alter only parent's or one partition's generation expression +ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -- error +ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -- error -- alter generation expression of parent and all its children altogether +ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); +SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; +ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 12); -- error +ALTER TABLE gtest_parent ADD CONSTRAINT cc CHECK (f3 < 13); -- ok +ALTER TABLE gtest_parent DROP CONSTRAINT cc; ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 2); \d gtest_parent \d gtest_child @@ -1012,11 +1042,13 @@ commit; drop table gtest_cursor; --- NOT NULL on a partitioned table's virtual column does not prove non-nullness, --- because a partition can have a different generation expression +-- a partition cannot have a different generation expression, which would let +-- the partitioned table's NOT NULL virtual column read as NULL CREATE TABLE gtestnn_parent2 (a int NOT NULL, b int GENERATED ALWAYS AS (nullif(a, 0)) VIRTUAL NOT NULL) PARTITION BY LIST (a); -CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 (b GENERATED ALWAYS AS (a + 1) VIRTUAL) FOR VALUES IN (0); -INSERT INTO gtestnn_parent2 VALUES (0); +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 (b GENERATED ALWAYS AS (a + 1) VIRTUAL) FOR VALUES IN (0); -- error +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 FOR VALUES IN (0, 1); +INSERT INTO gtestnn_parent2 VALUES (0); -- error +INSERT INTO gtestnn_parent2 VALUES (1); EXPLAIN (COSTS OFF) SELECT a FROM gtestnn_parent2 WHERE a NOT IN (SELECT b FROM gtestnn_parent2); SELECT a FROM gtestnn_parent2 WHERE a NOT IN (SELECT b FROM gtestnn_parent2); -- 2.37.1 (Apple Git-137.1)
nocfbot-v6-REL_18-0001-Require-child-tables-to-use-the-parent-s-virtual-gen.patch (application/octet-stream, 41.8K) download From fa48a0a9824558d3bf8e5f5a8d13971189dd8a11 Mon Sep 17 00:00:00 2001 From: shihao zhong <zhong950419@gmail.com> Date: Mon, 16 Nov 2026 08:04:02 -0500 Subject: [PATCH v6 REL_18] Require child tables to use the parent's virtual generation expression MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Otherwise a NOT NULL or CHECK constraint can be wrong for rows read through the parent. Suggested-by: Álvaro Herrera <alvherre@kurilemu.de> Discussion: https://postgr.es/m/E1xFKs5-0000000116b-2Cge@gemulon.postgresql.org --- doc/src/sgml/ddl.sgml | 18 +- doc/src/sgml/ref/alter_table.sgml | 5 + src/backend/commands/tablecmds.c | 249 +++++++++++++++++- .../regress/expected/generated_virtual.out | 188 +++++++------ src/test/regress/sql/generated_virtual.sql | 73 ++++- 5 files changed, 425 insertions(+), 108 deletions(-) diff --git a/doc/src/sgml/ddl.sgml b/doc/src/sgml/ddl.sgml index ddd7096f6b2..ad416a2bdf7 100644 --- a/doc/src/sgml/ddl.sgml +++ b/doc/src/sgml/ddl.sgml @@ -451,8 +451,10 @@ CREATE TABLE people ( <listitem> <para> If a parent column is a generated column, its child column must also - be a generated column of the same kind (stored or virtual); however, - the child column can have a different generation expression. + be a generated column of the same kind (stored or virtual). + A virtual generated child column must have the same generation + expression as the parent column. A stored generated child column + can have a different generation expression. </para> <para> @@ -478,8 +480,9 @@ CREATE TABLE people ( ... INHERITS</command>, then its <literal>GENERATED</literal> clause will automatically be copied from the parent. <command>ALTER TABLE ... INHERIT</command> will insist that parent and child columns - already match as to generation status, but it will not require their - generation expressions to match. + already match as to generation status, but it will only require + their generation expressions to match for virtual generated + columns. </para> </listitem> <listitem> @@ -490,8 +493,8 @@ CREATE TABLE people ( its <literal>GENERATED</literal> clause will automatically be copied from the parent. <command>ALTER TABLE ... ATTACH PARTITION</command> will insist that parent and child columns already match as to - generation status, but it will not require their generation - expressions to match. + generation status, but it will only require their generation + expressions to match for virtual generated columns. </para> </listitem> <listitem> @@ -499,7 +502,8 @@ CREATE TABLE people ( In case of multiple inheritance, if one parent column is a generated column, then all parent columns must be generated columns. If they do not all have the same generation expression, then the desired - expression for the child must be specified explicitly. + expression for the child must be specified explicitly. For virtual + generated columns, they must all have the same generation expression. </para> </listitem> </itemizedlist> diff --git a/doc/src/sgml/ref/alter_table.sgml b/doc/src/sgml/ref/alter_table.sgml index 31f2d91418b..01048b1c642 100644 --- a/doc/src/sgml/ref/alter_table.sgml +++ b/doc/src/sgml/ref/alter_table.sgml @@ -272,6 +272,11 @@ WITH ( MODULUS <replaceable class="parameter">numeric_literal</replaceable>, REM This form replaces the expression of a generated column. Existing data in a stored generated column is rewritten and all the future changes will apply the new generation expression. + The expression of a virtual generated column cannot be changed for an + inherited column, or with <literal>ONLY</literal> for a table that has + child tables. It has to be changed for the whole inheritance tree, + from the top. If a child table inherits the column from more than one + parent, the expression cannot be changed while it does. </para> <para> diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 5059909833e..c37705b1b6b 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -378,6 +378,7 @@ static List *MergeCheckConstraint(List *constraints, const char *name, Node *exp static void MergeChildAttribute(List *inh_columns, int exist_attno, int newcol_attno, const ColumnDef *newdef); static ColumnDef *MergeInheritedAttribute(List *inh_columns, int exist_attno, const ColumnDef *newdef); static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispartition); +static void CheckVirtualGeneratedExprs(Relation childrel, Relation parentrel); static void MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel); static void StoreCatalogInheritance(Oid relationId, List *supers, bool child_is_partition); @@ -521,7 +522,11 @@ static ObjectAddress ATExecSetIdentity(Relation rel, const char *colName, static ObjectAddress ATExecDropIdentity(Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode, bool recurse, bool recursing); static ObjectAddress ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName, - Node *newExpr, LOCKMODE lockmode); + Node *newExpr, bool check_tree, LOCKMODE lockmode); +static void ATPrepSetExpression(Relation rel, AlterTableCmd *cmd, bool recurse, + bool recursing, LOCKMODE lockmode); +static void CheckSetExpressionTree(Relation rel, const char *colName, + LOCKMODE lockmode); static void ATPrepDropExpression(Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode); static ObjectAddress ATExecDropExpression(Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode); static ObjectAddress ATExecSetStatistics(Relation rel, const char *colName, int16 colNum, @@ -1118,6 +1123,15 @@ DefineRelation(CreateStmt *stmt, char relkind, Oid ownerId, */ CommandCounterIncrement(); + /* Virtual generated columns must use the parents' expressions */ + foreach_oid(parentId, inheritOids) + { + Relation parent = table_open(parentId, NoLock); + + CheckVirtualGeneratedExprs(rel, parent); + table_close(parent, NoLock); + } + /* Process and store partition bound, if any. */ if (stmt->partbound) { @@ -3058,8 +3072,8 @@ MergeAttributes(List *columns, const List *supers, char relpersistence, * Check for conflicts related to generated columns. * * Same rules as above: generated-ness has to match the - * parent, but the contents of the generation expression - * can be different. + * parent. For virtual generated columns, + * CheckVirtualGeneratedExprs checks the expression later. */ if (coldef->generated) { @@ -3138,7 +3152,8 @@ MergeAttributes(List *columns, const List *supers, char relpersistence, (errcode(ERRCODE_INVALID_COLUMN_DEFINITION), errmsg("column \"%s\" inherits conflicting generation expressions", def->colname), - errhint("To resolve the conflict, specify a generation expression explicitly."))); + def->generated == ATTRIBUTE_GENERATED_STORED ? + errhint("To resolve the conflict, specify a generation expression explicitly.") : 0)); else ereport(ERROR, (errcode(ERRCODE_INVALID_COLUMN_DEFINITION), @@ -3346,10 +3361,11 @@ MergeChildAttribute(List *inh_columns, int exist_attno, int newcol_attno, const * * If the parent column is generated, the child column will be made a * generated column if it isn't already. If it is a generated column, - * we'll take its generation expression in preference to the parent's. We - * must check that the child column doesn't specify a default value or - * identity, which matches the rules for a single column in - * parse_utilcmd.c. + * we'll take its generation expression in preference to the parent's, + * though for a virtual generated column CheckVirtualGeneratedExprs later + * requires the two to match. We must check that the child column doesn't + * specify a default value or identity, which matches the rules for a + * single column in parse_utilcmd.c. * * Conversely, if the parent column is not generated, the child column * can't be either. (We used to allow that, but it results in being able @@ -5036,6 +5052,7 @@ ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd, case AT_SetExpression: /* ALTER COLUMN SET EXPRESSION */ ATSimplePermissions(cmd->subtype, rel, ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE); + ATPrepSetExpression(rel, cmd, recurse, recursing, lockmode); ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context); pass = AT_PASS_SET_EXPRESSION; break; @@ -5437,7 +5454,9 @@ ATExecCmd(List **wqueue, AlteredTableInfo *tab, cmd->recurse, false, lockmode); break; case AT_SetExpression: - address = ATExecSetExpression(tab, rel, cmd->name, cmd->def, lockmode); + /* ATPrepSetExpression sets recurse for the top-level table */ + address = ATExecSetExpression(tab, rel, cmd->name, cmd->def, + cmd->recurse, lockmode); break; case AT_DropExpression: address = ATExecDropExpression(rel, cmd->name, cmd->missing_ok, lockmode); @@ -7310,6 +7329,33 @@ ATExecAddColumn(List **wqueue, AlteredTableInfo *tab, Relation rel, get_collation_name(ccollid), get_collation_name(childatt->attcollation)))); + /* + * Child column must be virtual generated if and only if parent + * column is. Our caller checks the expression. + */ + if ((colDef->generated == ATTRIBUTE_GENERATED_VIRTUAL) != + (childatt->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)) + { + if (!childatt->attgenerated) + ereport(ERROR, + (errcode(ERRCODE_DATATYPE_MISMATCH), + errmsg("column \"%s\" in child table must be a generated column", + colDef->colname))); + else if (!colDef->generated) + ereport(ERROR, + (errcode(ERRCODE_DATATYPE_MISMATCH), + errmsg("column \"%s\" in child table must not be a generated column", + colDef->colname))); + else + ereport(ERROR, + (errcode(ERRCODE_DATATYPE_MISMATCH), + errmsg("column \"%s\" inherits from generated column of different kind", + colDef->colname), + errdetail("Parent column is %s, child column is %s.", + colDef->generated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL", + childatt->attgenerated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL"))); + } + /* Bump the existing child att's inhcount */ if (pg_add_s16_overflow(childatt->attinhcount, 1, &childatt->attinhcount)) @@ -7653,6 +7699,13 @@ ATExecAddColumn(List **wqueue, AlteredTableInfo *tab, Relation rel, &childcmd, recurse, true, lockmode, cur_pass, context); + /* The child may have had the column already */ + if (colDef->generated == ATTRIBUTE_GENERATED_VIRTUAL) + { + CommandCounterIncrement(); + CheckVirtualGeneratedExprs(childrel, rel); + } + table_close(childrel, NoLock); } @@ -8625,7 +8678,7 @@ ATExecDropIdentity(Relation rel, const char *colName, bool missing_ok, LOCKMODE */ static ObjectAddress ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName, - Node *newExpr, LOCKMODE lockmode) + Node *newExpr, bool check_tree, LOCKMODE lockmode) { HeapTuple tuple; Form_pg_attribute attTup; @@ -8676,6 +8729,9 @@ ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName, if (attgenerated == ATTRIBUTE_GENERATED_VIRTUAL && attTup->attnotnull) tab->verify_new_notnull = true; + if (attgenerated == ATTRIBUTE_GENERATED_VIRTUAL && check_tree) + CheckSetExpressionTree(rel, colName, lockmode); + /* * We need to prevent this because a change of expression could affect a * row filter and inject expressions that are not permitted in a row @@ -8774,6 +8830,111 @@ ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName, return address; } +/* + * ALTER TABLE ALTER COLUMN SET EXPRESSION + * + * A virtual generated column must have the same expression in a table and in + * all its parents and children, see CheckVirtualGeneratedExprs. So the + * expression can only be changed for a whole inheritance tree, from the top. + */ +static void +ATPrepSetExpression(Relation rel, AlterTableCmd *cmd, bool recurse, + bool recursing, LOCKMODE lockmode) +{ + HeapTuple tuple; + Form_pg_attribute attTup; + char attgenerated; + int16 attinhcount; + + /* + * Check the whole tree in phase 2, once columns added by this command + * exist. See CheckSetExpressionTree. + */ + cmd->recurse = recurse && !recursing; + + if (recursing) + return; + + tuple = SearchSysCacheAttName(RelationGetRelid(rel), cmd->name); + if (!HeapTupleIsValid(tuple)) + return; /* error will be reported later */ + attTup = (Form_pg_attribute) GETSTRUCT(tuple); + attgenerated = attTup->attgenerated; + attinhcount = attTup->attinhcount; + ReleaseSysCache(tuple); + + if (attgenerated != ATTRIBUTE_GENERATED_VIRTUAL) + return; + + /* + * A partition has only one parent, so its column comes from a single + * top-level table. With plain inheritance it may come from several. + */ + if (attinhcount > 0) + ereport(ERROR, + (errcode(ERRCODE_INVALID_TABLE_DEFINITION), + errmsg("cannot alter inherited column \"%s\"", cmd->name), + rel->rd_rel->relispartition ? + errhint("Alter the generation expression of the top-level parent table instead.") : 0)); + + /* Partitions pending detach count here, as they still have the column */ + if (!recurse) + { + if (find_inheritance_children_extended(RelationGetRelid(rel), false, + NoLock, NULL, NULL) != NIL) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("ALTER TABLE / SET EXPRESSION must be applied to child tables too"))); + } +} + +/* + * Recursion skips partitions pending detach, so they would keep the old + * expression. Also, a child with another parent outside this tree would end + * up with a different expression than that parent. + */ +static void +CheckSetExpressionTree(Relation rel, const char *colName, LOCKMODE lockmode) +{ + HeapTuple tuple; + int16 attinhcount; + List *children; + List *numparents; + ListCell *lc; + ListCell *lc2; + + children = find_all_inheritors(RelationGetRelid(rel), lockmode, &numparents); + forboth(lc, children, lc2, numparents) + { + Oid childrelid = lfirst_oid(lc); + bool detached_exist = false; + + (void) find_inheritance_children_extended(childrelid, true, NoLock, + &detached_exist, NULL); + if (detached_exist) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), + errmsg("cannot alter generation expression of column \"%s\" while a partition of \"%s\" is pending detach", + colName, get_rel_name(childrelid)), + errhint("Use ALTER TABLE ... DETACH PARTITION ... FINALIZE to complete the pending detach operation."))); + + if (childrelid == RelationGetRelid(rel)) + continue; + + tuple = SearchSysCacheAttName(childrelid, colName); + if (!HeapTupleIsValid(tuple)) + continue; /* error will be reported later */ + attinhcount = ((Form_pg_attribute) GETSTRUCT(tuple))->attinhcount; + ReleaseSysCache(tuple); + + if (attinhcount > lfirst_int(lc2)) + ereport(ERROR, + (errcode(ERRCODE_INVALID_TABLE_DEFINITION), + errmsg("cannot alter inherited column \"%s\" of relation \"%s\"", + colName, get_rel_name(childrelid)))); + } +} + /* * ALTER TABLE ALTER COLUMN DROP EXPRESSION */ @@ -17551,7 +17712,8 @@ constraints_equivalent(HeapTuple a, HeapTuple b, TupleDesc tupleDesc) * partitioned tables it's a foot-gun. * * The data type must match exactly. If the parent column is NOT NULL then - * the child must be as well. Defaults are not compared, however. + * the child must be as well. Defaults are not compared, however, and neither + * are generation expressions, except for virtual generated columns. */ static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispartition) @@ -17672,6 +17834,71 @@ MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispart } table_close(attrrel, RowExclusiveLock); + + CheckVirtualGeneratedExprs(child_rel, parent_rel); +} + +/* + * CheckVirtualGeneratedExprs + * Check that each virtual generated column of a child table has the same + * generation expression as in the parent. + * + * Reading through the parent computes the parent's expression, while + * constraints on the child are checked with its own, so they must be the + * same. As in constraints_equivalent, we compare the deparsed expressions. + * That is what pg_dump restores, and unlike equal() it also catches an + * implicit cast in one and an explicit cast in the other, which + * ALTER COLUMN TYPE treats differently. + */ +static void +CheckVirtualGeneratedExprs(Relation childrel, Relation parentrel) +{ + TupleDesc parent_desc = RelationGetDescr(parentrel); + TupleDesc child_desc = RelationGetDescr(childrel); + List *parent_context; + List *child_context; + + if (parent_desc->constr == NULL || + !parent_desc->constr->has_generated_virtual) + return; + + parent_context = deparse_context_for(RelationGetRelationName(parentrel), + RelationGetRelid(parentrel)); + child_context = deparse_context_for(RelationGetRelationName(childrel), + RelationGetRelid(childrel)); + + for (int i = 0; i < parent_desc->natts; i++) + { + Form_pg_attribute parent_att = TupleDescAttr(parent_desc, i); + AttrNumber child_attno; + Node *parent_expr; + Node *child_expr; + + if (parent_att->attisdropped || + parent_att->attgenerated != ATTRIBUTE_GENERATED_VIRTUAL) + continue; + + child_attno = get_attnum(RelationGetRelid(childrel), + NameStr(parent_att->attname)); + if (child_attno == InvalidAttrNumber) + elog(ERROR, "cache lookup failed for attribute \"%s\" of relation %u", + NameStr(parent_att->attname), RelationGetRelid(childrel)); + + parent_expr = TupleDescGetDefault(parent_desc, i + 1); + child_expr = TupleDescGetDefault(child_desc, child_attno); + if (parent_expr == NULL || child_expr == NULL) + elog(ERROR, "missing generation expression for column \"%s\"", + NameStr(parent_att->attname)); + + if (strcmp(deparse_expression(parent_expr, parent_context, false, false), + deparse_expression(child_expr, child_context, false, false)) != 0) + ereport(ERROR, + (errcode(ERRCODE_INVALID_COLUMN_DEFINITION), + errmsg("column \"%s\" of relation \"%s\" must have the same generation expression as in parent relation \"%s\"", + NameStr(parent_att->attname), + RelationGetRelationName(childrel), + RelationGetRelationName(parentrel)))); + } } /* diff --git a/src/test/regress/expected/generated_virtual.out b/src/test/regress/expected/generated_virtual.out index 03698488907..9fb79e9f5cd 100644 --- a/src/test/regress/expected/generated_virtual.out +++ b/src/test/regress/expected/generated_virtual.out @@ -356,15 +356,18 @@ CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 22) STORED) INHERITS NOTICE: merging column "b" with inherited definition ERROR: column "b" inherits from generated column of different kind DETAIL: Parent column is VIRTUAL, child column is STORED. -CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 22) VIRTUAL) INHERITS (gtest1); -- ok, overrides parent +CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 22) VIRTUAL) INHERITS (gtest1); -- error +NOTICE: merging column "b" with inherited definition +ERROR: column "b" of relation "gtestx" must have the same generation expression as in parent relation "gtest1" +CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL) INHERITS (gtest1); -- ok NOTICE: merging column "b" with inherited definition \d+ gtestx Table "generated_virtual_tests.gtestx" - Column | Type | Collation | Nullable | Default | Storage | Stats target | Description ---------+---------+-----------+----------+------------------------------+---------+--------------+------------- - a | integer | | not null | | plain | | - b | integer | | | generated always as (a * 22) | plain | | - x | integer | | | | plain | | + Column | Type | Collation | Nullable | Default | Storage | Stats target | Description +--------+---------+-----------+----------+-----------------------------+---------+--------------+------------- + a | integer | | not null | | plain | | + b | integer | | | generated always as (a * 2) | plain | | + x | integer | | | | plain | | Not-null constraints: "gtest1_a_not_null" NOT NULL "a" (inherited) Inherits: gtest1 @@ -379,9 +382,9 @@ SELECT * FROM gtest1; (3 rows) SELECT * FROM gtestx; - a | b | x -----+-----+---- - 11 | 242 | 22 + a | b | x +----+----+---- + 11 | 22 | 22 (1 row) CREATE TABLE gtestxx_1 (a int NOT NULL, b int); @@ -406,21 +409,49 @@ CREATE TABLE gtesty (x int, b int GENERATED ALWAYS AS (x * 22) VIRTUAL); CREATE TABLE gtest1_y () INHERITS (gtest1, gtesty); -- error NOTICE: merging multiple inherited definitions of column "b" ERROR: column "b" inherits conflicting generation expressions -HINT: To resolve the conflict, specify a generation expression explicitly. -CREATE TABLE gtest1_y (b int GENERATED ALWAYS AS (x + 1) VIRTUAL) INHERITS (gtest1, gtesty); -- ok +CREATE TABLE gtest1_y (b int GENERATED ALWAYS AS (x + 1) VIRTUAL) INHERITS (gtest1, gtesty); -- error NOTICE: merging multiple inherited definitions of column "b" NOTICE: moving and merging column "b" with inherited definition DETAIL: User-specified column moved to the position of the inherited column. -\d gtest1_y - Table "generated_virtual_tests.gtest1_y" - Column | Type | Collation | Nullable | Default ---------+---------+-----------+----------+----------------------------- - a | integer | | not null | - b | integer | | | generated always as (x + 1) - x | integer | | | -Inherits: gtest1, - gtesty - +ERROR: column "b" of relation "gtest1_y" must have the same generation expression as in parent relation "gtest1" +DROP TABLE gtesty; +-- adding a column merges it into an existing child column +CREATE TABLE gtesty (a int); +CREATE TABLE gtesty_1 (a int, b int GENERATED ALWAYS AS (a * 3) VIRTUAL) INHERITS (gtesty); +NOTICE: merging column "a" with inherited definition +CREATE TABLE gtesty_2 (a int, b int) INHERITS (gtesty); +NOTICE: merging column "a" with inherited definition +ALTER TABLE gtesty ADD COLUMN b int GENERATED ALWAYS AS (a * 2) VIRTUAL; -- error +NOTICE: merging definition of column "b" for child "gtesty_1" +ERROR: column "b" of relation "gtesty_1" must have the same generation expression as in parent relation "gtesty" +DROP TABLE gtesty_1; +ALTER TABLE gtesty ADD COLUMN b int GENERATED ALWAYS AS (a * 2) VIRTUAL; -- error +ERROR: column "b" in child table must be a generated column +DROP TABLE gtesty CASCADE; +NOTICE: drop cascades to table gtesty_2 +-- a child with two parents cannot have its expression changed through one +CREATE TABLE gtesty (a int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL); +CREATE TABLE gtestz (a int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL); +CREATE TABLE gtestyz () INHERITS (gtesty, gtestz); +NOTICE: merging multiple inherited definitions of column "a" +NOTICE: merging multiple inherited definitions of column "b" +ALTER TABLE gtesty ALTER COLUMN b SET EXPRESSION AS (a * 3); -- error +ERROR: cannot alter inherited column "b" of relation "gtestyz" +ALTER TABLE gtestyz ALTER COLUMN b SET EXPRESSION AS (a * 3); -- error, no hint +ERROR: cannot alter inherited column "b" +DROP TABLE gtesty, gtestz CASCADE; +NOTICE: drop cascades to table gtestyz +-- also when the column is added by the same command +CREATE TABLE gtestq (a int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL); +CREATE TABLE gtestp (a int); +CREATE TABLE gtestpq () INHERITS (gtestp, gtestq); +NOTICE: merging multiple inherited definitions of column "a" +ALTER TABLE gtestp ADD COLUMN b int GENERATED ALWAYS AS (a * 2) VIRTUAL, + ALTER COLUMN b SET EXPRESSION AS (a * 3); -- error +NOTICE: merging definition of column "b" for child "gtestpq" +ERROR: cannot alter inherited column "b" of relation "gtestpq" +DROP TABLE gtestp, gtestq CASCADE; +NOTICE: drop cascades to table gtestpq -- test correct handling of GENERATED column that's only in child CREATE TABLE gtestp (f1 int); CREATE TABLE gtestc (f2 int GENERATED ALWAYS AS (f1+1) VIRTUAL) INHERITS(gtestp); @@ -882,7 +913,11 @@ CREATE TABLE gtest_parent (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWA CREATE TABLE gtest_child PARTITION OF gtest_parent FOR VALUES FROM ('2016-07-01') TO ('2016-08-01'); -- inherits gen expr CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( - f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- overrides gen expr + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- error, must match parent +) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); +ERROR: column "f3" of relation "gtest_child2" must have the same generation expression as in parent relation "gtest_parent" +CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 2) VIRTUAL -- same as parent, ok ) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); CREATE TABLE gtest_child3 PARTITION OF gtest_parent ( f3 DEFAULT 42 -- error @@ -916,6 +951,17 @@ ERROR: column "f3" inherits from generated column of different kind DETAIL: Parent column is VIRTUAL, child column is STORED. DROP TABLE gtest_child3; CREATE TABLE gtest_child3 (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWAYS AS (f2 * 33) VIRTUAL); +ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); -- error +ERROR: column "f3" of relation "gtest_child3" must have the same generation expression as in parent relation "gtest_parent" +DROP TABLE gtest_child3; +-- an explicit cast is not the same as an implicit one +CREATE TABLE gtest_cast (a int, b numeric(10,0) GENERATED ALWAYS AS (a) VIRTUAL) PARTITION BY RANGE (a); +CREATE TABLE gtest_cast_1 (a int, b numeric(10,0) GENERATED ALWAYS AS (a::numeric(10,0)) VIRTUAL); +ALTER TABLE gtest_cast ATTACH PARTITION gtest_cast_1 FOR VALUES FROM (0) TO (10); -- error +ERROR: column "b" of relation "gtest_cast_1" must have the same generation expression as in parent relation "gtest_cast" +DROP TABLE gtest_cast, gtest_cast_1; +-- different column order, so the parent's expression has to be mapped +CREATE TABLE gtest_child3 (f3 bigint GENERATED ALWAYS AS (f2 * 2) VIRTUAL, f2 bigint, f1 date NOT NULL); ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); \d gtest_child Table "generated_virtual_tests.gtest_child" @@ -927,21 +973,21 @@ ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09 Partition of: gtest_parent FOR VALUES FROM ('07-01-2016') TO ('08-01-2016') \d gtest_child2 - Table "generated_virtual_tests.gtest_child2" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- + Table "generated_virtual_tests.gtest_child2" + Column | Type | Collation | Nullable | Default +--------+--------+-----------+----------+------------------------------ f1 | date | | not null | f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 22) + f3 | bigint | | | generated always as (f2 * 2) Partition of: gtest_parent FOR VALUES FROM ('08-01-2016') TO ('09-01-2016') \d gtest_child3 - Table "generated_virtual_tests.gtest_child3" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | + Table "generated_virtual_tests.gtest_child3" + Column | Type | Collation | Nullable | Default +--------+--------+-----------+----------+------------------------------ + f3 | bigint | | | generated always as (f2 * 2) f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 33) + f1 | date | | not null | Partition of: gtest_parent FOR VALUES FROM ('09-01-2016') TO ('10-01-2016') INSERT INTO gtest_parent (f1, f2) VALUES ('2016-07-15', 1); @@ -962,14 +1008,14 @@ SELECT tableoid::regclass, * FROM gtest_child ORDER BY 1, 2, 3; gtest_child | 07-15-2016 | 2 | 4 (2 rows) -SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; -- uses child's generation expression, not parent's +SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; tableoid | f1 | f2 | f3 --------------+------------+----+---- - gtest_child2 | 08-15-2016 | 3 | 66 + gtest_child2 | 08-15-2016 | 3 | 6 (1 row) SELECT tableoid::regclass, * FROM gtest_child3 ORDER BY 1, 2, 3; - tableoid | f1 | f2 | f3 + tableoid | f3 | f2 | f1 ----------+----+----+---- (0 rows) @@ -982,46 +1028,14 @@ SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; gtest_child3 | 09-13-2016 | 1 | 2 (3 rows) --- alter only parent's and one child's generation expression -ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -\d gtest_parent - Partitioned table "generated_virtual_tests.gtest_parent" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------ - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 4) -Partition key: RANGE (f1) -Number of partitions: 3 (Use \d+ to list them.) - -\d gtest_child - Table "generated_virtual_tests.gtest_child" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 10) -Partition of: gtest_parent FOR VALUES FROM ('07-01-2016') TO ('08-01-2016') - -\d gtest_child2 - Table "generated_virtual_tests.gtest_child2" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 22) -Partition of: gtest_parent FOR VALUES FROM ('08-01-2016') TO ('09-01-2016') - -\d gtest_child3 - Table "generated_virtual_tests.gtest_child3" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 33) -Partition of: gtest_parent FOR VALUES FROM ('09-01-2016') TO ('10-01-2016') - +-- cannot alter only parent's or one partition's generation expression +ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -- error +ERROR: ALTER TABLE / SET EXPRESSION must be applied to child tables too +ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -- error +ERROR: cannot alter inherited column "f3" +HINT: Alter the generation expression of the top-level parent table instead. +-- alter generation expression of parent and all its children altogether +ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; tableoid | f1 | f2 | f3 --------------+------------+----+---- @@ -1030,7 +1044,10 @@ SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; gtest_child3 | 09-13-2016 | 1 | 4 (3 rows) --- alter generation expression of parent and all its children altogether +ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 12); -- error +ERROR: check constraint "cc1" of relation "gtest_child2" is violated by some row +ALTER TABLE gtest_parent ADD CONSTRAINT cc CHECK (f3 < 13); -- ok +ALTER TABLE gtest_parent DROP CONSTRAINT cc; ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 2); \d gtest_parent Partitioned table "generated_virtual_tests.gtest_parent" @@ -1064,9 +1081,9 @@ Partition of: gtest_parent FOR VALUES FROM ('08-01-2016') TO ('09-01-2016') Table "generated_virtual_tests.gtest_child3" Column | Type | Collation | Nullable | Default --------+--------+-----------+----------+------------------------------ - f1 | date | | not null | - f2 | bigint | | | f3 | bigint | | | generated always as (f2 * 2) + f2 | bigint | | | + f1 | date | | not null | Partition of: gtest_parent FOR VALUES FROM ('09-01-2016') TO ('10-01-2016') SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; @@ -1812,3 +1829,20 @@ select * from gtest_cursor order by id; commit; drop table gtest_cursor; +-- a partition cannot have a different generation expression, which would let +-- the partitioned table's NOT NULL virtual column read as NULL +CREATE TABLE gtestnn_parent2 (a int NOT NULL, b int GENERATED ALWAYS AS (nullif(a, 0)) VIRTUAL NOT NULL) PARTITION BY LIST (a); +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 (b GENERATED ALWAYS AS (a + 1) VIRTUAL) FOR VALUES IN (0); -- error +ERROR: column "b" of relation "gtestnn_child2" must have the same generation expression as in parent relation "gtestnn_parent2" +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 FOR VALUES IN (0, 1); +INSERT INTO gtestnn_parent2 VALUES (0); -- error +ERROR: null value in column "b" of relation "gtestnn_child2" violates not-null constraint +DETAIL: Failing row contains (0, virtual). +INSERT INTO gtestnn_parent2 VALUES (1); +SELECT a, b FROM gtestnn_parent2; + a | b +---+--- + 1 | 1 +(1 row) + +DROP TABLE gtestnn_parent2; diff --git a/src/test/regress/sql/generated_virtual.sql b/src/test/regress/sql/generated_virtual.sql index b1b92b2ced5..489f42ac255 100644 --- a/src/test/regress/sql/generated_virtual.sql +++ b/src/test/regress/sql/generated_virtual.sql @@ -153,7 +153,8 @@ DROP TABLE gtest_normal, gtest_normal_child; CREATE TABLE gtestx (x int, b int DEFAULT 10) INHERITS (gtest1); -- error CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS IDENTITY) INHERITS (gtest1); -- error CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 22) STORED) INHERITS (gtest1); -- error -CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 22) VIRTUAL) INHERITS (gtest1); -- ok, overrides parent +CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 22) VIRTUAL) INHERITS (gtest1); -- error +CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL) INHERITS (gtest1); -- ok \d+ gtestx INSERT INTO gtestx (a, x) VALUES (11, 22); SELECT * FROM gtest1; @@ -177,8 +178,32 @@ DROP TABLE gtesty; CREATE TABLE gtesty (x int, b int GENERATED ALWAYS AS (x * 22) VIRTUAL); CREATE TABLE gtest1_y () INHERITS (gtest1, gtesty); -- error -CREATE TABLE gtest1_y (b int GENERATED ALWAYS AS (x + 1) VIRTUAL) INHERITS (gtest1, gtesty); -- ok -\d gtest1_y +CREATE TABLE gtest1_y (b int GENERATED ALWAYS AS (x + 1) VIRTUAL) INHERITS (gtest1, gtesty); -- error +DROP TABLE gtesty; + +-- adding a column merges it into an existing child column +CREATE TABLE gtesty (a int); +CREATE TABLE gtesty_1 (a int, b int GENERATED ALWAYS AS (a * 3) VIRTUAL) INHERITS (gtesty); +CREATE TABLE gtesty_2 (a int, b int) INHERITS (gtesty); +ALTER TABLE gtesty ADD COLUMN b int GENERATED ALWAYS AS (a * 2) VIRTUAL; -- error +DROP TABLE gtesty_1; +ALTER TABLE gtesty ADD COLUMN b int GENERATED ALWAYS AS (a * 2) VIRTUAL; -- error +DROP TABLE gtesty CASCADE; + +-- a child with two parents cannot have its expression changed through one +CREATE TABLE gtesty (a int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL); +CREATE TABLE gtestz (a int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL); +CREATE TABLE gtestyz () INHERITS (gtesty, gtestz); +ALTER TABLE gtesty ALTER COLUMN b SET EXPRESSION AS (a * 3); -- error +ALTER TABLE gtestyz ALTER COLUMN b SET EXPRESSION AS (a * 3); -- error, no hint +DROP TABLE gtesty, gtestz CASCADE; +-- also when the column is added by the same command +CREATE TABLE gtestq (a int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL); +CREATE TABLE gtestp (a int); +CREATE TABLE gtestpq () INHERITS (gtestp, gtestq); +ALTER TABLE gtestp ADD COLUMN b int GENERATED ALWAYS AS (a * 2) VIRTUAL, + ALTER COLUMN b SET EXPRESSION AS (a * 3); -- error +DROP TABLE gtestp, gtestq CASCADE; -- test correct handling of GENERATED column that's only in child CREATE TABLE gtestp (f1 int); @@ -514,7 +539,10 @@ CREATE TABLE gtest_parent (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWA CREATE TABLE gtest_child PARTITION OF gtest_parent FOR VALUES FROM ('2016-07-01') TO ('2016-08-01'); -- inherits gen expr CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( - f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- overrides gen expr + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- error, must match parent +) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); +CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 2) VIRTUAL -- same as parent, ok ) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); CREATE TABLE gtest_child3 PARTITION OF gtest_parent ( f3 DEFAULT 42 -- error @@ -538,6 +566,15 @@ CREATE TABLE gtest_child3 (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWA ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); -- error DROP TABLE gtest_child3; CREATE TABLE gtest_child3 (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWAYS AS (f2 * 33) VIRTUAL); +ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); -- error +DROP TABLE gtest_child3; +-- an explicit cast is not the same as an implicit one +CREATE TABLE gtest_cast (a int, b numeric(10,0) GENERATED ALWAYS AS (a) VIRTUAL) PARTITION BY RANGE (a); +CREATE TABLE gtest_cast_1 (a int, b numeric(10,0) GENERATED ALWAYS AS (a::numeric(10,0)) VIRTUAL); +ALTER TABLE gtest_cast ATTACH PARTITION gtest_cast_1 FOR VALUES FROM (0) TO (10); -- error +DROP TABLE gtest_cast, gtest_cast_1; +-- different column order, so the parent's expression has to be mapped +CREATE TABLE gtest_child3 (f3 bigint GENERATED ALWAYS AS (f2 * 2) VIRTUAL, f2 bigint, f1 date NOT NULL); ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); \d gtest_child \d gtest_child2 @@ -547,21 +584,21 @@ INSERT INTO gtest_parent (f1, f2) VALUES ('2016-07-15', 2); INSERT INTO gtest_parent (f1, f2) VALUES ('2016-08-15', 3); SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; SELECT tableoid::regclass, * FROM gtest_child ORDER BY 1, 2, 3; -SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; -- uses child's generation expression, not parent's +SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; SELECT tableoid::regclass, * FROM gtest_child3 ORDER BY 1, 2, 3; UPDATE gtest_parent SET f1 = f1 + 60 WHERE f2 = 1; SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; --- alter only parent's and one child's generation expression -ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -\d gtest_parent -\d gtest_child -\d gtest_child2 -\d gtest_child3 -SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; +-- cannot alter only parent's or one partition's generation expression +ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -- error +ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -- error -- alter generation expression of parent and all its children altogether +ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); +SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; +ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 12); -- error +ALTER TABLE gtest_parent ADD CONSTRAINT cc CHECK (f3 < 13); -- ok +ALTER TABLE gtest_parent DROP CONSTRAINT cc; ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 2); \d gtest_parent \d gtest_child @@ -969,3 +1006,13 @@ select * from gtest_cursor order by id; commit; drop table gtest_cursor; + +-- a partition cannot have a different generation expression, which would let +-- the partitioned table's NOT NULL virtual column read as NULL +CREATE TABLE gtestnn_parent2 (a int NOT NULL, b int GENERATED ALWAYS AS (nullif(a, 0)) VIRTUAL NOT NULL) PARTITION BY LIST (a); +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 (b GENERATED ALWAYS AS (a + 1) VIRTUAL) FOR VALUES IN (0); -- error +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 FOR VALUES IN (0, 1); +INSERT INTO gtestnn_parent2 VALUES (0); -- error +INSERT INTO gtestnn_parent2 VALUES (1); +SELECT a, b FROM gtestnn_parent2; +DROP TABLE gtestnn_parent2; -- 2.37.1 (Apple Git-137.1)
^ permalink raw reply [nested|flat] 24+ messages in thread

* Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned
  2026-10-10 00:23 pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Richard Guo <rguo@postgresql.org>
  2026-10-13 12:42 ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-10-13 14:34   ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Richard Guo <guofenglinux@gmail.com>
  2026-10-13 15:41     ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-10-13 16:00       ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-10-14 04:39         ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-10-26 17:40           ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Manu <manuelreyesbravo@gmail.com>
  2026-10-27 03:10             ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-11-11 15:41               ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-11-11 15:47                 ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-11-12 04:36                   ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-11-14 01:12                     ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Manu <manuelreyesbravo@gmail.com>
  2026-11-15 03:36                       ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-11-15 21:15                         ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Zsolt Parragi <zsolt.parragi@percona.com>
  2026-11-17 01:43                           ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-11-17 19:26                             ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Zsolt Parragi <zsolt.parragi@percona.com>
  2026-11-19 05:01                               ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
@ 2026-11-19 19:08                                 ` Manu <manuelreyesbravo@gmail.com>
  2026-11-24 03:31                                   ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  0 siblings, 1 reply; 24+ messages in thread

From: Manu @ 2026-11-19 19:08 UTC (permalink / raw)
  To: shihao zhong <zhong950419@gmail.com>; +Cc: Zsolt Parragi <zsolt.parragi@percona.com>; Álvaro Herrera <alvherre@kurilemu.de>; Richard Guo <guofenglinux@gmail.com>; pgsql-hackers@lists.postgresql.org

Hi Shihao,

On Thu, Nov 19, 2026 at 12:01 AM shihao zhong <zhong950419@gmail.com>
wrote:
> Thanks for catching both, v6 attached.

v6 passes everything we had, on master (b443bc7406f), REL_19_STABLE
(b1bc8f8ea5d) and, in its 18 version, REL_18_STABLE (ecfe3a44dab).
Two new cases, both on trees that an unpatched 18 or 19 left
divergent, after the minor update.

1. A child with two parents.  The pg_upgrade text says to run SET
EXPRESSION on the top-level parent, which works on unpatched 18 but
not with the patch:

  -- unpatched 18
  CREATE TABLE ip (x int, v int GENERATED ALWAYS AS (x * 2) VIRTUAL);
  CREATE TABLE iq (x int, v int GENERATED ALWAYS AS (x * 2) VIRTUAL);
  CREATE TABLE ic (v int GENERATED ALWAYS AS (x * 3) VIRTUAL)
    INHERITS (ip, iq);
  -- 18 with the patch; the same on 19 with the master patch
  ALTER TABLE ip ALTER COLUMN v SET EXPRESSION AS (x * 2);
  ERROR:  cannot alter inherited column "v" of relation "ic"

The same for iq.  If the parents' expressions differ (x * 2 and
x * 3, the child giving its own, as 18's ddl.sgml asks), the text
does not work on any branch, unpatched included.  What works on all
of them is NO INHERIT from all parents but one, SET EXPRESSION, and
INHERIT again.  Maybe, after "add them back afterwards.":

  A child table with more than one parent must first be removed from
  all but one with NO INHERIT, and added back once all its parents
  have the same expression.

2. With the patch, adding a virtual column to the parent of such a
tree fails, naming the old column:

  -- unpatched 18
  CREATE TABLE ta (x int, v int GENERATED ALWAYS AS (x * 2) VIRTUAL)
    PARTITION BY LIST (x);
  CREATE TABLE ta1 PARTITION OF ta
    (v GENERATED ALWAYS AS (x * 3) VIRTUAL) FOR VALUES IN (1);
  -- 18 with the patch
  ALTER TABLE ta ADD COLUMN w int GENERATED ALWAYS AS (x + 1) VIRTUAL;
  ERROR:  column "v" of relation "ta1" must have the same generation
  expression as in parent relation "ta"

The check after the recursion in ATExecAddColumn (tablecmds.c:8347
on master, 8285 on 18) compares every virtual column of the parent,
but only the one being added is new to the child; ATTACH and INHERIT
are the ones that bring a whole new parent.  Maybe compare only that
column there?

Regards,
Manu






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

* Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned
  2026-10-10 00:23 pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Richard Guo <rguo@postgresql.org>
  2026-10-13 12:42 ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-10-13 14:34   ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Richard Guo <guofenglinux@gmail.com>
  2026-10-13 15:41     ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-10-13 16:00       ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-10-14 04:39         ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-10-26 17:40           ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Manu <manuelreyesbravo@gmail.com>
  2026-10-27 03:10             ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-11-11 15:41               ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-11-11 15:47                 ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-11-12 04:36                   ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-11-14 01:12                     ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Manu <manuelreyesbravo@gmail.com>
  2026-11-15 03:36                       ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-11-15 21:15                         ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Zsolt Parragi <zsolt.parragi@percona.com>
  2026-11-17 01:43                           ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-11-17 19:26                             ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Zsolt Parragi <zsolt.parragi@percona.com>
  2026-11-19 05:01                               ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-11-19 19:08                                 ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Manu <manuelreyesbravo@gmail.com>
@ 2026-11-24 03:31                                   ` shihao zhong <zhong950419@gmail.com>
  2026-11-25 01:42                                     ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Manu <manuelreyesbravo@gmail.com>
  0 siblings, 1 reply; 24+ messages in thread

From: shihao zhong @ 2026-11-24 03:31 UTC (permalink / raw)
  To: Manu <manuelreyesbravo@gmail.com>; +Cc: Zsolt Parragi <zsolt.parragi@percona.com>; Álvaro Herrera <alvherre@kurilemu.de>; Richard Guo <guofenglinux@gmail.com>; pgsql-hackers@lists.postgresql.org

Hi Manu,

Thanks for testing v6, both cases reproduce here. v7 is attached for
master, 19 and 18.

ADD COLUMN now checks only the new column, and the pg_upgrade message
uses your text. v7 also compares the expressions with the settings
pg_dump uses, and it no longer breaks test_ddl_deparse.

Thanks,
Shihao

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

nocfbot-v7-REL_19-0001-Require-child-tables-to-use-the-parent-s-virtual-.patch (application/x-patch, 54.7K) download From c03bc1444f82c71fda27a3b184ab8853390469a6 Mon Sep 17 00:00:00 2001 From: shihao zhong <zhong950419@gmail.com> Date: Tue, 13 Oct 2026 23:22:52 -0400 Subject: [PATCH v7] Require child tables to use the parent's virtual generation expression MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Otherwise a NOT NULL or CHECK constraint can be wrong for rows read through the parent. Suggested-by: Álvaro Herrera <alvherre@kurilemu.de> Discussion: https://postgr.es/m/E1xFKs5-0000000116b-2Cge@gemulon.postgresql.org --- doc/src/sgml/ddl.sgml | 18 +- doc/src/sgml/ref/alter_table.sgml | 5 + src/backend/commands/tablecmds.c | 271 +++++++++++++++++- src/bin/pg_upgrade/check.c | 84 ++++++ .../perl/PostgreSQL/Test/AdjustUpgrade.pm | 10 + .../regress/expected/generated_virtual.out | 241 ++++++++++------ src/test/regress/sql/generated_virtual.sql | 117 ++++++-- 7 files changed, 619 insertions(+), 127 deletions(-) diff --git a/doc/src/sgml/ddl.sgml b/doc/src/sgml/ddl.sgml index 52ff2b8b165..6dcec1084d8 100644 --- a/doc/src/sgml/ddl.sgml +++ b/doc/src/sgml/ddl.sgml @@ -451,8 +451,10 @@ CREATE TABLE people ( <listitem> <para> If a parent column is a generated column, its child column must also - be a generated column of the same kind (stored or virtual); however, - the child column can have a different generation expression. + be a generated column of the same kind (stored or virtual). + A virtual generated child column must have the same generation + expression as the parent column. A stored generated child column + can have a different generation expression. </para> <para> @@ -478,8 +480,9 @@ CREATE TABLE people ( ... INHERITS</command>, then its <literal>GENERATED</literal> clause will automatically be copied from the parent. <command>ALTER TABLE ... INHERIT</command> will insist that parent and child columns - already match as to generation status, but it will not require their - generation expressions to match. + already match as to generation status, but it will only require + their generation expressions to match for virtual generated + columns. </para> </listitem> <listitem> @@ -490,8 +493,8 @@ CREATE TABLE people ( its <literal>GENERATED</literal> clause will automatically be copied from the parent. <command>ALTER TABLE ... ATTACH PARTITION</command> will insist that parent and child columns already match as to - generation status, but it will not require their generation - expressions to match. + generation status, but it will only require their generation + expressions to match for virtual generated columns. </para> </listitem> <listitem> @@ -499,7 +502,8 @@ CREATE TABLE people ( In case of multiple inheritance, if one parent column is a generated column, then all parent columns must be generated columns. If they do not all have the same generation expression, then the desired - expression for the child must be specified explicitly. + expression for the child must be specified explicitly. For virtual + generated columns, they must all have the same generation expression. </para> </listitem> </itemizedlist> diff --git a/doc/src/sgml/ref/alter_table.sgml b/doc/src/sgml/ref/alter_table.sgml index 8495d531465..c87e221e88d 100644 --- a/doc/src/sgml/ref/alter_table.sgml +++ b/doc/src/sgml/ref/alter_table.sgml @@ -276,6 +276,11 @@ WITH ( MODULUS <replaceable class="parameter">numeric_literal</replaceable>, REM Replacing the expression of a virtual generated column does not require a table rewrite, but if the column is used in a constraint, the table will be scanned to check that existing rows meet the constraint. + The expression of a virtual generated column cannot be changed for an + inherited column, or with <literal>ONLY</literal> for a table that has + child tables. It has to be changed for the whole inheritance tree, + from the top. If a child table also inherits the column from a parent + outside that tree, the expression cannot be changed while it does. </para> <para> diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 18182ab47dc..f6339927283 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -383,6 +383,8 @@ static List *MergeCheckConstraint(List *constraints, const char *name, Node *exp static void MergeChildAttribute(List *inh_columns, int exist_attno, int newcol_attno, const ColumnDef *newdef); static ColumnDef *MergeInheritedAttribute(List *inh_columns, int exist_attno, const ColumnDef *newdef); static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispartition); +static void CheckVirtualGeneratedExprs(Relation childrel, Relation parentrel, + const char *colname); static void MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel); static void StoreCatalogInheritance(Oid relationId, List *supers, bool child_is_partition); @@ -553,6 +555,10 @@ static ObjectAddress ATExecDropIdentity(Relation rel, const char *colName, bool bool recurse, bool recursing); static ObjectAddress ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName, Node *newExpr, LOCKMODE lockmode); +static void ATPrepSetExpression(Relation rel, AlterTableCmd *cmd, bool recurse, + bool recursing, LOCKMODE lockmode); +static void CheckSetExpressionTree(Relation rel, const char *colName, + LOCKMODE lockmode); static void ATPrepDropExpression(Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode); static ObjectAddress ATExecDropExpression(Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode); static ObjectAddress ATExecSetStatistics(Relation rel, const char *colName, int16 colNum, @@ -1151,6 +1157,15 @@ DefineRelation(CreateStmt *stmt, char relkind, Oid ownerId, */ CommandCounterIncrement(); + /* Virtual generated columns must use the parents' expressions */ + foreach_oid(parentId, inheritOids) + { + Relation parent = table_open(parentId, NoLock); + + CheckVirtualGeneratedExprs(rel, parent, NULL); + table_close(parent, NoLock); + } + /* Process and store partition bound, if any. */ if (stmt->partbound) { @@ -3096,8 +3111,8 @@ MergeAttributes(List *columns, const List *supers, char relpersistence, * Check for conflicts related to generated columns. * * Same rules as above: generated-ness has to match the - * parent, but the contents of the generation expression - * can be different. + * parent. For virtual generated columns, + * CheckVirtualGeneratedExprs checks the expression later. */ if (coldef->generated) { @@ -3176,7 +3191,8 @@ MergeAttributes(List *columns, const List *supers, char relpersistence, (errcode(ERRCODE_INVALID_COLUMN_DEFINITION), errmsg("column \"%s\" inherits conflicting generation expressions", def->colname), - errhint("To resolve the conflict, specify a generation expression explicitly."))); + def->generated == ATTRIBUTE_GENERATED_STORED ? + errhint("To resolve the conflict, specify a generation expression explicitly.") : 0)); else ereport(ERROR, (errcode(ERRCODE_INVALID_COLUMN_DEFINITION), @@ -3384,10 +3400,11 @@ MergeChildAttribute(List *inh_columns, int exist_attno, int newcol_attno, const * * If the parent column is generated, the child column will be made a * generated column if it isn't already. If it is a generated column, - * we'll take its generation expression in preference to the parent's. We - * must check that the child column doesn't specify a default value or - * identity, which matches the rules for a single column in - * parse_utilcmd.c. + * we'll take its generation expression in preference to the parent's, + * though for a virtual generated column CheckVirtualGeneratedExprs later + * requires the two to match. We must check that the child column doesn't + * specify a default value or identity, which matches the rules for a + * single column in parse_utilcmd.c. * * Conversely, if the parent column is not generated, the child column * can't be either. (We used to allow that, but it results in being able @@ -5074,6 +5091,7 @@ ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd, case AT_SetExpression: /* ALTER COLUMN SET EXPRESSION */ ATSimplePermissions(cmd->subtype, rel, ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE); + ATPrepSetExpression(rel, cmd, recurse, recursing, lockmode); ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context); pass = AT_PASS_SET_EXPRESSION; break; @@ -7892,6 +7910,33 @@ ATExecAddColumn(List **wqueue, AlteredTableInfo *tab, Relation rel, get_collation_name(ccollid), get_collation_name(childatt->attcollation)))); + /* + * Child column must be virtual generated if and only if parent + * column is. Our caller checks the expression. + */ + if ((colDef->generated == ATTRIBUTE_GENERATED_VIRTUAL) != + (childatt->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)) + { + if (!childatt->attgenerated) + ereport(ERROR, + (errcode(ERRCODE_DATATYPE_MISMATCH), + errmsg("column \"%s\" in child table must be a generated column", + colDef->colname))); + else if (!colDef->generated) + ereport(ERROR, + (errcode(ERRCODE_DATATYPE_MISMATCH), + errmsg("column \"%s\" in child table must not be a generated column", + colDef->colname))); + else + ereport(ERROR, + (errcode(ERRCODE_DATATYPE_MISMATCH), + errmsg("column \"%s\" inherits from generated column of different kind", + colDef->colname), + errdetail("Parent column is %s, child column is %s.", + colDef->generated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL", + childatt->attgenerated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL"))); + } + /* Bump the existing child att's inhcount */ if (pg_add_s16_overflow(childatt->attinhcount, 1, &childatt->attinhcount)) @@ -8258,6 +8303,17 @@ ATExecAddColumn(List **wqueue, AlteredTableInfo *tab, Relation rel, &childcmd, recurse, true, lockmode, cur_pass, context); + /* + * The child may have had the column already. Only this column is new + * to the child, so don't compare the others: they may differ in a + * tree that was created before the check was added. + */ + if (colDef->generated == ATTRIBUTE_GENERATED_VIRTUAL) + { + CommandCounterIncrement(); + CheckVirtualGeneratedExprs(childrel, rel, colDef->colname); + } + table_close(childrel, NoLock); } @@ -9269,6 +9325,13 @@ ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName, if (attgenerated == ATTRIBUTE_GENERATED_VIRTUAL && attTup->attnotnull) tab->verify_new_notnull = true; + /* + * Check the whole tree from the table the column comes from, now that + * columns added by this command exist. + */ + if (attgenerated == ATTRIBUTE_GENERATED_VIRTUAL && attTup->attinhcount == 0) + CheckSetExpressionTree(rel, colName, lockmode); + /* * We need to prevent this because a change of expression could affect a * row filter and inject expressions that are not permitted in a row @@ -9373,6 +9436,105 @@ ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName, return address; } +/* + * ALTER TABLE ALTER COLUMN SET EXPRESSION + * + * A virtual generated column must have the same expression in a table and in + * all its parents and children, see CheckVirtualGeneratedExprs. So the + * expression can only be changed for a whole inheritance tree, from the top. + */ +static void +ATPrepSetExpression(Relation rel, AlterTableCmd *cmd, bool recurse, + bool recursing, LOCKMODE lockmode) +{ + HeapTuple tuple; + Form_pg_attribute attTup; + char attgenerated; + int16 attinhcount; + + if (recursing) + return; + + tuple = SearchSysCacheAttName(RelationGetRelid(rel), cmd->name); + if (!HeapTupleIsValid(tuple)) + return; /* error will be reported later */ + attTup = (Form_pg_attribute) GETSTRUCT(tuple); + attgenerated = attTup->attgenerated; + attinhcount = attTup->attinhcount; + ReleaseSysCache(tuple); + + if (attgenerated != ATTRIBUTE_GENERATED_VIRTUAL) + return; + + /* + * A partition has only one parent, so its column comes from a single + * top-level table. With plain inheritance it may come from several. + */ + if (attinhcount > 0) + ereport(ERROR, + (errcode(ERRCODE_INVALID_TABLE_DEFINITION), + errmsg("cannot alter inherited column \"%s\"", cmd->name), + rel->rd_rel->relispartition ? + errhint("Alter the generation expression of the top-level parent table instead.") : 0)); + + /* Partitions pending detach count here, as they still have the column */ + if (!recurse) + { + if (find_inheritance_children_extended(RelationGetRelid(rel), false, + NoLock, NULL, NULL) != NIL) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("ALTER TABLE / SET EXPRESSION must be applied to child tables too"))); + } +} + +/* + * Recursion skips partitions pending detach, so they would keep the old + * expression. Also, a child with another parent outside this tree would end + * up with a different expression than that parent. + */ +static void +CheckSetExpressionTree(Relation rel, const char *colName, LOCKMODE lockmode) +{ + HeapTuple tuple; + int16 attinhcount; + List *children; + List *numparents; + ListCell *lc; + ListCell *lc2; + + children = find_all_inheritors(RelationGetRelid(rel), lockmode, &numparents); + forboth(lc, children, lc2, numparents) + { + Oid childrelid = lfirst_oid(lc); + bool detached_exist = false; + + (void) find_inheritance_children_extended(childrelid, true, NoLock, + &detached_exist, NULL); + if (detached_exist) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), + errmsg("cannot alter generation expression of column \"%s\" while a partition of \"%s\" is pending detach", + colName, get_rel_name(childrelid)), + errhint("Use ALTER TABLE ... DETACH PARTITION ... FINALIZE to complete the pending detach operation."))); + + if (childrelid == RelationGetRelid(rel)) + continue; + + tuple = SearchSysCacheAttName(childrelid, colName); + if (!HeapTupleIsValid(tuple)) + continue; /* error will be reported later */ + attinhcount = ((Form_pg_attribute) GETSTRUCT(tuple))->attinhcount; + ReleaseSysCache(tuple); + + if (attinhcount > lfirst_int(lc2)) + ereport(ERROR, + (errcode(ERRCODE_INVALID_TABLE_DEFINITION), + errmsg("cannot alter inherited column \"%s\" of relation \"%s\"", + colName, get_rel_name(childrelid)))); + } +} + /* * ALTER TABLE ALTER COLUMN DROP EXPRESSION */ @@ -18795,7 +18957,8 @@ constraints_equivalent(HeapTuple a, HeapTuple b, TupleDesc tupleDesc) * partitioned tables it's a foot-gun. * * The data type must match exactly. If the parent column is NOT NULL then - * the child must be as well. Defaults are not compared, however. + * the child must be as well. Defaults are not compared, however, and neither + * are generation expressions, except for virtual generated columns. */ static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispartition) @@ -18916,6 +19079,98 @@ MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispart } table_close(attrrel, RowExclusiveLock); + + CheckVirtualGeneratedExprs(child_rel, parent_rel, NULL); +} + +/* + * CheckVirtualGeneratedExprs + * Check that each virtual generated column of a child table has the same + * generation expression as in the parent. If colname is not NULL, check + * only that column. + * + * Reading through the parent computes the parent's expression, while + * constraints on the child are checked with its own, so they must be the + * same. As in constraints_equivalent, we compare the deparsed expressions. + * That is what pg_dump restores, and unlike equal() it also catches an + * implicit cast in one and an explicit cast in the other, which + * ALTER COLUMN TYPE treats differently. The trees themselves can differ in + * ways that do not matter, such as the collation fields that + * ALTER COLUMN TYPE leaves unset. + * + * Deparse with the settings pg_dump uses, so that constants are printed + * without ambiguity whatever the session's settings are: a low + * extra_float_digits rounds float constants, and some DateStyles hide the + * UTC offset of a timestamptz constant. Constants of types such as regproc + * can still look the same when they are not. + */ +static void +CheckVirtualGeneratedExprs(Relation childrel, Relation parentrel, + const char *colname) +{ + TupleDesc parent_desc = RelationGetDescr(parentrel); + TupleDesc child_desc = RelationGetDescr(childrel); + List *parent_context; + List *child_context; + int save_nestlevel; + + if (parent_desc->constr == NULL || + !parent_desc->constr->has_generated_virtual) + return; + + save_nestlevel = NewGUCNestLevel(); + (void) set_config_option("extra_float_digits", "3", + PGC_USERSET, PGC_S_SESSION, + GUC_ACTION_SAVE, true, 0, false); + (void) set_config_option("datestyle", "ISO", + PGC_USERSET, PGC_S_SESSION, + GUC_ACTION_SAVE, true, 0, false); + (void) set_config_option("intervalstyle", "postgres", + PGC_USERSET, PGC_S_SESSION, + GUC_ACTION_SAVE, true, 0, false); + + parent_context = deparse_context_for(RelationGetRelationName(parentrel), + RelationGetRelid(parentrel)); + child_context = deparse_context_for(RelationGetRelationName(childrel), + RelationGetRelid(childrel)); + + for (int i = 0; i < parent_desc->natts; i++) + { + Form_pg_attribute parent_att = TupleDescAttr(parent_desc, i); + AttrNumber child_attno; + Node *parent_expr; + Node *child_expr; + + if (parent_att->attisdropped || + parent_att->attgenerated != ATTRIBUTE_GENERATED_VIRTUAL) + continue; + + if (colname != NULL && strcmp(colname, NameStr(parent_att->attname)) != 0) + continue; + + child_attno = get_attnum(RelationGetRelid(childrel), + NameStr(parent_att->attname)); + if (child_attno == InvalidAttrNumber) + elog(ERROR, "cache lookup failed for attribute \"%s\" of relation %u", + NameStr(parent_att->attname), RelationGetRelid(childrel)); + + parent_expr = TupleDescGetDefault(parent_desc, i + 1); + child_expr = TupleDescGetDefault(child_desc, child_attno); + if (parent_expr == NULL || child_expr == NULL) + elog(ERROR, "missing generation expression for column \"%s\"", + NameStr(parent_att->attname)); + + if (strcmp(deparse_expression(parent_expr, parent_context, false, false), + deparse_expression(child_expr, child_context, false, false)) != 0) + ereport(ERROR, + (errcode(ERRCODE_INVALID_COLUMN_DEFINITION), + errmsg("column \"%s\" of relation \"%s\" must have the same generation expression as in parent relation \"%s\"", + NameStr(parent_att->attname), + RelationGetRelationName(childrel), + RelationGetRelationName(parentrel)))); + } + + AtEOXact_GUC(false, save_nestlevel); } /* diff --git a/src/bin/pg_upgrade/check.c b/src/bin/pg_upgrade/check.c index affc9e3c6cf..d2a27f715b9 100644 --- a/src/bin/pg_upgrade/check.c +++ b/src/bin/pg_upgrade/check.c @@ -29,6 +29,7 @@ static void check_for_user_defined_postfix_ops(ClusterInfo *cluster); static void check_for_incompatible_polymorphics(ClusterInfo *cluster); static void check_for_tables_with_oids(ClusterInfo *cluster); static void check_for_not_null_inheritance(ClusterInfo *cluster); +static void check_for_virtual_generated_exprs(ClusterInfo *cluster); static void check_for_gist_inet_ops(ClusterInfo *cluster); static void check_for_pg_role_prefix(ClusterInfo *cluster); static void check_for_new_tablespace_dir(void); @@ -701,6 +702,15 @@ check_and_dump_old_cluster(void) if (GET_MAJOR_VERSION(old_cluster.major_version) <= 1800) check_for_not_null_inheritance(&old_cluster); + /* + * Virtual generated columns (new in PG 18) of a child table used to be + * allowed to have a different generation expression than the parent, but + * schema restore fails for them now. Verify there are none. + */ + if (GET_MAJOR_VERSION(old_cluster.major_version) >= 1800 && + GET_MAJOR_VERSION(old_cluster.major_version) <= 1900) + check_for_virtual_generated_exprs(&old_cluster); + /* * The btree_gist extension contains gist_inet_ops and gist_cidr_ops * opclasses that do not reliably give correct answers. We want to @@ -1800,6 +1810,80 @@ check_for_not_null_inheritance(ClusterInfo *cluster) check_ok(); } +/* + * check_for_virtual_generated_exprs() + * + * A virtual generated column of a child table, including a partition, must + * have the same generation expression as the parent. Check that the cluster + * to be upgraded has no child tables that differ, which older versions + * allowed. + */ +static void +check_for_virtual_generated_exprs(ClusterInfo *cluster) +{ + UpgradeTaskReport report; + UpgradeTask *task; + const char *query; + + prep_status("Checking for virtual generated column inconsistencies"); + + report.file = NULL; + snprintf(report.path, sizeof(report.path), "%s/%s", + log_opts.basedir, + "virtual_generated_columns.txt"); + + query = "SELECT DISTINCT nc.nspname, cc.relname, ac.attname " + "FROM pg_catalog.pg_class cc " + " JOIN pg_catalog.pg_namespace nc ON nc.oid = cc.relnamespace " + " JOIN pg_catalog.pg_inherits i ON i.inhrelid = cc.oid " + " JOIN pg_catalog.pg_attribute ac ON ac.attrelid = cc.oid " + " JOIN pg_catalog.pg_attribute ap ON ap.attrelid = i.inhparent " + " AND ap.attname = ac.attname " + " JOIN pg_catalog.pg_attrdef dc ON dc.adrelid = ac.attrelid " + " AND dc.adnum = ac.attnum " + " JOIN pg_catalog.pg_attrdef dp ON dp.adrelid = ap.attrelid " + " AND dp.adnum = ap.attnum " + "WHERE ac.attgenerated = 'v' " + " AND pg_catalog.pg_get_expr(dc.adbin, dc.adrelid) <> " + " pg_catalog.pg_get_expr(dp.adbin, dp.adrelid)"; + + task = upgrade_task_create(); + /* deparse constants the way the server's check does */ + upgrade_task_add_step(task, + "SELECT pg_catalog.set_config('extra_float_digits', '3', false), " + "pg_catalog.set_config('datestyle', 'ISO', false), " + "pg_catalog.set_config('intervalstyle', 'postgres', false)", + NULL, true, NULL); + /* the not-null check's callback reports the same columns */ + upgrade_task_add_step(task, query, + process_inconsistent_notnull, + true, &report); + upgrade_task_run(task, cluster); + upgrade_task_free(task); + + if (report.file) + { + fclose(report.file); + pg_log(PG_REPORT, "fatal"); + pg_fatal("Your installation contains child tables or partitions whose virtual\n" + "generated columns have a different generation expression than the\n" + "parent table. This is no longer allowed, so the upgrade would fail.\n" + "You can fix this by running\n" + " ALTER TABLE parent ALTER COLUMN column SET EXPRESSION AS (...);\n" + "on the top-level parent table of each column. In version 18 this\n" + "is not allowed if any table in that inheritance tree has CHECK\n" + "constraints, so drop them first and add them back afterwards. A\n" + "child table with more than one parent must first be removed from\n" + "all but one with NO INHERIT, and added back once all its parents\n" + "have the same expression. Rows that violate NOT NULL or CHECK with\n" + "the new expression must be fixed first. A list of the problem\n" + "columns is in the file:\n" + " %s", report.path); + } + else + check_ok(); +} + /* * Callback function for processing results of query for * check_for_gist_inet_ops()'s UpgradeTask. If the query returned any rows diff --git a/src/test/perl/PostgreSQL/Test/AdjustUpgrade.pm b/src/test/perl/PostgreSQL/Test/AdjustUpgrade.pm index 4df813eafc6..2779a71ee8f 100644 --- a/src/test/perl/PostgreSQL/Test/AdjustUpgrade.pm +++ b/src/test/perl/PostgreSQL/Test/AdjustUpgrade.pm @@ -141,6 +141,16 @@ sub adjust_database_contents } } + # Child tables whose virtual generated column has a different expression + # than the parent's cannot be upgraded to v20. + if ($old_version >= 18 && $old_version < 20) + { + _add_st( + $result, 'regression', + 'drop table if exists generated_virtual_tests.gtest1_y', + 'drop table if exists generated_virtual_tests.gtestx'); + } + # we removed these test-support functions in v18 if ($old_version < 18) { diff --git a/src/test/regress/expected/generated_virtual.out b/src/test/regress/expected/generated_virtual.out index b14e10fb5a0..17fee3f1eb8 100644 --- a/src/test/regress/expected/generated_virtual.out +++ b/src/test/regress/expected/generated_virtual.out @@ -357,15 +357,18 @@ CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 22) STORED) INHERITS NOTICE: merging column "b" with inherited definition ERROR: column "b" inherits from generated column of different kind DETAIL: Parent column is VIRTUAL, child column is STORED. -CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 22) VIRTUAL) INHERITS (gtest1); -- ok, overrides parent +CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 22) VIRTUAL) INHERITS (gtest1); -- error +NOTICE: merging column "b" with inherited definition +ERROR: column "b" of relation "gtestx" must have the same generation expression as in parent relation "gtest1" +CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL) INHERITS (gtest1); -- ok NOTICE: merging column "b" with inherited definition \d+ gtestx Table "generated_virtual_tests.gtestx" - Column | Type | Collation | Nullable | Default | Storage | Stats target | Description ---------+---------+-----------+----------+------------------------------+---------+--------------+------------- - a | integer | | not null | | plain | | - b | integer | | | generated always as (a * 22) | plain | | - x | integer | | | | plain | | + Column | Type | Collation | Nullable | Default | Storage | Stats target | Description +--------+---------+-----------+----------+-----------------------------+---------+--------------+------------- + a | integer | | not null | | plain | | + b | integer | | | generated always as (a * 2) | plain | | + x | integer | | | | plain | | Not-null constraints: "gtest1_a_not_null" NOT NULL "a" (inherited) Inherits: @@ -381,9 +384,9 @@ SELECT * FROM gtest1; (3 rows) SELECT * FROM gtestx; - a | b | x -----+-----+---- - 11 | 242 | 22 + a | b | x +----+----+---- + 11 | 22 | 22 (1 row) CREATE TABLE gtestxx_1 (a int NOT NULL, b int); @@ -408,22 +411,102 @@ CREATE TABLE gtesty (x int, b int GENERATED ALWAYS AS (x * 22) VIRTUAL); CREATE TABLE gtest1_y () INHERITS (gtest1, gtesty); -- error NOTICE: merging multiple inherited definitions of column "b" ERROR: column "b" inherits conflicting generation expressions -HINT: To resolve the conflict, specify a generation expression explicitly. -CREATE TABLE gtest1_y (b int GENERATED ALWAYS AS (x + 1) VIRTUAL) INHERITS (gtest1, gtesty); -- ok +CREATE TABLE gtest1_y (b int GENERATED ALWAYS AS (x + 1) VIRTUAL) INHERITS (gtest1, gtesty); -- error NOTICE: merging multiple inherited definitions of column "b" NOTICE: moving and merging column "b" with inherited definition DETAIL: User-specified column moved to the position of the inherited column. -\d gtest1_y - Table "generated_virtual_tests.gtest1_y" - Column | Type | Collation | Nullable | Default ---------+---------+-----------+----------+----------------------------- - a | integer | | not null | - b | integer | | | generated always as (x + 1) - x | integer | | | -Inherits: - gtest1 - gtesty +ERROR: column "b" of relation "gtest1_y" must have the same generation expression as in parent relation "gtest1" +DROP TABLE gtesty; +-- adding a column merges it into an existing child column +CREATE TABLE gtesty (a int); +CREATE TABLE gtesty_1 (a int, b int GENERATED ALWAYS AS (a * 3) VIRTUAL) INHERITS (gtesty); +NOTICE: merging column "a" with inherited definition +CREATE TABLE gtesty_2 (a int, b int) INHERITS (gtesty); +NOTICE: merging column "a" with inherited definition +ALTER TABLE gtesty ADD COLUMN b int GENERATED ALWAYS AS (a * 2) VIRTUAL; -- error +NOTICE: merging definition of column "b" for child "gtesty_1" +ERROR: column "b" of relation "gtesty_1" must have the same generation expression as in parent relation "gtesty" +DROP TABLE gtesty_1; +ALTER TABLE gtesty ADD COLUMN b int GENERATED ALWAYS AS (a * 2) VIRTUAL; -- error +ERROR: column "b" in child table must be a generated column +DROP TABLE gtesty CASCADE; +NOTICE: drop cascades to table gtesty_2 +-- a child with two parents cannot have its expression changed through one +CREATE TABLE gtesty (a int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL); +CREATE TABLE gtestz (a int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL); +CREATE TABLE gtestyz () INHERITS (gtesty, gtestz); +NOTICE: merging multiple inherited definitions of column "a" +NOTICE: merging multiple inherited definitions of column "b" +ALTER TABLE gtesty ALTER COLUMN b SET EXPRESSION AS (a * 3); -- error +ERROR: cannot alter inherited column "b" of relation "gtestyz" +ALTER TABLE gtestyz ALTER COLUMN b SET EXPRESSION AS (a * 3); -- error, no hint +ERROR: cannot alter inherited column "b" +DROP TABLE gtesty, gtestz CASCADE; +NOTICE: drop cascades to table gtestyz +-- also when the column is added by the same command +CREATE TABLE gtestq (a int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL); +CREATE TABLE gtestp (a int); +CREATE TABLE gtestpq () INHERITS (gtestp, gtestq); +NOTICE: merging multiple inherited definitions of column "a" +ALTER TABLE gtestp ADD COLUMN b int GENERATED ALWAYS AS (a * 2) VIRTUAL, + ALTER COLUMN b SET EXPRESSION AS (a * 3); -- error +NOTICE: merging definition of column "b" for child "gtestpq" +ERROR: cannot alter inherited column "b" of relation "gtestpq" +DROP TABLE gtestp, gtestq CASCADE; +NOTICE: drop cascades to table gtestpq +-- Trees made by older minor versions can have a child whose expression +-- differs, which CREATE and ATTACH no longer allow. Emulate one by writing a +-- different expression directly into the child's pg_attrdef row. +CREATE TABLE gtestd (a int, b int GENERATED ALWAYS AS (a * 3) VIRTUAL); +CREATE TABLE gtestr (a int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL) PARTITION BY LIST (a); +CREATE TABLE gtestr1 PARTITION OF gtestr FOR VALUES IN (1); +UPDATE pg_attrdef SET adbin = (SELECT adbin FROM pg_attrdef WHERE adrelid = 'gtestd'::regclass) + WHERE adrelid = 'gtestr1'::regclass; +-- adding a column checks only the new column, not the old one +ALTER TABLE gtestr ADD COLUMN c int GENERATED ALWAYS AS (a + 1) VIRTUAL; +INSERT INTO gtestr VALUES (1); +SELECT * FROM gtestr; + a | b | c +---+---+--- + 1 | 2 | 2 +(1 row) +-- but the new column is still checked against a child that already has it +CREATE TABLE gtests (a int); +CREATE TABLE gtests1 (a int, c int GENERATED ALWAYS AS (a * 5) VIRTUAL) INHERITS (gtests); +NOTICE: merging column "a" with inherited definition +ALTER TABLE gtests ADD COLUMN c int GENERATED ALWAYS AS (a + 1) VIRTUAL; -- error +NOTICE: merging definition of column "c" for child "gtests1" +ERROR: column "c" of relation "gtests1" must have the same generation expression as in parent relation "gtests" +ALTER TABLE gtests ADD COLUMN c int GENERATED ALWAYS AS (a * 5) VIRTUAL; -- ok +NOTICE: merging definition of column "c" for child "gtests1" +DROP TABLE gtestd, gtestr, gtests CASCADE; +NOTICE: drop cascades to table gtests1 +-- constants that differ can have the same text, depending on settings +CREATE TABLE gtestf (a float4, b float4 GENERATED ALWAYS AS (a * '0.1'::float4) VIRTUAL); +SET extra_float_digits = 0; +CREATE TABLE gtestf1 (b float4 GENERATED ALWAYS AS (a * '0.10000001'::float4) VIRTUAL) INHERITS (gtestf); -- error +NOTICE: moving and merging column "b" with inherited definition +DETAIL: User-specified column moved to the position of the inherited column. +ERROR: column "b" of relation "gtestf1" must have the same generation expression as in parent relation "gtestf" +RESET extra_float_digits; +DROP TABLE gtestf; +CREATE TABLE gtestz (a timestamptz, b boolean GENERATED ALWAYS AS (a < '2014-10-25 21:30:00+00'::timestamptz) VIRTUAL); +SET DateStyle = 'SQL, MDY'; +SET TimeZone = 'Europe/Moscow'; +CREATE TABLE gtestz1 (b boolean GENERATED ALWAYS AS (a < '2014-10-25 22:30:00+00'::timestamptz) VIRTUAL) INHERITS (gtestz); -- error +NOTICE: moving and merging column "b" with inherited definition +DETAIL: User-specified column moved to the position of the inherited column. +ERROR: column "b" of relation "gtestz1" must have the same generation expression as in parent relation "gtestz" +RESET DateStyle; +RESET TimeZone; +DROP TABLE gtestz; +-- a child written by hand still matches after the parent's type was changed +CREATE TABLE gtestt (a int, b varchar(5), c varchar(5) GENERATED ALWAYS AS (b) VIRTUAL) PARTITION BY LIST (a); +ALTER TABLE gtestt ALTER COLUMN c TYPE varchar(10); +CREATE TABLE gtestt1 (a int, b varchar(5), c varchar(10) GENERATED ALWAYS AS (b) VIRTUAL); +ALTER TABLE gtestt ATTACH PARTITION gtestt1 FOR VALUES IN (1); +DROP TABLE gtestt; -- test correct handling of GENERATED column that's only in child CREATE TABLE gtestp (f1 int); CREATE TABLE gtestc (f2 int GENERATED ALWAYS AS (f1+1) VIRTUAL) INHERITS(gtestp); @@ -912,7 +995,11 @@ CREATE TABLE gtest_parent (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWA CREATE TABLE gtest_child PARTITION OF gtest_parent FOR VALUES FROM ('2016-07-01') TO ('2016-08-01'); -- inherits gen expr CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( - f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- overrides gen expr + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- error, must match parent +) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); +ERROR: column "f3" of relation "gtest_child2" must have the same generation expression as in parent relation "gtest_parent" +CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 2) VIRTUAL -- same as parent, ok ) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); CREATE TABLE gtest_child3 PARTITION OF gtest_parent ( f3 DEFAULT 42 -- error @@ -946,6 +1033,17 @@ ERROR: column "f3" inherits from generated column of different kind DETAIL: Parent column is VIRTUAL, child column is STORED. DROP TABLE gtest_child3; CREATE TABLE gtest_child3 (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWAYS AS (f2 * 33) VIRTUAL); +ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); -- error +ERROR: column "f3" of relation "gtest_child3" must have the same generation expression as in parent relation "gtest_parent" +DROP TABLE gtest_child3; +-- an explicit cast is not the same as an implicit one +CREATE TABLE gtest_cast (a int, b numeric(10,0) GENERATED ALWAYS AS (a) VIRTUAL) PARTITION BY RANGE (a); +CREATE TABLE gtest_cast_1 (a int, b numeric(10,0) GENERATED ALWAYS AS (a::numeric(10,0)) VIRTUAL); +ALTER TABLE gtest_cast ATTACH PARTITION gtest_cast_1 FOR VALUES FROM (0) TO (10); -- error +ERROR: column "b" of relation "gtest_cast_1" must have the same generation expression as in parent relation "gtest_cast" +DROP TABLE gtest_cast, gtest_cast_1; +-- different column order, so the parent's expression has to be mapped +CREATE TABLE gtest_child3 (f3 bigint GENERATED ALWAYS AS (f2 * 2) VIRTUAL, f2 bigint, f1 date NOT NULL); ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); \d gtest_child Table "generated_virtual_tests.gtest_child" @@ -957,21 +1055,21 @@ ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09 Partition of: gtest_parent FOR VALUES FROM ('07-01-2016') TO ('08-01-2016') \d gtest_child2 - Table "generated_virtual_tests.gtest_child2" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- + Table "generated_virtual_tests.gtest_child2" + Column | Type | Collation | Nullable | Default +--------+--------+-----------+----------+------------------------------ f1 | date | | not null | f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 22) + f3 | bigint | | | generated always as (f2 * 2) Partition of: gtest_parent FOR VALUES FROM ('08-01-2016') TO ('09-01-2016') \d gtest_child3 - Table "generated_virtual_tests.gtest_child3" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | + Table "generated_virtual_tests.gtest_child3" + Column | Type | Collation | Nullable | Default +--------+--------+-----------+----------+------------------------------ + f3 | bigint | | | generated always as (f2 * 2) f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 33) + f1 | date | | not null | Partition of: gtest_parent FOR VALUES FROM ('09-01-2016') TO ('10-01-2016') INSERT INTO gtest_parent (f1, f2) VALUES ('2016-07-15', 1); @@ -992,14 +1090,14 @@ SELECT tableoid::regclass, * FROM gtest_child ORDER BY 1, 2, 3; gtest_child | 07-15-2016 | 2 | 4 (2 rows) -SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; -- uses child's generation expression, not parent's +SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; tableoid | f1 | f2 | f3 --------------+------------+----+---- - gtest_child2 | 08-15-2016 | 3 | 66 + gtest_child2 | 08-15-2016 | 3 | 6 (1 row) SELECT tableoid::regclass, * FROM gtest_child3 ORDER BY 1, 2, 3; - tableoid | f1 | f2 | f3 + tableoid | f3 | f2 | f1 ----------+----+----+---- (0 rows) @@ -1012,46 +1110,14 @@ SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; gtest_child3 | 09-13-2016 | 1 | 2 (3 rows) --- alter only parent's and one child's generation expression -ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -\d gtest_parent - Partitioned table "generated_virtual_tests.gtest_parent" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------ - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 4) -Partition key: RANGE (f1) -Number of partitions: 3 (Use \d+ to list them.) - -\d gtest_child - Table "generated_virtual_tests.gtest_child" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 10) -Partition of: gtest_parent FOR VALUES FROM ('07-01-2016') TO ('08-01-2016') - -\d gtest_child2 - Table "generated_virtual_tests.gtest_child2" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 22) -Partition of: gtest_parent FOR VALUES FROM ('08-01-2016') TO ('09-01-2016') - -\d gtest_child3 - Table "generated_virtual_tests.gtest_child3" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 33) -Partition of: gtest_parent FOR VALUES FROM ('09-01-2016') TO ('10-01-2016') - +-- cannot alter only parent's or one partition's generation expression +ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -- error +ERROR: ALTER TABLE / SET EXPRESSION must be applied to child tables too +ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -- error +ERROR: cannot alter inherited column "f3" +HINT: Alter the generation expression of the top-level parent table instead. +-- alter generation expression of parent and all its children altogether +ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; tableoid | f1 | f2 | f3 --------------+------------+----+---- @@ -1060,16 +1126,10 @@ SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; gtest_child3 | 09-13-2016 | 1 | 4 (3 rows) --- check constraint was validated based on each partitions's generation expression -ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 19); -- error -ERROR: check constraint "cc1" of relation "gtest_child" is violated by some row -ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 66); -- error +ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 12); -- error ERROR: check constraint "cc1" of relation "gtest_child2" is violated by some row -ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 <> 33); -- error -ERROR: check constraint "cc1" of relation "gtest_child3" is violated by some row -ALTER TABLE gtest_parent ADD CONSTRAINT cc CHECK (f3 < 67); -- ok +ALTER TABLE gtest_parent ADD CONSTRAINT cc CHECK (f3 < 13); -- ok ALTER TABLE gtest_parent DROP CONSTRAINT cc; --- alter generation expression of parent and all its children altogether ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 2); \d gtest_parent Partitioned table "generated_virtual_tests.gtest_parent" @@ -1103,9 +1163,9 @@ Partition of: gtest_parent FOR VALUES FROM ('08-01-2016') TO ('09-01-2016') Table "generated_virtual_tests.gtest_child3" Column | Type | Collation | Nullable | Default --------+--------+-----------+----------+------------------------------ - f1 | date | | not null | - f2 | bigint | | | f3 | bigint | | | generated always as (f2 * 2) + f2 | bigint | | | + f1 | date | | not null | Partition of: gtest_parent FOR VALUES FROM ('09-01-2016') TO ('10-01-2016') SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; @@ -1894,11 +1954,16 @@ select * from gtest_cursor order by id; commit; drop table gtest_cursor; --- NOT NULL on a partitioned table's virtual column does not prove non-nullness, --- because a partition can have a different generation expression +-- a partition cannot have a different generation expression, which would let +-- the partitioned table's NOT NULL virtual column read as NULL CREATE TABLE gtestnn_parent2 (a int NOT NULL, b int GENERATED ALWAYS AS (nullif(a, 0)) VIRTUAL NOT NULL) PARTITION BY LIST (a); -CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 (b GENERATED ALWAYS AS (a + 1) VIRTUAL) FOR VALUES IN (0); -INSERT INTO gtestnn_parent2 VALUES (0); +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 (b GENERATED ALWAYS AS (a + 1) VIRTUAL) FOR VALUES IN (0); -- error +ERROR: column "b" of relation "gtestnn_child2" must have the same generation expression as in parent relation "gtestnn_parent2" +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 FOR VALUES IN (0, 1); +INSERT INTO gtestnn_parent2 VALUES (0); -- error +ERROR: null value in column "b" of relation "gtestnn_child2" violates not-null constraint +DETAIL: Failing row contains (0, virtual). +INSERT INTO gtestnn_parent2 VALUES (1); EXPLAIN (COSTS OFF) SELECT a FROM gtestnn_parent2 WHERE a NOT IN (SELECT b FROM gtestnn_parent2); QUERY PLAN diff --git a/src/test/regress/sql/generated_virtual.sql b/src/test/regress/sql/generated_virtual.sql index e62880f941a..e41423b07de 100644 --- a/src/test/regress/sql/generated_virtual.sql +++ b/src/test/regress/sql/generated_virtual.sql @@ -153,7 +153,8 @@ DROP TABLE gtest_normal, gtest_normal_child; CREATE TABLE gtestx (x int, b int DEFAULT 10) INHERITS (gtest1); -- error CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS IDENTITY) INHERITS (gtest1); -- error CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 22) STORED) INHERITS (gtest1); -- error -CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 22) VIRTUAL) INHERITS (gtest1); -- ok, overrides parent +CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 22) VIRTUAL) INHERITS (gtest1); -- error +CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL) INHERITS (gtest1); -- ok \d+ gtestx INSERT INTO gtestx (a, x) VALUES (11, 22); SELECT * FROM gtest1; @@ -177,8 +178,69 @@ DROP TABLE gtesty; CREATE TABLE gtesty (x int, b int GENERATED ALWAYS AS (x * 22) VIRTUAL); CREATE TABLE gtest1_y () INHERITS (gtest1, gtesty); -- error -CREATE TABLE gtest1_y (b int GENERATED ALWAYS AS (x + 1) VIRTUAL) INHERITS (gtest1, gtesty); -- ok -\d gtest1_y +CREATE TABLE gtest1_y (b int GENERATED ALWAYS AS (x + 1) VIRTUAL) INHERITS (gtest1, gtesty); -- error +DROP TABLE gtesty; + +-- adding a column merges it into an existing child column +CREATE TABLE gtesty (a int); +CREATE TABLE gtesty_1 (a int, b int GENERATED ALWAYS AS (a * 3) VIRTUAL) INHERITS (gtesty); +CREATE TABLE gtesty_2 (a int, b int) INHERITS (gtesty); +ALTER TABLE gtesty ADD COLUMN b int GENERATED ALWAYS AS (a * 2) VIRTUAL; -- error +DROP TABLE gtesty_1; +ALTER TABLE gtesty ADD COLUMN b int GENERATED ALWAYS AS (a * 2) VIRTUAL; -- error +DROP TABLE gtesty CASCADE; + +-- a child with two parents cannot have its expression changed through one +CREATE TABLE gtesty (a int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL); +CREATE TABLE gtestz (a int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL); +CREATE TABLE gtestyz () INHERITS (gtesty, gtestz); +ALTER TABLE gtesty ALTER COLUMN b SET EXPRESSION AS (a * 3); -- error +ALTER TABLE gtestyz ALTER COLUMN b SET EXPRESSION AS (a * 3); -- error, no hint +DROP TABLE gtesty, gtestz CASCADE; +-- also when the column is added by the same command +CREATE TABLE gtestq (a int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL); +CREATE TABLE gtestp (a int); +CREATE TABLE gtestpq () INHERITS (gtestp, gtestq); +ALTER TABLE gtestp ADD COLUMN b int GENERATED ALWAYS AS (a * 2) VIRTUAL, + ALTER COLUMN b SET EXPRESSION AS (a * 3); -- error +DROP TABLE gtestp, gtestq CASCADE; +-- Trees made by older minor versions can have a child whose expression +-- differs, which CREATE and ATTACH no longer allow. Emulate one by writing a +-- different expression directly into the child's pg_attrdef row. +CREATE TABLE gtestd (a int, b int GENERATED ALWAYS AS (a * 3) VIRTUAL); +CREATE TABLE gtestr (a int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL) PARTITION BY LIST (a); +CREATE TABLE gtestr1 PARTITION OF gtestr FOR VALUES IN (1); +UPDATE pg_attrdef SET adbin = (SELECT adbin FROM pg_attrdef WHERE adrelid = 'gtestd'::regclass) + WHERE adrelid = 'gtestr1'::regclass; +-- adding a column checks only the new column, not the old one +ALTER TABLE gtestr ADD COLUMN c int GENERATED ALWAYS AS (a + 1) VIRTUAL; +INSERT INTO gtestr VALUES (1); +SELECT * FROM gtestr; +-- but the new column is still checked against a child that already has it +CREATE TABLE gtests (a int); +CREATE TABLE gtests1 (a int, c int GENERATED ALWAYS AS (a * 5) VIRTUAL) INHERITS (gtests); +ALTER TABLE gtests ADD COLUMN c int GENERATED ALWAYS AS (a + 1) VIRTUAL; -- error +ALTER TABLE gtests ADD COLUMN c int GENERATED ALWAYS AS (a * 5) VIRTUAL; -- ok +DROP TABLE gtestd, gtestr, gtests CASCADE; +-- constants that differ can have the same text, depending on settings +CREATE TABLE gtestf (a float4, b float4 GENERATED ALWAYS AS (a * '0.1'::float4) VIRTUAL); +SET extra_float_digits = 0; +CREATE TABLE gtestf1 (b float4 GENERATED ALWAYS AS (a * '0.10000001'::float4) VIRTUAL) INHERITS (gtestf); -- error +RESET extra_float_digits; +DROP TABLE gtestf; +CREATE TABLE gtestz (a timestamptz, b boolean GENERATED ALWAYS AS (a < '2014-10-25 21:30:00+00'::timestamptz) VIRTUAL); +SET DateStyle = 'SQL, MDY'; +SET TimeZone = 'Europe/Moscow'; +CREATE TABLE gtestz1 (b boolean GENERATED ALWAYS AS (a < '2014-10-25 22:30:00+00'::timestamptz) VIRTUAL) INHERITS (gtestz); -- error +RESET DateStyle; +RESET TimeZone; +DROP TABLE gtestz; +-- a child written by hand still matches after the parent's type was changed +CREATE TABLE gtestt (a int, b varchar(5), c varchar(5) GENERATED ALWAYS AS (b) VIRTUAL) PARTITION BY LIST (a); +ALTER TABLE gtestt ALTER COLUMN c TYPE varchar(10); +CREATE TABLE gtestt1 (a int, b varchar(5), c varchar(10) GENERATED ALWAYS AS (b) VIRTUAL); +ALTER TABLE gtestt ATTACH PARTITION gtestt1 FOR VALUES IN (1); +DROP TABLE gtestt; -- test correct handling of GENERATED column that's only in child CREATE TABLE gtestp (f1 int); @@ -529,7 +591,10 @@ CREATE TABLE gtest_parent (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWA CREATE TABLE gtest_child PARTITION OF gtest_parent FOR VALUES FROM ('2016-07-01') TO ('2016-08-01'); -- inherits gen expr CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( - f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- overrides gen expr + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- error, must match parent +) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); +CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 2) VIRTUAL -- same as parent, ok ) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); CREATE TABLE gtest_child3 PARTITION OF gtest_parent ( f3 DEFAULT 42 -- error @@ -553,6 +618,15 @@ CREATE TABLE gtest_child3 (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWA ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); -- error DROP TABLE gtest_child3; CREATE TABLE gtest_child3 (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWAYS AS (f2 * 33) VIRTUAL); +ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); -- error +DROP TABLE gtest_child3; +-- an explicit cast is not the same as an implicit one +CREATE TABLE gtest_cast (a int, b numeric(10,0) GENERATED ALWAYS AS (a) VIRTUAL) PARTITION BY RANGE (a); +CREATE TABLE gtest_cast_1 (a int, b numeric(10,0) GENERATED ALWAYS AS (a::numeric(10,0)) VIRTUAL); +ALTER TABLE gtest_cast ATTACH PARTITION gtest_cast_1 FOR VALUES FROM (0) TO (10); -- error +DROP TABLE gtest_cast, gtest_cast_1; +-- different column order, so the parent's expression has to be mapped +CREATE TABLE gtest_child3 (f3 bigint GENERATED ALWAYS AS (f2 * 2) VIRTUAL, f2 bigint, f1 date NOT NULL); ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); \d gtest_child \d gtest_child2 @@ -562,28 +636,21 @@ INSERT INTO gtest_parent (f1, f2) VALUES ('2016-07-15', 2); INSERT INTO gtest_parent (f1, f2) VALUES ('2016-08-15', 3); SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; SELECT tableoid::regclass, * FROM gtest_child ORDER BY 1, 2, 3; -SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; -- uses child's generation expression, not parent's +SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; SELECT tableoid::regclass, * FROM gtest_child3 ORDER BY 1, 2, 3; UPDATE gtest_parent SET f1 = f1 + 60 WHERE f2 = 1; SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; --- alter only parent's and one child's generation expression -ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -\d gtest_parent -\d gtest_child -\d gtest_child2 -\d gtest_child3 -SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; - --- check constraint was validated based on each partitions's generation expression -ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 19); -- error -ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 66); -- error -ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 <> 33); -- error -ALTER TABLE gtest_parent ADD CONSTRAINT cc CHECK (f3 < 67); -- ok -ALTER TABLE gtest_parent DROP CONSTRAINT cc; +-- cannot alter only parent's or one partition's generation expression +ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -- error +ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -- error -- alter generation expression of parent and all its children altogether +ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); +SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; +ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 12); -- error +ALTER TABLE gtest_parent ADD CONSTRAINT cc CHECK (f3 < 13); -- ok +ALTER TABLE gtest_parent DROP CONSTRAINT cc; ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 2); \d gtest_parent \d gtest_child @@ -1012,11 +1079,13 @@ commit; drop table gtest_cursor; --- NOT NULL on a partitioned table's virtual column does not prove non-nullness, --- because a partition can have a different generation expression +-- a partition cannot have a different generation expression, which would let +-- the partitioned table's NOT NULL virtual column read as NULL CREATE TABLE gtestnn_parent2 (a int NOT NULL, b int GENERATED ALWAYS AS (nullif(a, 0)) VIRTUAL NOT NULL) PARTITION BY LIST (a); -CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 (b GENERATED ALWAYS AS (a + 1) VIRTUAL) FOR VALUES IN (0); -INSERT INTO gtestnn_parent2 VALUES (0); +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 (b GENERATED ALWAYS AS (a + 1) VIRTUAL) FOR VALUES IN (0); -- error +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 FOR VALUES IN (0, 1); +INSERT INTO gtestnn_parent2 VALUES (0); -- error +INSERT INTO gtestnn_parent2 VALUES (1); EXPLAIN (COSTS OFF) SELECT a FROM gtestnn_parent2 WHERE a NOT IN (SELECT b FROM gtestnn_parent2); SELECT a FROM gtestnn_parent2 WHERE a NOT IN (SELECT b FROM gtestnn_parent2); -- 2.37.1 (Apple Git-137.1)
v7-0001-Require-child-tables-to-use-the-parent-s-virtual-.patch (application/x-patch, 54.7K) download From c52c8da9f6823f0dfcd6200d76ec17644cf39222 Mon Sep 17 00:00:00 2001 From: shihao zhong <zhong950419@gmail.com> Date: Tue, 13 Oct 2026 23:22:52 -0400 Subject: [PATCH v7] Require child tables to use the parent's virtual generation expression MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Otherwise a NOT NULL or CHECK constraint can be wrong for rows read through the parent. Suggested-by: Álvaro Herrera <alvherre@kurilemu.de> Discussion: https://postgr.es/m/E1xFKs5-0000000116b-2Cge@gemulon.postgresql.org --- doc/src/sgml/ddl.sgml | 18 +- doc/src/sgml/ref/alter_table.sgml | 5 + src/backend/commands/tablecmds.c | 271 +++++++++++++++++- src/bin/pg_upgrade/check.c | 84 ++++++ .../perl/PostgreSQL/Test/AdjustUpgrade.pm | 10 + .../regress/expected/generated_virtual.out | 241 ++++++++++------ src/test/regress/sql/generated_virtual.sql | 117 ++++++-- 7 files changed, 619 insertions(+), 127 deletions(-) diff --git a/doc/src/sgml/ddl.sgml b/doc/src/sgml/ddl.sgml index d78d986756e..2f117a5940b 100644 --- a/doc/src/sgml/ddl.sgml +++ b/doc/src/sgml/ddl.sgml @@ -451,8 +451,10 @@ CREATE TABLE people ( <listitem> <para> If a parent column is a generated column, its child column must also - be a generated column of the same kind (stored or virtual); however, - the child column can have a different generation expression. + be a generated column of the same kind (stored or virtual). + A virtual generated child column must have the same generation + expression as the parent column. A stored generated child column + can have a different generation expression. </para> <para> @@ -478,8 +480,9 @@ CREATE TABLE people ( ... INHERITS</command>, then its <literal>GENERATED</literal> clause will automatically be copied from the parent. <command>ALTER TABLE ... INHERIT</command> will insist that parent and child columns - already match as to generation status, but it will not require their - generation expressions to match. + already match as to generation status, but it will only require + their generation expressions to match for virtual generated + columns. </para> </listitem> <listitem> @@ -490,8 +493,8 @@ CREATE TABLE people ( its <literal>GENERATED</literal> clause will automatically be copied from the parent. <command>ALTER TABLE ... ATTACH PARTITION</command> will insist that parent and child columns already match as to - generation status, but it will not require their generation - expressions to match. + generation status, but it will only require their generation + expressions to match for virtual generated columns. </para> </listitem> <listitem> @@ -499,7 +502,8 @@ CREATE TABLE people ( In case of multiple inheritance, if one parent column is a generated column, then all parent columns must be generated columns. If they do not all have the same generation expression, then the desired - expression for the child must be specified explicitly. + expression for the child must be specified explicitly. For virtual + generated columns, they must all have the same generation expression. </para> </listitem> </itemizedlist> diff --git a/doc/src/sgml/ref/alter_table.sgml b/doc/src/sgml/ref/alter_table.sgml index 0f9d698d170..d9192c44f16 100644 --- a/doc/src/sgml/ref/alter_table.sgml +++ b/doc/src/sgml/ref/alter_table.sgml @@ -276,6 +276,11 @@ WITH ( MODULUS <replaceable class="parameter">numeric_literal</replaceable>, REM Replacing the expression of a virtual generated column does not require a table rewrite, but if the column is used in a constraint, the table will be scanned to check that existing rows meet the constraint. + The expression of a virtual generated column cannot be changed for an + inherited column, or with <literal>ONLY</literal> for a table that has + child tables. It has to be changed for the whole inheritance tree, + from the top. If a child table also inherits the column from a parent + outside that tree, the expression cannot be changed while it does. </para> <para> diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 9786a5af58a..0aca2f4778a 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -383,6 +383,8 @@ static List *MergeCheckConstraint(List *constraints, const char *name, Node *exp static void MergeChildAttribute(List *inh_columns, int exist_attno, int newcol_attno, const ColumnDef *newdef); static ColumnDef *MergeInheritedAttribute(List *inh_columns, int exist_attno, const ColumnDef *newdef); static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispartition); +static void CheckVirtualGeneratedExprs(Relation childrel, Relation parentrel, + const char *colname); static void MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel); static void StoreCatalogInheritance(Oid relationId, List *supers, bool child_is_partition); @@ -553,6 +555,10 @@ static ObjectAddress ATExecDropIdentity(Relation rel, const char *colName, bool bool recurse, bool recursing); static ObjectAddress ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName, Node *newExpr, LOCKMODE lockmode); +static void ATPrepSetExpression(Relation rel, AlterTableCmd *cmd, bool recurse, + bool recursing, LOCKMODE lockmode); +static void CheckSetExpressionTree(Relation rel, const char *colName, + LOCKMODE lockmode); static void ATPrepDropExpression(Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode); static ObjectAddress ATExecDropExpression(Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode); static ObjectAddress ATExecSetStatistics(Relation rel, const char *colName, int16 colNum, @@ -1151,6 +1157,15 @@ DefineRelation(CreateStmt *stmt, char relkind, Oid ownerId, */ CommandCounterIncrement(); + /* Virtual generated columns must use the parents' expressions */ + foreach_oid(parentId, inheritOids) + { + Relation parent = table_open(parentId, NoLock); + + CheckVirtualGeneratedExprs(rel, parent, NULL); + table_close(parent, NoLock); + } + /* Process and store partition bound, if any. */ if (stmt->partbound) { @@ -3109,8 +3124,8 @@ MergeAttributes(List *columns, const List *supers, char relpersistence, * Check for conflicts related to generated columns. * * Same rules as above: generated-ness has to match the - * parent, but the contents of the generation expression - * can be different. + * parent. For virtual generated columns, + * CheckVirtualGeneratedExprs checks the expression later. */ if (coldef->generated) { @@ -3189,7 +3204,8 @@ MergeAttributes(List *columns, const List *supers, char relpersistence, (errcode(ERRCODE_INVALID_COLUMN_DEFINITION), errmsg("column \"%s\" inherits conflicting generation expressions", def->colname), - errhint("To resolve the conflict, specify a generation expression explicitly."))); + def->generated == ATTRIBUTE_GENERATED_STORED ? + errhint("To resolve the conflict, specify a generation expression explicitly.") : 0)); else ereport(ERROR, (errcode(ERRCODE_INVALID_COLUMN_DEFINITION), @@ -3397,10 +3413,11 @@ MergeChildAttribute(List *inh_columns, int exist_attno, int newcol_attno, const * * If the parent column is generated, the child column will be made a * generated column if it isn't already. If it is a generated column, - * we'll take its generation expression in preference to the parent's. We - * must check that the child column doesn't specify a default value or - * identity, which matches the rules for a single column in - * parse_utilcmd.c. + * we'll take its generation expression in preference to the parent's, + * though for a virtual generated column CheckVirtualGeneratedExprs later + * requires the two to match. We must check that the child column doesn't + * specify a default value or identity, which matches the rules for a + * single column in parse_utilcmd.c. * * Conversely, if the parent column is not generated, the child column * can't be either. (We used to allow that, but it results in being able @@ -5100,6 +5117,7 @@ ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd, case AT_SetExpression: /* ALTER COLUMN SET EXPRESSION */ ATSimplePermissions(cmd->subtype, rel, ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE); + ATPrepSetExpression(rel, cmd, recurse, recursing, lockmode); ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context); pass = AT_PASS_SET_EXPRESSION; break; @@ -7932,6 +7950,33 @@ ATExecAddColumn(List **wqueue, AlteredTableInfo *tab, Relation rel, get_collation_name(ccollid), get_collation_name(childatt->attcollation)))); + /* + * Child column must be virtual generated if and only if parent + * column is. Our caller checks the expression. + */ + if ((colDef->generated == ATTRIBUTE_GENERATED_VIRTUAL) != + (childatt->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)) + { + if (!childatt->attgenerated) + ereport(ERROR, + (errcode(ERRCODE_DATATYPE_MISMATCH), + errmsg("column \"%s\" in child table must be a generated column", + colDef->colname))); + else if (!colDef->generated) + ereport(ERROR, + (errcode(ERRCODE_DATATYPE_MISMATCH), + errmsg("column \"%s\" in child table must not be a generated column", + colDef->colname))); + else + ereport(ERROR, + (errcode(ERRCODE_DATATYPE_MISMATCH), + errmsg("column \"%s\" inherits from generated column of different kind", + colDef->colname), + errdetail("Parent column is %s, child column is %s.", + colDef->generated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL", + childatt->attgenerated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL"))); + } + /* Bump the existing child att's inhcount */ if (pg_add_s16_overflow(childatt->attinhcount, 1, &childatt->attinhcount)) @@ -8294,6 +8339,17 @@ ATExecAddColumn(List **wqueue, AlteredTableInfo *tab, Relation rel, &childcmd, recurse, true, lockmode, cur_pass, context); + /* + * The child may have had the column already. Only this column is new + * to the child, so don't compare the others: they may differ in a + * tree that was created before the check was added. + */ + if (colDef->generated == ATTRIBUTE_GENERATED_VIRTUAL) + { + CommandCounterIncrement(); + CheckVirtualGeneratedExprs(childrel, rel, colDef->colname); + } + table_close(childrel, NoLock); } @@ -9305,6 +9361,13 @@ ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName, if (attgenerated == ATTRIBUTE_GENERATED_VIRTUAL && attTup->attnotnull) tab->verify_new_notnull = true; + /* + * Check the whole tree from the table the column comes from, now that + * columns added by this command exist. + */ + if (attgenerated == ATTRIBUTE_GENERATED_VIRTUAL && attTup->attinhcount == 0) + CheckSetExpressionTree(rel, colName, lockmode); + /* * We need to prevent this because a change of expression could affect a * row filter and inject expressions that are not permitted in a row @@ -9409,6 +9472,105 @@ ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName, return address; } +/* + * ALTER TABLE ALTER COLUMN SET EXPRESSION + * + * A virtual generated column must have the same expression in a table and in + * all its parents and children, see CheckVirtualGeneratedExprs. So the + * expression can only be changed for a whole inheritance tree, from the top. + */ +static void +ATPrepSetExpression(Relation rel, AlterTableCmd *cmd, bool recurse, + bool recursing, LOCKMODE lockmode) +{ + HeapTuple tuple; + Form_pg_attribute attTup; + char attgenerated; + int16 attinhcount; + + if (recursing) + return; + + tuple = SearchSysCacheAttName(RelationGetRelid(rel), cmd->name); + if (!HeapTupleIsValid(tuple)) + return; /* error will be reported later */ + attTup = (Form_pg_attribute) GETSTRUCT(tuple); + attgenerated = attTup->attgenerated; + attinhcount = attTup->attinhcount; + ReleaseSysCache(tuple); + + if (attgenerated != ATTRIBUTE_GENERATED_VIRTUAL) + return; + + /* + * A partition has only one parent, so its column comes from a single + * top-level table. With plain inheritance it may come from several. + */ + if (attinhcount > 0) + ereport(ERROR, + (errcode(ERRCODE_INVALID_TABLE_DEFINITION), + errmsg("cannot alter inherited column \"%s\"", cmd->name), + rel->rd_rel->relispartition ? + errhint("Alter the generation expression of the top-level parent table instead.") : 0)); + + /* Partitions pending detach count here, as they still have the column */ + if (!recurse) + { + if (find_inheritance_children_extended(RelationGetRelid(rel), false, + NoLock, NULL, NULL) != NIL) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("ALTER TABLE / SET EXPRESSION must be applied to child tables too"))); + } +} + +/* + * Recursion skips partitions pending detach, so they would keep the old + * expression. Also, a child with another parent outside this tree would end + * up with a different expression than that parent. + */ +static void +CheckSetExpressionTree(Relation rel, const char *colName, LOCKMODE lockmode) +{ + HeapTuple tuple; + int16 attinhcount; + List *children; + List *numparents; + ListCell *lc; + ListCell *lc2; + + children = find_all_inheritors(RelationGetRelid(rel), lockmode, &numparents); + forboth(lc, children, lc2, numparents) + { + Oid childrelid = lfirst_oid(lc); + bool detached_exist = false; + + (void) find_inheritance_children_extended(childrelid, true, NoLock, + &detached_exist, NULL); + if (detached_exist) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), + errmsg("cannot alter generation expression of column \"%s\" while a partition of \"%s\" is pending detach", + colName, get_rel_name(childrelid)), + errhint("Use ALTER TABLE ... DETACH PARTITION ... FINALIZE to complete the pending detach operation."))); + + if (childrelid == RelationGetRelid(rel)) + continue; + + tuple = SearchSysCacheAttName(childrelid, colName); + if (!HeapTupleIsValid(tuple)) + continue; /* error will be reported later */ + attinhcount = ((Form_pg_attribute) GETSTRUCT(tuple))->attinhcount; + ReleaseSysCache(tuple); + + if (attinhcount > lfirst_int(lc2)) + ereport(ERROR, + (errcode(ERRCODE_INVALID_TABLE_DEFINITION), + errmsg("cannot alter inherited column \"%s\" of relation \"%s\"", + colName, get_rel_name(childrelid)))); + } +} + /* * ALTER TABLE ALTER COLUMN DROP EXPRESSION */ @@ -18859,7 +19021,8 @@ constraints_equivalent(HeapTuple a, HeapTuple b, TupleDesc tupleDesc) * partitioned tables it's a foot-gun. * * The data type must match exactly. If the parent column is NOT NULL then - * the child must be as well. Defaults are not compared, however. + * the child must be as well. Defaults are not compared, however, and neither + * are generation expressions, except for virtual generated columns. */ static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispartition) @@ -18980,6 +19143,98 @@ MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispart } table_close(attrrel, RowExclusiveLock); + + CheckVirtualGeneratedExprs(child_rel, parent_rel, NULL); +} + +/* + * CheckVirtualGeneratedExprs + * Check that each virtual generated column of a child table has the same + * generation expression as in the parent. If colname is not NULL, check + * only that column. + * + * Reading through the parent computes the parent's expression, while + * constraints on the child are checked with its own, so they must be the + * same. As in constraints_equivalent, we compare the deparsed expressions. + * That is what pg_dump restores, and unlike equal() it also catches an + * implicit cast in one and an explicit cast in the other, which + * ALTER COLUMN TYPE treats differently. The trees themselves can differ in + * ways that do not matter, such as the collation fields that + * ALTER COLUMN TYPE leaves unset. + * + * Deparse with the settings pg_dump uses, so that constants are printed + * without ambiguity whatever the session's settings are: a low + * extra_float_digits rounds float constants, and some DateStyles hide the + * UTC offset of a timestamptz constant. Constants of types such as regproc + * can still look the same when they are not. + */ +static void +CheckVirtualGeneratedExprs(Relation childrel, Relation parentrel, + const char *colname) +{ + TupleDesc parent_desc = RelationGetDescr(parentrel); + TupleDesc child_desc = RelationGetDescr(childrel); + List *parent_context; + List *child_context; + int save_nestlevel; + + if (parent_desc->constr == NULL || + !parent_desc->constr->has_generated_virtual) + return; + + save_nestlevel = NewGUCNestLevel(); + (void) set_config_option("extra_float_digits", "3", + PGC_USERSET, PGC_S_SESSION, + GUC_ACTION_SAVE, true, 0, false); + (void) set_config_option("datestyle", "ISO", + PGC_USERSET, PGC_S_SESSION, + GUC_ACTION_SAVE, true, 0, false); + (void) set_config_option("intervalstyle", "postgres", + PGC_USERSET, PGC_S_SESSION, + GUC_ACTION_SAVE, true, 0, false); + + parent_context = deparse_context_for(RelationGetRelationName(parentrel), + RelationGetRelid(parentrel)); + child_context = deparse_context_for(RelationGetRelationName(childrel), + RelationGetRelid(childrel)); + + for (int i = 0; i < parent_desc->natts; i++) + { + Form_pg_attribute parent_att = TupleDescAttr(parent_desc, i); + AttrNumber child_attno; + Node *parent_expr; + Node *child_expr; + + if (parent_att->attisdropped || + parent_att->attgenerated != ATTRIBUTE_GENERATED_VIRTUAL) + continue; + + if (colname != NULL && strcmp(colname, NameStr(parent_att->attname)) != 0) + continue; + + child_attno = get_attnum(RelationGetRelid(childrel), + NameStr(parent_att->attname)); + if (child_attno == InvalidAttrNumber) + elog(ERROR, "cache lookup failed for attribute \"%s\" of relation %u", + NameStr(parent_att->attname), RelationGetRelid(childrel)); + + parent_expr = TupleDescGetDefault(parent_desc, i + 1); + child_expr = TupleDescGetDefault(child_desc, child_attno); + if (parent_expr == NULL || child_expr == NULL) + elog(ERROR, "missing generation expression for column \"%s\"", + NameStr(parent_att->attname)); + + if (strcmp(deparse_expression(parent_expr, parent_context, false, false), + deparse_expression(child_expr, child_context, false, false)) != 0) + ereport(ERROR, + (errcode(ERRCODE_INVALID_COLUMN_DEFINITION), + errmsg("column \"%s\" of relation \"%s\" must have the same generation expression as in parent relation \"%s\"", + NameStr(parent_att->attname), + RelationGetRelationName(childrel), + RelationGetRelationName(parentrel)))); + } + + AtEOXact_GUC(false, save_nestlevel); } /* diff --git a/src/bin/pg_upgrade/check.c b/src/bin/pg_upgrade/check.c index 2d4aaf22a0f..a4b73828479 100644 --- a/src/bin/pg_upgrade/check.c +++ b/src/bin/pg_upgrade/check.c @@ -29,6 +29,7 @@ static void check_for_user_defined_postfix_ops(ClusterInfo *cluster); static void check_for_incompatible_polymorphics(ClusterInfo *cluster); static void check_for_tables_with_oids(ClusterInfo *cluster); static void check_for_not_null_inheritance(ClusterInfo *cluster); +static void check_for_virtual_generated_exprs(ClusterInfo *cluster); static void check_for_gist_inet_ops(ClusterInfo *cluster); static void check_for_new_tablespace_dir(void); static void check_for_user_defined_encoding_conversions(ClusterInfo *cluster); @@ -673,6 +674,15 @@ check_and_dump_old_cluster(void) if (GET_MAJOR_VERSION(old_cluster.major_version) <= 1800) check_for_not_null_inheritance(&old_cluster); + /* + * Virtual generated columns (new in PG 18) of a child table used to be + * allowed to have a different generation expression than the parent, but + * schema restore fails for them now. Verify there are none. + */ + if (GET_MAJOR_VERSION(old_cluster.major_version) >= 1800 && + GET_MAJOR_VERSION(old_cluster.major_version) <= 1900) + check_for_virtual_generated_exprs(&old_cluster); + /* * The btree_gist extension contains gist_inet_ops and gist_cidr_ops * opclasses that do not reliably give correct answers. We want to @@ -1733,6 +1743,80 @@ check_for_not_null_inheritance(ClusterInfo *cluster) check_ok(); } +/* + * check_for_virtual_generated_exprs() + * + * A virtual generated column of a child table, including a partition, must + * have the same generation expression as the parent. Check that the cluster + * to be upgraded has no child tables that differ, which older versions + * allowed. + */ +static void +check_for_virtual_generated_exprs(ClusterInfo *cluster) +{ + UpgradeTaskReport report; + UpgradeTask *task; + const char *query; + + prep_status("Checking for virtual generated column inconsistencies"); + + report.file = NULL; + snprintf(report.path, sizeof(report.path), "%s/%s", + log_opts.basedir, + "virtual_generated_columns.txt"); + + query = "SELECT DISTINCT nc.nspname, cc.relname, ac.attname " + "FROM pg_catalog.pg_class cc " + " JOIN pg_catalog.pg_namespace nc ON nc.oid = cc.relnamespace " + " JOIN pg_catalog.pg_inherits i ON i.inhrelid = cc.oid " + " JOIN pg_catalog.pg_attribute ac ON ac.attrelid = cc.oid " + " JOIN pg_catalog.pg_attribute ap ON ap.attrelid = i.inhparent " + " AND ap.attname = ac.attname " + " JOIN pg_catalog.pg_attrdef dc ON dc.adrelid = ac.attrelid " + " AND dc.adnum = ac.attnum " + " JOIN pg_catalog.pg_attrdef dp ON dp.adrelid = ap.attrelid " + " AND dp.adnum = ap.attnum " + "WHERE ac.attgenerated = 'v' " + " AND pg_catalog.pg_get_expr(dc.adbin, dc.adrelid) <> " + " pg_catalog.pg_get_expr(dp.adbin, dp.adrelid)"; + + task = upgrade_task_create(); + /* deparse constants the way the server's check does */ + upgrade_task_add_step(task, + "SELECT pg_catalog.set_config('extra_float_digits', '3', false), " + "pg_catalog.set_config('datestyle', 'ISO', false), " + "pg_catalog.set_config('intervalstyle', 'postgres', false)", + NULL, true, NULL); + /* the not-null check's callback reports the same columns */ + upgrade_task_add_step(task, query, + process_inconsistent_notnull, + true, &report); + upgrade_task_run(task, cluster); + upgrade_task_free(task); + + if (report.file) + { + fclose(report.file); + pg_log(PG_REPORT, "fatal"); + pg_fatal("Your installation contains child tables or partitions whose virtual\n" + "generated columns have a different generation expression than the\n" + "parent table. This is no longer allowed, so the upgrade would fail.\n" + "You can fix this by running\n" + " ALTER TABLE parent ALTER COLUMN column SET EXPRESSION AS (...);\n" + "on the top-level parent table of each column. In version 18 this\n" + "is not allowed if any table in that inheritance tree has CHECK\n" + "constraints, so drop them first and add them back afterwards. A\n" + "child table with more than one parent must first be removed from\n" + "all but one with NO INHERIT, and added back once all its parents\n" + "have the same expression. Rows that violate NOT NULL or CHECK with\n" + "the new expression must be fixed first. A list of the problem\n" + "columns is in the file:\n" + " %s", report.path); + } + else + check_ok(); +} + /* * Callback function for processing results of query for * check_for_gist_inet_ops()'s UpgradeTask. If the query returned any rows diff --git a/src/test/perl/PostgreSQL/Test/AdjustUpgrade.pm b/src/test/perl/PostgreSQL/Test/AdjustUpgrade.pm index 7bea8db8e61..7c3629338e6 100644 --- a/src/test/perl/PostgreSQL/Test/AdjustUpgrade.pm +++ b/src/test/perl/PostgreSQL/Test/AdjustUpgrade.pm @@ -156,6 +156,16 @@ sub adjust_database_contents } } + # Child tables whose virtual generated column has a different expression + # than the parent's cannot be upgraded to v20. + if ($old_version >= 18 && $old_version < 20) + { + _add_st( + $result, 'regression', + 'drop table if exists generated_virtual_tests.gtest1_y', + 'drop table if exists generated_virtual_tests.gtestx'); + } + # we removed these test-support functions in v18 if ($old_version < 18) { diff --git a/src/test/regress/expected/generated_virtual.out b/src/test/regress/expected/generated_virtual.out index b14e10fb5a0..17fee3f1eb8 100644 --- a/src/test/regress/expected/generated_virtual.out +++ b/src/test/regress/expected/generated_virtual.out @@ -357,15 +357,18 @@ CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 22) STORED) INHERITS NOTICE: merging column "b" with inherited definition ERROR: column "b" inherits from generated column of different kind DETAIL: Parent column is VIRTUAL, child column is STORED. -CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 22) VIRTUAL) INHERITS (gtest1); -- ok, overrides parent +CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 22) VIRTUAL) INHERITS (gtest1); -- error +NOTICE: merging column "b" with inherited definition +ERROR: column "b" of relation "gtestx" must have the same generation expression as in parent relation "gtest1" +CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL) INHERITS (gtest1); -- ok NOTICE: merging column "b" with inherited definition \d+ gtestx Table "generated_virtual_tests.gtestx" - Column | Type | Collation | Nullable | Default | Storage | Stats target | Description ---------+---------+-----------+----------+------------------------------+---------+--------------+------------- - a | integer | | not null | | plain | | - b | integer | | | generated always as (a * 22) | plain | | - x | integer | | | | plain | | + Column | Type | Collation | Nullable | Default | Storage | Stats target | Description +--------+---------+-----------+----------+-----------------------------+---------+--------------+------------- + a | integer | | not null | | plain | | + b | integer | | | generated always as (a * 2) | plain | | + x | integer | | | | plain | | Not-null constraints: "gtest1_a_not_null" NOT NULL "a" (inherited) Inherits: @@ -381,9 +384,9 @@ SELECT * FROM gtest1; (3 rows) SELECT * FROM gtestx; - a | b | x -----+-----+---- - 11 | 242 | 22 + a | b | x +----+----+---- + 11 | 22 | 22 (1 row) CREATE TABLE gtestxx_1 (a int NOT NULL, b int); @@ -408,22 +411,102 @@ CREATE TABLE gtesty (x int, b int GENERATED ALWAYS AS (x * 22) VIRTUAL); CREATE TABLE gtest1_y () INHERITS (gtest1, gtesty); -- error NOTICE: merging multiple inherited definitions of column "b" ERROR: column "b" inherits conflicting generation expressions -HINT: To resolve the conflict, specify a generation expression explicitly. -CREATE TABLE gtest1_y (b int GENERATED ALWAYS AS (x + 1) VIRTUAL) INHERITS (gtest1, gtesty); -- ok +CREATE TABLE gtest1_y (b int GENERATED ALWAYS AS (x + 1) VIRTUAL) INHERITS (gtest1, gtesty); -- error NOTICE: merging multiple inherited definitions of column "b" NOTICE: moving and merging column "b" with inherited definition DETAIL: User-specified column moved to the position of the inherited column. -\d gtest1_y - Table "generated_virtual_tests.gtest1_y" - Column | Type | Collation | Nullable | Default ---------+---------+-----------+----------+----------------------------- - a | integer | | not null | - b | integer | | | generated always as (x + 1) - x | integer | | | -Inherits: - gtest1 - gtesty +ERROR: column "b" of relation "gtest1_y" must have the same generation expression as in parent relation "gtest1" +DROP TABLE gtesty; +-- adding a column merges it into an existing child column +CREATE TABLE gtesty (a int); +CREATE TABLE gtesty_1 (a int, b int GENERATED ALWAYS AS (a * 3) VIRTUAL) INHERITS (gtesty); +NOTICE: merging column "a" with inherited definition +CREATE TABLE gtesty_2 (a int, b int) INHERITS (gtesty); +NOTICE: merging column "a" with inherited definition +ALTER TABLE gtesty ADD COLUMN b int GENERATED ALWAYS AS (a * 2) VIRTUAL; -- error +NOTICE: merging definition of column "b" for child "gtesty_1" +ERROR: column "b" of relation "gtesty_1" must have the same generation expression as in parent relation "gtesty" +DROP TABLE gtesty_1; +ALTER TABLE gtesty ADD COLUMN b int GENERATED ALWAYS AS (a * 2) VIRTUAL; -- error +ERROR: column "b" in child table must be a generated column +DROP TABLE gtesty CASCADE; +NOTICE: drop cascades to table gtesty_2 +-- a child with two parents cannot have its expression changed through one +CREATE TABLE gtesty (a int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL); +CREATE TABLE gtestz (a int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL); +CREATE TABLE gtestyz () INHERITS (gtesty, gtestz); +NOTICE: merging multiple inherited definitions of column "a" +NOTICE: merging multiple inherited definitions of column "b" +ALTER TABLE gtesty ALTER COLUMN b SET EXPRESSION AS (a * 3); -- error +ERROR: cannot alter inherited column "b" of relation "gtestyz" +ALTER TABLE gtestyz ALTER COLUMN b SET EXPRESSION AS (a * 3); -- error, no hint +ERROR: cannot alter inherited column "b" +DROP TABLE gtesty, gtestz CASCADE; +NOTICE: drop cascades to table gtestyz +-- also when the column is added by the same command +CREATE TABLE gtestq (a int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL); +CREATE TABLE gtestp (a int); +CREATE TABLE gtestpq () INHERITS (gtestp, gtestq); +NOTICE: merging multiple inherited definitions of column "a" +ALTER TABLE gtestp ADD COLUMN b int GENERATED ALWAYS AS (a * 2) VIRTUAL, + ALTER COLUMN b SET EXPRESSION AS (a * 3); -- error +NOTICE: merging definition of column "b" for child "gtestpq" +ERROR: cannot alter inherited column "b" of relation "gtestpq" +DROP TABLE gtestp, gtestq CASCADE; +NOTICE: drop cascades to table gtestpq +-- Trees made by older minor versions can have a child whose expression +-- differs, which CREATE and ATTACH no longer allow. Emulate one by writing a +-- different expression directly into the child's pg_attrdef row. +CREATE TABLE gtestd (a int, b int GENERATED ALWAYS AS (a * 3) VIRTUAL); +CREATE TABLE gtestr (a int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL) PARTITION BY LIST (a); +CREATE TABLE gtestr1 PARTITION OF gtestr FOR VALUES IN (1); +UPDATE pg_attrdef SET adbin = (SELECT adbin FROM pg_attrdef WHERE adrelid = 'gtestd'::regclass) + WHERE adrelid = 'gtestr1'::regclass; +-- adding a column checks only the new column, not the old one +ALTER TABLE gtestr ADD COLUMN c int GENERATED ALWAYS AS (a + 1) VIRTUAL; +INSERT INTO gtestr VALUES (1); +SELECT * FROM gtestr; + a | b | c +---+---+--- + 1 | 2 | 2 +(1 row) +-- but the new column is still checked against a child that already has it +CREATE TABLE gtests (a int); +CREATE TABLE gtests1 (a int, c int GENERATED ALWAYS AS (a * 5) VIRTUAL) INHERITS (gtests); +NOTICE: merging column "a" with inherited definition +ALTER TABLE gtests ADD COLUMN c int GENERATED ALWAYS AS (a + 1) VIRTUAL; -- error +NOTICE: merging definition of column "c" for child "gtests1" +ERROR: column "c" of relation "gtests1" must have the same generation expression as in parent relation "gtests" +ALTER TABLE gtests ADD COLUMN c int GENERATED ALWAYS AS (a * 5) VIRTUAL; -- ok +NOTICE: merging definition of column "c" for child "gtests1" +DROP TABLE gtestd, gtestr, gtests CASCADE; +NOTICE: drop cascades to table gtests1 +-- constants that differ can have the same text, depending on settings +CREATE TABLE gtestf (a float4, b float4 GENERATED ALWAYS AS (a * '0.1'::float4) VIRTUAL); +SET extra_float_digits = 0; +CREATE TABLE gtestf1 (b float4 GENERATED ALWAYS AS (a * '0.10000001'::float4) VIRTUAL) INHERITS (gtestf); -- error +NOTICE: moving and merging column "b" with inherited definition +DETAIL: User-specified column moved to the position of the inherited column. +ERROR: column "b" of relation "gtestf1" must have the same generation expression as in parent relation "gtestf" +RESET extra_float_digits; +DROP TABLE gtestf; +CREATE TABLE gtestz (a timestamptz, b boolean GENERATED ALWAYS AS (a < '2014-10-25 21:30:00+00'::timestamptz) VIRTUAL); +SET DateStyle = 'SQL, MDY'; +SET TimeZone = 'Europe/Moscow'; +CREATE TABLE gtestz1 (b boolean GENERATED ALWAYS AS (a < '2014-10-25 22:30:00+00'::timestamptz) VIRTUAL) INHERITS (gtestz); -- error +NOTICE: moving and merging column "b" with inherited definition +DETAIL: User-specified column moved to the position of the inherited column. +ERROR: column "b" of relation "gtestz1" must have the same generation expression as in parent relation "gtestz" +RESET DateStyle; +RESET TimeZone; +DROP TABLE gtestz; +-- a child written by hand still matches after the parent's type was changed +CREATE TABLE gtestt (a int, b varchar(5), c varchar(5) GENERATED ALWAYS AS (b) VIRTUAL) PARTITION BY LIST (a); +ALTER TABLE gtestt ALTER COLUMN c TYPE varchar(10); +CREATE TABLE gtestt1 (a int, b varchar(5), c varchar(10) GENERATED ALWAYS AS (b) VIRTUAL); +ALTER TABLE gtestt ATTACH PARTITION gtestt1 FOR VALUES IN (1); +DROP TABLE gtestt; -- test correct handling of GENERATED column that's only in child CREATE TABLE gtestp (f1 int); CREATE TABLE gtestc (f2 int GENERATED ALWAYS AS (f1+1) VIRTUAL) INHERITS(gtestp); @@ -912,7 +995,11 @@ CREATE TABLE gtest_parent (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWA CREATE TABLE gtest_child PARTITION OF gtest_parent FOR VALUES FROM ('2016-07-01') TO ('2016-08-01'); -- inherits gen expr CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( - f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- overrides gen expr + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- error, must match parent +) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); +ERROR: column "f3" of relation "gtest_child2" must have the same generation expression as in parent relation "gtest_parent" +CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 2) VIRTUAL -- same as parent, ok ) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); CREATE TABLE gtest_child3 PARTITION OF gtest_parent ( f3 DEFAULT 42 -- error @@ -946,6 +1033,17 @@ ERROR: column "f3" inherits from generated column of different kind DETAIL: Parent column is VIRTUAL, child column is STORED. DROP TABLE gtest_child3; CREATE TABLE gtest_child3 (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWAYS AS (f2 * 33) VIRTUAL); +ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); -- error +ERROR: column "f3" of relation "gtest_child3" must have the same generation expression as in parent relation "gtest_parent" +DROP TABLE gtest_child3; +-- an explicit cast is not the same as an implicit one +CREATE TABLE gtest_cast (a int, b numeric(10,0) GENERATED ALWAYS AS (a) VIRTUAL) PARTITION BY RANGE (a); +CREATE TABLE gtest_cast_1 (a int, b numeric(10,0) GENERATED ALWAYS AS (a::numeric(10,0)) VIRTUAL); +ALTER TABLE gtest_cast ATTACH PARTITION gtest_cast_1 FOR VALUES FROM (0) TO (10); -- error +ERROR: column "b" of relation "gtest_cast_1" must have the same generation expression as in parent relation "gtest_cast" +DROP TABLE gtest_cast, gtest_cast_1; +-- different column order, so the parent's expression has to be mapped +CREATE TABLE gtest_child3 (f3 bigint GENERATED ALWAYS AS (f2 * 2) VIRTUAL, f2 bigint, f1 date NOT NULL); ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); \d gtest_child Table "generated_virtual_tests.gtest_child" @@ -957,21 +1055,21 @@ ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09 Partition of: gtest_parent FOR VALUES FROM ('07-01-2016') TO ('08-01-2016') \d gtest_child2 - Table "generated_virtual_tests.gtest_child2" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- + Table "generated_virtual_tests.gtest_child2" + Column | Type | Collation | Nullable | Default +--------+--------+-----------+----------+------------------------------ f1 | date | | not null | f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 22) + f3 | bigint | | | generated always as (f2 * 2) Partition of: gtest_parent FOR VALUES FROM ('08-01-2016') TO ('09-01-2016') \d gtest_child3 - Table "generated_virtual_tests.gtest_child3" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | + Table "generated_virtual_tests.gtest_child3" + Column | Type | Collation | Nullable | Default +--------+--------+-----------+----------+------------------------------ + f3 | bigint | | | generated always as (f2 * 2) f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 33) + f1 | date | | not null | Partition of: gtest_parent FOR VALUES FROM ('09-01-2016') TO ('10-01-2016') INSERT INTO gtest_parent (f1, f2) VALUES ('2016-07-15', 1); @@ -992,14 +1090,14 @@ SELECT tableoid::regclass, * FROM gtest_child ORDER BY 1, 2, 3; gtest_child | 07-15-2016 | 2 | 4 (2 rows) -SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; -- uses child's generation expression, not parent's +SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; tableoid | f1 | f2 | f3 --------------+------------+----+---- - gtest_child2 | 08-15-2016 | 3 | 66 + gtest_child2 | 08-15-2016 | 3 | 6 (1 row) SELECT tableoid::regclass, * FROM gtest_child3 ORDER BY 1, 2, 3; - tableoid | f1 | f2 | f3 + tableoid | f3 | f2 | f1 ----------+----+----+---- (0 rows) @@ -1012,46 +1110,14 @@ SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; gtest_child3 | 09-13-2016 | 1 | 2 (3 rows) --- alter only parent's and one child's generation expression -ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -\d gtest_parent - Partitioned table "generated_virtual_tests.gtest_parent" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------ - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 4) -Partition key: RANGE (f1) -Number of partitions: 3 (Use \d+ to list them.) - -\d gtest_child - Table "generated_virtual_tests.gtest_child" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 10) -Partition of: gtest_parent FOR VALUES FROM ('07-01-2016') TO ('08-01-2016') - -\d gtest_child2 - Table "generated_virtual_tests.gtest_child2" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 22) -Partition of: gtest_parent FOR VALUES FROM ('08-01-2016') TO ('09-01-2016') - -\d gtest_child3 - Table "generated_virtual_tests.gtest_child3" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 33) -Partition of: gtest_parent FOR VALUES FROM ('09-01-2016') TO ('10-01-2016') - +-- cannot alter only parent's or one partition's generation expression +ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -- error +ERROR: ALTER TABLE / SET EXPRESSION must be applied to child tables too +ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -- error +ERROR: cannot alter inherited column "f3" +HINT: Alter the generation expression of the top-level parent table instead. +-- alter generation expression of parent and all its children altogether +ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; tableoid | f1 | f2 | f3 --------------+------------+----+---- @@ -1060,16 +1126,10 @@ SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; gtest_child3 | 09-13-2016 | 1 | 4 (3 rows) --- check constraint was validated based on each partitions's generation expression -ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 19); -- error -ERROR: check constraint "cc1" of relation "gtest_child" is violated by some row -ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 66); -- error +ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 12); -- error ERROR: check constraint "cc1" of relation "gtest_child2" is violated by some row -ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 <> 33); -- error -ERROR: check constraint "cc1" of relation "gtest_child3" is violated by some row -ALTER TABLE gtest_parent ADD CONSTRAINT cc CHECK (f3 < 67); -- ok +ALTER TABLE gtest_parent ADD CONSTRAINT cc CHECK (f3 < 13); -- ok ALTER TABLE gtest_parent DROP CONSTRAINT cc; --- alter generation expression of parent and all its children altogether ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 2); \d gtest_parent Partitioned table "generated_virtual_tests.gtest_parent" @@ -1103,9 +1163,9 @@ Partition of: gtest_parent FOR VALUES FROM ('08-01-2016') TO ('09-01-2016') Table "generated_virtual_tests.gtest_child3" Column | Type | Collation | Nullable | Default --------+--------+-----------+----------+------------------------------ - f1 | date | | not null | - f2 | bigint | | | f3 | bigint | | | generated always as (f2 * 2) + f2 | bigint | | | + f1 | date | | not null | Partition of: gtest_parent FOR VALUES FROM ('09-01-2016') TO ('10-01-2016') SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; @@ -1894,11 +1954,16 @@ select * from gtest_cursor order by id; commit; drop table gtest_cursor; --- NOT NULL on a partitioned table's virtual column does not prove non-nullness, --- because a partition can have a different generation expression +-- a partition cannot have a different generation expression, which would let +-- the partitioned table's NOT NULL virtual column read as NULL CREATE TABLE gtestnn_parent2 (a int NOT NULL, b int GENERATED ALWAYS AS (nullif(a, 0)) VIRTUAL NOT NULL) PARTITION BY LIST (a); -CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 (b GENERATED ALWAYS AS (a + 1) VIRTUAL) FOR VALUES IN (0); -INSERT INTO gtestnn_parent2 VALUES (0); +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 (b GENERATED ALWAYS AS (a + 1) VIRTUAL) FOR VALUES IN (0); -- error +ERROR: column "b" of relation "gtestnn_child2" must have the same generation expression as in parent relation "gtestnn_parent2" +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 FOR VALUES IN (0, 1); +INSERT INTO gtestnn_parent2 VALUES (0); -- error +ERROR: null value in column "b" of relation "gtestnn_child2" violates not-null constraint +DETAIL: Failing row contains (0, virtual). +INSERT INTO gtestnn_parent2 VALUES (1); EXPLAIN (COSTS OFF) SELECT a FROM gtestnn_parent2 WHERE a NOT IN (SELECT b FROM gtestnn_parent2); QUERY PLAN diff --git a/src/test/regress/sql/generated_virtual.sql b/src/test/regress/sql/generated_virtual.sql index e62880f941a..e41423b07de 100644 --- a/src/test/regress/sql/generated_virtual.sql +++ b/src/test/regress/sql/generated_virtual.sql @@ -153,7 +153,8 @@ DROP TABLE gtest_normal, gtest_normal_child; CREATE TABLE gtestx (x int, b int DEFAULT 10) INHERITS (gtest1); -- error CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS IDENTITY) INHERITS (gtest1); -- error CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 22) STORED) INHERITS (gtest1); -- error -CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 22) VIRTUAL) INHERITS (gtest1); -- ok, overrides parent +CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 22) VIRTUAL) INHERITS (gtest1); -- error +CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL) INHERITS (gtest1); -- ok \d+ gtestx INSERT INTO gtestx (a, x) VALUES (11, 22); SELECT * FROM gtest1; @@ -177,8 +178,69 @@ DROP TABLE gtesty; CREATE TABLE gtesty (x int, b int GENERATED ALWAYS AS (x * 22) VIRTUAL); CREATE TABLE gtest1_y () INHERITS (gtest1, gtesty); -- error -CREATE TABLE gtest1_y (b int GENERATED ALWAYS AS (x + 1) VIRTUAL) INHERITS (gtest1, gtesty); -- ok -\d gtest1_y +CREATE TABLE gtest1_y (b int GENERATED ALWAYS AS (x + 1) VIRTUAL) INHERITS (gtest1, gtesty); -- error +DROP TABLE gtesty; + +-- adding a column merges it into an existing child column +CREATE TABLE gtesty (a int); +CREATE TABLE gtesty_1 (a int, b int GENERATED ALWAYS AS (a * 3) VIRTUAL) INHERITS (gtesty); +CREATE TABLE gtesty_2 (a int, b int) INHERITS (gtesty); +ALTER TABLE gtesty ADD COLUMN b int GENERATED ALWAYS AS (a * 2) VIRTUAL; -- error +DROP TABLE gtesty_1; +ALTER TABLE gtesty ADD COLUMN b int GENERATED ALWAYS AS (a * 2) VIRTUAL; -- error +DROP TABLE gtesty CASCADE; + +-- a child with two parents cannot have its expression changed through one +CREATE TABLE gtesty (a int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL); +CREATE TABLE gtestz (a int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL); +CREATE TABLE gtestyz () INHERITS (gtesty, gtestz); +ALTER TABLE gtesty ALTER COLUMN b SET EXPRESSION AS (a * 3); -- error +ALTER TABLE gtestyz ALTER COLUMN b SET EXPRESSION AS (a * 3); -- error, no hint +DROP TABLE gtesty, gtestz CASCADE; +-- also when the column is added by the same command +CREATE TABLE gtestq (a int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL); +CREATE TABLE gtestp (a int); +CREATE TABLE gtestpq () INHERITS (gtestp, gtestq); +ALTER TABLE gtestp ADD COLUMN b int GENERATED ALWAYS AS (a * 2) VIRTUAL, + ALTER COLUMN b SET EXPRESSION AS (a * 3); -- error +DROP TABLE gtestp, gtestq CASCADE; +-- Trees made by older minor versions can have a child whose expression +-- differs, which CREATE and ATTACH no longer allow. Emulate one by writing a +-- different expression directly into the child's pg_attrdef row. +CREATE TABLE gtestd (a int, b int GENERATED ALWAYS AS (a * 3) VIRTUAL); +CREATE TABLE gtestr (a int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL) PARTITION BY LIST (a); +CREATE TABLE gtestr1 PARTITION OF gtestr FOR VALUES IN (1); +UPDATE pg_attrdef SET adbin = (SELECT adbin FROM pg_attrdef WHERE adrelid = 'gtestd'::regclass) + WHERE adrelid = 'gtestr1'::regclass; +-- adding a column checks only the new column, not the old one +ALTER TABLE gtestr ADD COLUMN c int GENERATED ALWAYS AS (a + 1) VIRTUAL; +INSERT INTO gtestr VALUES (1); +SELECT * FROM gtestr; +-- but the new column is still checked against a child that already has it +CREATE TABLE gtests (a int); +CREATE TABLE gtests1 (a int, c int GENERATED ALWAYS AS (a * 5) VIRTUAL) INHERITS (gtests); +ALTER TABLE gtests ADD COLUMN c int GENERATED ALWAYS AS (a + 1) VIRTUAL; -- error +ALTER TABLE gtests ADD COLUMN c int GENERATED ALWAYS AS (a * 5) VIRTUAL; -- ok +DROP TABLE gtestd, gtestr, gtests CASCADE; +-- constants that differ can have the same text, depending on settings +CREATE TABLE gtestf (a float4, b float4 GENERATED ALWAYS AS (a * '0.1'::float4) VIRTUAL); +SET extra_float_digits = 0; +CREATE TABLE gtestf1 (b float4 GENERATED ALWAYS AS (a * '0.10000001'::float4) VIRTUAL) INHERITS (gtestf); -- error +RESET extra_float_digits; +DROP TABLE gtestf; +CREATE TABLE gtestz (a timestamptz, b boolean GENERATED ALWAYS AS (a < '2014-10-25 21:30:00+00'::timestamptz) VIRTUAL); +SET DateStyle = 'SQL, MDY'; +SET TimeZone = 'Europe/Moscow'; +CREATE TABLE gtestz1 (b boolean GENERATED ALWAYS AS (a < '2014-10-25 22:30:00+00'::timestamptz) VIRTUAL) INHERITS (gtestz); -- error +RESET DateStyle; +RESET TimeZone; +DROP TABLE gtestz; +-- a child written by hand still matches after the parent's type was changed +CREATE TABLE gtestt (a int, b varchar(5), c varchar(5) GENERATED ALWAYS AS (b) VIRTUAL) PARTITION BY LIST (a); +ALTER TABLE gtestt ALTER COLUMN c TYPE varchar(10); +CREATE TABLE gtestt1 (a int, b varchar(5), c varchar(10) GENERATED ALWAYS AS (b) VIRTUAL); +ALTER TABLE gtestt ATTACH PARTITION gtestt1 FOR VALUES IN (1); +DROP TABLE gtestt; -- test correct handling of GENERATED column that's only in child CREATE TABLE gtestp (f1 int); @@ -529,7 +591,10 @@ CREATE TABLE gtest_parent (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWA CREATE TABLE gtest_child PARTITION OF gtest_parent FOR VALUES FROM ('2016-07-01') TO ('2016-08-01'); -- inherits gen expr CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( - f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- overrides gen expr + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- error, must match parent +) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); +CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 2) VIRTUAL -- same as parent, ok ) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); CREATE TABLE gtest_child3 PARTITION OF gtest_parent ( f3 DEFAULT 42 -- error @@ -553,6 +618,15 @@ CREATE TABLE gtest_child3 (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWA ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); -- error DROP TABLE gtest_child3; CREATE TABLE gtest_child3 (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWAYS AS (f2 * 33) VIRTUAL); +ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); -- error +DROP TABLE gtest_child3; +-- an explicit cast is not the same as an implicit one +CREATE TABLE gtest_cast (a int, b numeric(10,0) GENERATED ALWAYS AS (a) VIRTUAL) PARTITION BY RANGE (a); +CREATE TABLE gtest_cast_1 (a int, b numeric(10,0) GENERATED ALWAYS AS (a::numeric(10,0)) VIRTUAL); +ALTER TABLE gtest_cast ATTACH PARTITION gtest_cast_1 FOR VALUES FROM (0) TO (10); -- error +DROP TABLE gtest_cast, gtest_cast_1; +-- different column order, so the parent's expression has to be mapped +CREATE TABLE gtest_child3 (f3 bigint GENERATED ALWAYS AS (f2 * 2) VIRTUAL, f2 bigint, f1 date NOT NULL); ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); \d gtest_child \d gtest_child2 @@ -562,28 +636,21 @@ INSERT INTO gtest_parent (f1, f2) VALUES ('2016-07-15', 2); INSERT INTO gtest_parent (f1, f2) VALUES ('2016-08-15', 3); SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; SELECT tableoid::regclass, * FROM gtest_child ORDER BY 1, 2, 3; -SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; -- uses child's generation expression, not parent's +SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; SELECT tableoid::regclass, * FROM gtest_child3 ORDER BY 1, 2, 3; UPDATE gtest_parent SET f1 = f1 + 60 WHERE f2 = 1; SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; --- alter only parent's and one child's generation expression -ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -\d gtest_parent -\d gtest_child -\d gtest_child2 -\d gtest_child3 -SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; - --- check constraint was validated based on each partitions's generation expression -ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 19); -- error -ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 66); -- error -ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 <> 33); -- error -ALTER TABLE gtest_parent ADD CONSTRAINT cc CHECK (f3 < 67); -- ok -ALTER TABLE gtest_parent DROP CONSTRAINT cc; +-- cannot alter only parent's or one partition's generation expression +ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -- error +ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -- error -- alter generation expression of parent and all its children altogether +ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); +SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; +ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 12); -- error +ALTER TABLE gtest_parent ADD CONSTRAINT cc CHECK (f3 < 13); -- ok +ALTER TABLE gtest_parent DROP CONSTRAINT cc; ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 2); \d gtest_parent \d gtest_child @@ -1012,11 +1079,13 @@ commit; drop table gtest_cursor; --- NOT NULL on a partitioned table's virtual column does not prove non-nullness, --- because a partition can have a different generation expression +-- a partition cannot have a different generation expression, which would let +-- the partitioned table's NOT NULL virtual column read as NULL CREATE TABLE gtestnn_parent2 (a int NOT NULL, b int GENERATED ALWAYS AS (nullif(a, 0)) VIRTUAL NOT NULL) PARTITION BY LIST (a); -CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 (b GENERATED ALWAYS AS (a + 1) VIRTUAL) FOR VALUES IN (0); -INSERT INTO gtestnn_parent2 VALUES (0); +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 (b GENERATED ALWAYS AS (a + 1) VIRTUAL) FOR VALUES IN (0); -- error +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 FOR VALUES IN (0, 1); +INSERT INTO gtestnn_parent2 VALUES (0); -- error +INSERT INTO gtestnn_parent2 VALUES (1); EXPLAIN (COSTS OFF) SELECT a FROM gtestnn_parent2 WHERE a NOT IN (SELECT b FROM gtestnn_parent2); SELECT a FROM gtestnn_parent2 WHERE a NOT IN (SELECT b FROM gtestnn_parent2); -- 2.37.1 (Apple Git-137.1)
nocfbot-v7-REL_18-0001-Require-child-tables-to-use-the-parent-s-virtual-.patch (application/x-patch, 47.5K) download From c93e3e965df6018ce5815d61caf5cd344825ac9e Mon Sep 17 00:00:00 2001 From: shihao zhong <zhong950419@gmail.com> Date: Tue, 13 Oct 2026 23:22:52 -0400 Subject: [PATCH v7] Require child tables to use the parent's virtual generation expression MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Otherwise a NOT NULL or CHECK constraint can be wrong for rows read through the parent. Suggested-by: Álvaro Herrera <alvherre@kurilemu.de> Discussion: https://postgr.es/m/E1xFKs5-0000000116b-2Cge@gemulon.postgresql.org --- doc/src/sgml/ddl.sgml | 18 +- doc/src/sgml/ref/alter_table.sgml | 5 + src/backend/commands/tablecmds.c | 271 +++++++++++++++++- .../regress/expected/generated_virtual.out | 239 ++++++++++----- src/test/regress/sql/generated_virtual.sql | 110 ++++++- 5 files changed, 539 insertions(+), 104 deletions(-) diff --git a/doc/src/sgml/ddl.sgml b/doc/src/sgml/ddl.sgml index ddd7096f6b2..ad416a2bdf7 100644 --- a/doc/src/sgml/ddl.sgml +++ b/doc/src/sgml/ddl.sgml @@ -451,8 +451,10 @@ CREATE TABLE people ( <listitem> <para> If a parent column is a generated column, its child column must also - be a generated column of the same kind (stored or virtual); however, - the child column can have a different generation expression. + be a generated column of the same kind (stored or virtual). + A virtual generated child column must have the same generation + expression as the parent column. A stored generated child column + can have a different generation expression. </para> <para> @@ -478,8 +480,9 @@ CREATE TABLE people ( ... INHERITS</command>, then its <literal>GENERATED</literal> clause will automatically be copied from the parent. <command>ALTER TABLE ... INHERIT</command> will insist that parent and child columns - already match as to generation status, but it will not require their - generation expressions to match. + already match as to generation status, but it will only require + their generation expressions to match for virtual generated + columns. </para> </listitem> <listitem> @@ -490,8 +493,8 @@ CREATE TABLE people ( its <literal>GENERATED</literal> clause will automatically be copied from the parent. <command>ALTER TABLE ... ATTACH PARTITION</command> will insist that parent and child columns already match as to - generation status, but it will not require their generation - expressions to match. + generation status, but it will only require their generation + expressions to match for virtual generated columns. </para> </listitem> <listitem> @@ -499,7 +502,8 @@ CREATE TABLE people ( In case of multiple inheritance, if one parent column is a generated column, then all parent columns must be generated columns. If they do not all have the same generation expression, then the desired - expression for the child must be specified explicitly. + expression for the child must be specified explicitly. For virtual + generated columns, they must all have the same generation expression. </para> </listitem> </itemizedlist> diff --git a/doc/src/sgml/ref/alter_table.sgml b/doc/src/sgml/ref/alter_table.sgml index 31f2d91418b..c9cdfed96b7 100644 --- a/doc/src/sgml/ref/alter_table.sgml +++ b/doc/src/sgml/ref/alter_table.sgml @@ -272,6 +272,11 @@ WITH ( MODULUS <replaceable class="parameter">numeric_literal</replaceable>, REM This form replaces the expression of a generated column. Existing data in a stored generated column is rewritten and all the future changes will apply the new generation expression. + The expression of a virtual generated column cannot be changed for an + inherited column, or with <literal>ONLY</literal> for a table that has + child tables. It has to be changed for the whole inheritance tree, + from the top. If a child table also inherits the column from a parent + outside that tree, the expression cannot be changed while it does. </para> <para> diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 5059909833e..78e2defec2a 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -378,6 +378,8 @@ static List *MergeCheckConstraint(List *constraints, const char *name, Node *exp static void MergeChildAttribute(List *inh_columns, int exist_attno, int newcol_attno, const ColumnDef *newdef); static ColumnDef *MergeInheritedAttribute(List *inh_columns, int exist_attno, const ColumnDef *newdef); static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispartition); +static void CheckVirtualGeneratedExprs(Relation childrel, Relation parentrel, + const char *colname); static void MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel); static void StoreCatalogInheritance(Oid relationId, List *supers, bool child_is_partition); @@ -522,6 +524,10 @@ static ObjectAddress ATExecDropIdentity(Relation rel, const char *colName, bool bool recurse, bool recursing); static ObjectAddress ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName, Node *newExpr, LOCKMODE lockmode); +static void ATPrepSetExpression(Relation rel, AlterTableCmd *cmd, bool recurse, + bool recursing, LOCKMODE lockmode); +static void CheckSetExpressionTree(Relation rel, const char *colName, + LOCKMODE lockmode); static void ATPrepDropExpression(Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode); static ObjectAddress ATExecDropExpression(Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode); static ObjectAddress ATExecSetStatistics(Relation rel, const char *colName, int16 colNum, @@ -1118,6 +1124,15 @@ DefineRelation(CreateStmt *stmt, char relkind, Oid ownerId, */ CommandCounterIncrement(); + /* Virtual generated columns must use the parents' expressions */ + foreach_oid(parentId, inheritOids) + { + Relation parent = table_open(parentId, NoLock); + + CheckVirtualGeneratedExprs(rel, parent, NULL); + table_close(parent, NoLock); + } + /* Process and store partition bound, if any. */ if (stmt->partbound) { @@ -3058,8 +3073,8 @@ MergeAttributes(List *columns, const List *supers, char relpersistence, * Check for conflicts related to generated columns. * * Same rules as above: generated-ness has to match the - * parent, but the contents of the generation expression - * can be different. + * parent. For virtual generated columns, + * CheckVirtualGeneratedExprs checks the expression later. */ if (coldef->generated) { @@ -3138,7 +3153,8 @@ MergeAttributes(List *columns, const List *supers, char relpersistence, (errcode(ERRCODE_INVALID_COLUMN_DEFINITION), errmsg("column \"%s\" inherits conflicting generation expressions", def->colname), - errhint("To resolve the conflict, specify a generation expression explicitly."))); + def->generated == ATTRIBUTE_GENERATED_STORED ? + errhint("To resolve the conflict, specify a generation expression explicitly.") : 0)); else ereport(ERROR, (errcode(ERRCODE_INVALID_COLUMN_DEFINITION), @@ -3346,10 +3362,11 @@ MergeChildAttribute(List *inh_columns, int exist_attno, int newcol_attno, const * * If the parent column is generated, the child column will be made a * generated column if it isn't already. If it is a generated column, - * we'll take its generation expression in preference to the parent's. We - * must check that the child column doesn't specify a default value or - * identity, which matches the rules for a single column in - * parse_utilcmd.c. + * we'll take its generation expression in preference to the parent's, + * though for a virtual generated column CheckVirtualGeneratedExprs later + * requires the two to match. We must check that the child column doesn't + * specify a default value or identity, which matches the rules for a + * single column in parse_utilcmd.c. * * Conversely, if the parent column is not generated, the child column * can't be either. (We used to allow that, but it results in being able @@ -5036,6 +5053,7 @@ ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd, case AT_SetExpression: /* ALTER COLUMN SET EXPRESSION */ ATSimplePermissions(cmd->subtype, rel, ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE); + ATPrepSetExpression(rel, cmd, recurse, recursing, lockmode); ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context); pass = AT_PASS_SET_EXPRESSION; break; @@ -7310,6 +7328,33 @@ ATExecAddColumn(List **wqueue, AlteredTableInfo *tab, Relation rel, get_collation_name(ccollid), get_collation_name(childatt->attcollation)))); + /* + * Child column must be virtual generated if and only if parent + * column is. Our caller checks the expression. + */ + if ((colDef->generated == ATTRIBUTE_GENERATED_VIRTUAL) != + (childatt->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)) + { + if (!childatt->attgenerated) + ereport(ERROR, + (errcode(ERRCODE_DATATYPE_MISMATCH), + errmsg("column \"%s\" in child table must be a generated column", + colDef->colname))); + else if (!colDef->generated) + ereport(ERROR, + (errcode(ERRCODE_DATATYPE_MISMATCH), + errmsg("column \"%s\" in child table must not be a generated column", + colDef->colname))); + else + ereport(ERROR, + (errcode(ERRCODE_DATATYPE_MISMATCH), + errmsg("column \"%s\" inherits from generated column of different kind", + colDef->colname), + errdetail("Parent column is %s, child column is %s.", + colDef->generated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL", + childatt->attgenerated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL"))); + } + /* Bump the existing child att's inhcount */ if (pg_add_s16_overflow(childatt->attinhcount, 1, &childatt->attinhcount)) @@ -7653,6 +7698,17 @@ ATExecAddColumn(List **wqueue, AlteredTableInfo *tab, Relation rel, &childcmd, recurse, true, lockmode, cur_pass, context); + /* + * The child may have had the column already. Only this column is new + * to the child, so don't compare the others: they may differ in a + * tree that was created before the check was added. + */ + if (colDef->generated == ATTRIBUTE_GENERATED_VIRTUAL) + { + CommandCounterIncrement(); + CheckVirtualGeneratedExprs(childrel, rel, colDef->colname); + } + table_close(childrel, NoLock); } @@ -8676,6 +8732,13 @@ ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName, if (attgenerated == ATTRIBUTE_GENERATED_VIRTUAL && attTup->attnotnull) tab->verify_new_notnull = true; + /* + * Check the whole tree from the table the column comes from, now that + * columns added by this command exist. + */ + if (attgenerated == ATTRIBUTE_GENERATED_VIRTUAL && attTup->attinhcount == 0) + CheckSetExpressionTree(rel, colName, lockmode); + /* * We need to prevent this because a change of expression could affect a * row filter and inject expressions that are not permitted in a row @@ -8774,6 +8837,105 @@ ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName, return address; } +/* + * ALTER TABLE ALTER COLUMN SET EXPRESSION + * + * A virtual generated column must have the same expression in a table and in + * all its parents and children, see CheckVirtualGeneratedExprs. So the + * expression can only be changed for a whole inheritance tree, from the top. + */ +static void +ATPrepSetExpression(Relation rel, AlterTableCmd *cmd, bool recurse, + bool recursing, LOCKMODE lockmode) +{ + HeapTuple tuple; + Form_pg_attribute attTup; + char attgenerated; + int16 attinhcount; + + if (recursing) + return; + + tuple = SearchSysCacheAttName(RelationGetRelid(rel), cmd->name); + if (!HeapTupleIsValid(tuple)) + return; /* error will be reported later */ + attTup = (Form_pg_attribute) GETSTRUCT(tuple); + attgenerated = attTup->attgenerated; + attinhcount = attTup->attinhcount; + ReleaseSysCache(tuple); + + if (attgenerated != ATTRIBUTE_GENERATED_VIRTUAL) + return; + + /* + * A partition has only one parent, so its column comes from a single + * top-level table. With plain inheritance it may come from several. + */ + if (attinhcount > 0) + ereport(ERROR, + (errcode(ERRCODE_INVALID_TABLE_DEFINITION), + errmsg("cannot alter inherited column \"%s\"", cmd->name), + rel->rd_rel->relispartition ? + errhint("Alter the generation expression of the top-level parent table instead.") : 0)); + + /* Partitions pending detach count here, as they still have the column */ + if (!recurse) + { + if (find_inheritance_children_extended(RelationGetRelid(rel), false, + NoLock, NULL, NULL) != NIL) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("ALTER TABLE / SET EXPRESSION must be applied to child tables too"))); + } +} + +/* + * Recursion skips partitions pending detach, so they would keep the old + * expression. Also, a child with another parent outside this tree would end + * up with a different expression than that parent. + */ +static void +CheckSetExpressionTree(Relation rel, const char *colName, LOCKMODE lockmode) +{ + HeapTuple tuple; + int16 attinhcount; + List *children; + List *numparents; + ListCell *lc; + ListCell *lc2; + + children = find_all_inheritors(RelationGetRelid(rel), lockmode, &numparents); + forboth(lc, children, lc2, numparents) + { + Oid childrelid = lfirst_oid(lc); + bool detached_exist = false; + + (void) find_inheritance_children_extended(childrelid, true, NoLock, + &detached_exist, NULL); + if (detached_exist) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), + errmsg("cannot alter generation expression of column \"%s\" while a partition of \"%s\" is pending detach", + colName, get_rel_name(childrelid)), + errhint("Use ALTER TABLE ... DETACH PARTITION ... FINALIZE to complete the pending detach operation."))); + + if (childrelid == RelationGetRelid(rel)) + continue; + + tuple = SearchSysCacheAttName(childrelid, colName); + if (!HeapTupleIsValid(tuple)) + continue; /* error will be reported later */ + attinhcount = ((Form_pg_attribute) GETSTRUCT(tuple))->attinhcount; + ReleaseSysCache(tuple); + + if (attinhcount > lfirst_int(lc2)) + ereport(ERROR, + (errcode(ERRCODE_INVALID_TABLE_DEFINITION), + errmsg("cannot alter inherited column \"%s\" of relation \"%s\"", + colName, get_rel_name(childrelid)))); + } +} + /* * ALTER TABLE ALTER COLUMN DROP EXPRESSION */ @@ -17551,7 +17713,8 @@ constraints_equivalent(HeapTuple a, HeapTuple b, TupleDesc tupleDesc) * partitioned tables it's a foot-gun. * * The data type must match exactly. If the parent column is NOT NULL then - * the child must be as well. Defaults are not compared, however. + * the child must be as well. Defaults are not compared, however, and neither + * are generation expressions, except for virtual generated columns. */ static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispartition) @@ -17672,6 +17835,98 @@ MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispart } table_close(attrrel, RowExclusiveLock); + + CheckVirtualGeneratedExprs(child_rel, parent_rel, NULL); +} + +/* + * CheckVirtualGeneratedExprs + * Check that each virtual generated column of a child table has the same + * generation expression as in the parent. If colname is not NULL, check + * only that column. + * + * Reading through the parent computes the parent's expression, while + * constraints on the child are checked with its own, so they must be the + * same. As in constraints_equivalent, we compare the deparsed expressions. + * That is what pg_dump restores, and unlike equal() it also catches an + * implicit cast in one and an explicit cast in the other, which + * ALTER COLUMN TYPE treats differently. The trees themselves can differ in + * ways that do not matter, such as the collation fields that + * ALTER COLUMN TYPE leaves unset. + * + * Deparse with the settings pg_dump uses, so that constants are printed + * without ambiguity whatever the session's settings are: a low + * extra_float_digits rounds float constants, and some DateStyles hide the + * UTC offset of a timestamptz constant. Constants of types such as regproc + * can still look the same when they are not. + */ +static void +CheckVirtualGeneratedExprs(Relation childrel, Relation parentrel, + const char *colname) +{ + TupleDesc parent_desc = RelationGetDescr(parentrel); + TupleDesc child_desc = RelationGetDescr(childrel); + List *parent_context; + List *child_context; + int save_nestlevel; + + if (parent_desc->constr == NULL || + !parent_desc->constr->has_generated_virtual) + return; + + save_nestlevel = NewGUCNestLevel(); + (void) set_config_option("extra_float_digits", "3", + PGC_USERSET, PGC_S_SESSION, + GUC_ACTION_SAVE, true, 0, false); + (void) set_config_option("datestyle", "ISO", + PGC_USERSET, PGC_S_SESSION, + GUC_ACTION_SAVE, true, 0, false); + (void) set_config_option("intervalstyle", "postgres", + PGC_USERSET, PGC_S_SESSION, + GUC_ACTION_SAVE, true, 0, false); + + parent_context = deparse_context_for(RelationGetRelationName(parentrel), + RelationGetRelid(parentrel)); + child_context = deparse_context_for(RelationGetRelationName(childrel), + RelationGetRelid(childrel)); + + for (int i = 0; i < parent_desc->natts; i++) + { + Form_pg_attribute parent_att = TupleDescAttr(parent_desc, i); + AttrNumber child_attno; + Node *parent_expr; + Node *child_expr; + + if (parent_att->attisdropped || + parent_att->attgenerated != ATTRIBUTE_GENERATED_VIRTUAL) + continue; + + if (colname != NULL && strcmp(colname, NameStr(parent_att->attname)) != 0) + continue; + + child_attno = get_attnum(RelationGetRelid(childrel), + NameStr(parent_att->attname)); + if (child_attno == InvalidAttrNumber) + elog(ERROR, "cache lookup failed for attribute \"%s\" of relation %u", + NameStr(parent_att->attname), RelationGetRelid(childrel)); + + parent_expr = TupleDescGetDefault(parent_desc, i + 1); + child_expr = TupleDescGetDefault(child_desc, child_attno); + if (parent_expr == NULL || child_expr == NULL) + elog(ERROR, "missing generation expression for column \"%s\"", + NameStr(parent_att->attname)); + + if (strcmp(deparse_expression(parent_expr, parent_context, false, false), + deparse_expression(child_expr, child_context, false, false)) != 0) + ereport(ERROR, + (errcode(ERRCODE_INVALID_COLUMN_DEFINITION), + errmsg("column \"%s\" of relation \"%s\" must have the same generation expression as in parent relation \"%s\"", + NameStr(parent_att->attname), + RelationGetRelationName(childrel), + RelationGetRelationName(parentrel)))); + } + + AtEOXact_GUC(false, save_nestlevel); } /* diff --git a/src/test/regress/expected/generated_virtual.out b/src/test/regress/expected/generated_virtual.out index 03698488907..0b0f56f1c05 100644 --- a/src/test/regress/expected/generated_virtual.out +++ b/src/test/regress/expected/generated_virtual.out @@ -356,15 +356,18 @@ CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 22) STORED) INHERITS NOTICE: merging column "b" with inherited definition ERROR: column "b" inherits from generated column of different kind DETAIL: Parent column is VIRTUAL, child column is STORED. -CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 22) VIRTUAL) INHERITS (gtest1); -- ok, overrides parent +CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 22) VIRTUAL) INHERITS (gtest1); -- error +NOTICE: merging column "b" with inherited definition +ERROR: column "b" of relation "gtestx" must have the same generation expression as in parent relation "gtest1" +CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL) INHERITS (gtest1); -- ok NOTICE: merging column "b" with inherited definition \d+ gtestx Table "generated_virtual_tests.gtestx" - Column | Type | Collation | Nullable | Default | Storage | Stats target | Description ---------+---------+-----------+----------+------------------------------+---------+--------------+------------- - a | integer | | not null | | plain | | - b | integer | | | generated always as (a * 22) | plain | | - x | integer | | | | plain | | + Column | Type | Collation | Nullable | Default | Storage | Stats target | Description +--------+---------+-----------+----------+-----------------------------+---------+--------------+------------- + a | integer | | not null | | plain | | + b | integer | | | generated always as (a * 2) | plain | | + x | integer | | | | plain | | Not-null constraints: "gtest1_a_not_null" NOT NULL "a" (inherited) Inherits: gtest1 @@ -379,9 +382,9 @@ SELECT * FROM gtest1; (3 rows) SELECT * FROM gtestx; - a | b | x -----+-----+---- - 11 | 242 | 22 + a | b | x +----+----+---- + 11 | 22 | 22 (1 row) CREATE TABLE gtestxx_1 (a int NOT NULL, b int); @@ -406,21 +409,102 @@ CREATE TABLE gtesty (x int, b int GENERATED ALWAYS AS (x * 22) VIRTUAL); CREATE TABLE gtest1_y () INHERITS (gtest1, gtesty); -- error NOTICE: merging multiple inherited definitions of column "b" ERROR: column "b" inherits conflicting generation expressions -HINT: To resolve the conflict, specify a generation expression explicitly. -CREATE TABLE gtest1_y (b int GENERATED ALWAYS AS (x + 1) VIRTUAL) INHERITS (gtest1, gtesty); -- ok +CREATE TABLE gtest1_y (b int GENERATED ALWAYS AS (x + 1) VIRTUAL) INHERITS (gtest1, gtesty); -- error NOTICE: merging multiple inherited definitions of column "b" NOTICE: moving and merging column "b" with inherited definition DETAIL: User-specified column moved to the position of the inherited column. -\d gtest1_y - Table "generated_virtual_tests.gtest1_y" - Column | Type | Collation | Nullable | Default ---------+---------+-----------+----------+----------------------------- - a | integer | | not null | - b | integer | | | generated always as (x + 1) - x | integer | | | -Inherits: gtest1, - gtesty +ERROR: column "b" of relation "gtest1_y" must have the same generation expression as in parent relation "gtest1" +DROP TABLE gtesty; +-- adding a column merges it into an existing child column +CREATE TABLE gtesty (a int); +CREATE TABLE gtesty_1 (a int, b int GENERATED ALWAYS AS (a * 3) VIRTUAL) INHERITS (gtesty); +NOTICE: merging column "a" with inherited definition +CREATE TABLE gtesty_2 (a int, b int) INHERITS (gtesty); +NOTICE: merging column "a" with inherited definition +ALTER TABLE gtesty ADD COLUMN b int GENERATED ALWAYS AS (a * 2) VIRTUAL; -- error +NOTICE: merging definition of column "b" for child "gtesty_1" +ERROR: column "b" of relation "gtesty_1" must have the same generation expression as in parent relation "gtesty" +DROP TABLE gtesty_1; +ALTER TABLE gtesty ADD COLUMN b int GENERATED ALWAYS AS (a * 2) VIRTUAL; -- error +ERROR: column "b" in child table must be a generated column +DROP TABLE gtesty CASCADE; +NOTICE: drop cascades to table gtesty_2 +-- a child with two parents cannot have its expression changed through one +CREATE TABLE gtesty (a int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL); +CREATE TABLE gtestz (a int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL); +CREATE TABLE gtestyz () INHERITS (gtesty, gtestz); +NOTICE: merging multiple inherited definitions of column "a" +NOTICE: merging multiple inherited definitions of column "b" +ALTER TABLE gtesty ALTER COLUMN b SET EXPRESSION AS (a * 3); -- error +ERROR: cannot alter inherited column "b" of relation "gtestyz" +ALTER TABLE gtestyz ALTER COLUMN b SET EXPRESSION AS (a * 3); -- error, no hint +ERROR: cannot alter inherited column "b" +DROP TABLE gtesty, gtestz CASCADE; +NOTICE: drop cascades to table gtestyz +-- also when the column is added by the same command +CREATE TABLE gtestq (a int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL); +CREATE TABLE gtestp (a int); +CREATE TABLE gtestpq () INHERITS (gtestp, gtestq); +NOTICE: merging multiple inherited definitions of column "a" +ALTER TABLE gtestp ADD COLUMN b int GENERATED ALWAYS AS (a * 2) VIRTUAL, + ALTER COLUMN b SET EXPRESSION AS (a * 3); -- error +NOTICE: merging definition of column "b" for child "gtestpq" +ERROR: cannot alter inherited column "b" of relation "gtestpq" +DROP TABLE gtestp, gtestq CASCADE; +NOTICE: drop cascades to table gtestpq +-- Trees made by older minor versions can have a child whose expression +-- differs, which CREATE and ATTACH no longer allow. Emulate one by writing a +-- different expression directly into the child's pg_attrdef row. +CREATE TABLE gtestd (a int, b int GENERATED ALWAYS AS (a * 3) VIRTUAL); +CREATE TABLE gtestr (a int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL) PARTITION BY LIST (a); +CREATE TABLE gtestr1 PARTITION OF gtestr FOR VALUES IN (1); +UPDATE pg_attrdef SET adbin = (SELECT adbin FROM pg_attrdef WHERE adrelid = 'gtestd'::regclass) + WHERE adrelid = 'gtestr1'::regclass; +-- adding a column checks only the new column, not the old one +ALTER TABLE gtestr ADD COLUMN c int GENERATED ALWAYS AS (a + 1) VIRTUAL; +INSERT INTO gtestr VALUES (1); +SELECT * FROM gtestr; + a | b | c +---+---+--- + 1 | 2 | 2 +(1 row) +-- but the new column is still checked against a child that already has it +CREATE TABLE gtests (a int); +CREATE TABLE gtests1 (a int, c int GENERATED ALWAYS AS (a * 5) VIRTUAL) INHERITS (gtests); +NOTICE: merging column "a" with inherited definition +ALTER TABLE gtests ADD COLUMN c int GENERATED ALWAYS AS (a + 1) VIRTUAL; -- error +NOTICE: merging definition of column "c" for child "gtests1" +ERROR: column "c" of relation "gtests1" must have the same generation expression as in parent relation "gtests" +ALTER TABLE gtests ADD COLUMN c int GENERATED ALWAYS AS (a * 5) VIRTUAL; -- ok +NOTICE: merging definition of column "c" for child "gtests1" +DROP TABLE gtestd, gtestr, gtests CASCADE; +NOTICE: drop cascades to table gtests1 +-- constants that differ can have the same text, depending on settings +CREATE TABLE gtestf (a float4, b float4 GENERATED ALWAYS AS (a * '0.1'::float4) VIRTUAL); +SET extra_float_digits = 0; +CREATE TABLE gtestf1 (b float4 GENERATED ALWAYS AS (a * '0.10000001'::float4) VIRTUAL) INHERITS (gtestf); -- error +NOTICE: moving and merging column "b" with inherited definition +DETAIL: User-specified column moved to the position of the inherited column. +ERROR: column "b" of relation "gtestf1" must have the same generation expression as in parent relation "gtestf" +RESET extra_float_digits; +DROP TABLE gtestf; +CREATE TABLE gtestz (a timestamptz, b boolean GENERATED ALWAYS AS (a < '2014-10-25 21:30:00+00'::timestamptz) VIRTUAL); +SET DateStyle = 'SQL, MDY'; +SET TimeZone = 'Europe/Moscow'; +CREATE TABLE gtestz1 (b boolean GENERATED ALWAYS AS (a < '2014-10-25 22:30:00+00'::timestamptz) VIRTUAL) INHERITS (gtestz); -- error +NOTICE: moving and merging column "b" with inherited definition +DETAIL: User-specified column moved to the position of the inherited column. +ERROR: column "b" of relation "gtestz1" must have the same generation expression as in parent relation "gtestz" +RESET DateStyle; +RESET TimeZone; +DROP TABLE gtestz; +-- a child written by hand still matches after the parent's type was changed +CREATE TABLE gtestt (a int, b varchar(5), c varchar(5) GENERATED ALWAYS AS (b) VIRTUAL) PARTITION BY LIST (a); +ALTER TABLE gtestt ALTER COLUMN c TYPE varchar(10); +CREATE TABLE gtestt1 (a int, b varchar(5), c varchar(10) GENERATED ALWAYS AS (b) VIRTUAL); +ALTER TABLE gtestt ATTACH PARTITION gtestt1 FOR VALUES IN (1); +DROP TABLE gtestt; -- test correct handling of GENERATED column that's only in child CREATE TABLE gtestp (f1 int); CREATE TABLE gtestc (f2 int GENERATED ALWAYS AS (f1+1) VIRTUAL) INHERITS(gtestp); @@ -882,7 +966,11 @@ CREATE TABLE gtest_parent (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWA CREATE TABLE gtest_child PARTITION OF gtest_parent FOR VALUES FROM ('2016-07-01') TO ('2016-08-01'); -- inherits gen expr CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( - f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- overrides gen expr + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- error, must match parent +) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); +ERROR: column "f3" of relation "gtest_child2" must have the same generation expression as in parent relation "gtest_parent" +CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 2) VIRTUAL -- same as parent, ok ) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); CREATE TABLE gtest_child3 PARTITION OF gtest_parent ( f3 DEFAULT 42 -- error @@ -916,6 +1004,17 @@ ERROR: column "f3" inherits from generated column of different kind DETAIL: Parent column is VIRTUAL, child column is STORED. DROP TABLE gtest_child3; CREATE TABLE gtest_child3 (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWAYS AS (f2 * 33) VIRTUAL); +ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); -- error +ERROR: column "f3" of relation "gtest_child3" must have the same generation expression as in parent relation "gtest_parent" +DROP TABLE gtest_child3; +-- an explicit cast is not the same as an implicit one +CREATE TABLE gtest_cast (a int, b numeric(10,0) GENERATED ALWAYS AS (a) VIRTUAL) PARTITION BY RANGE (a); +CREATE TABLE gtest_cast_1 (a int, b numeric(10,0) GENERATED ALWAYS AS (a::numeric(10,0)) VIRTUAL); +ALTER TABLE gtest_cast ATTACH PARTITION gtest_cast_1 FOR VALUES FROM (0) TO (10); -- error +ERROR: column "b" of relation "gtest_cast_1" must have the same generation expression as in parent relation "gtest_cast" +DROP TABLE gtest_cast, gtest_cast_1; +-- different column order, so the parent's expression has to be mapped +CREATE TABLE gtest_child3 (f3 bigint GENERATED ALWAYS AS (f2 * 2) VIRTUAL, f2 bigint, f1 date NOT NULL); ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); \d gtest_child Table "generated_virtual_tests.gtest_child" @@ -927,21 +1026,21 @@ ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09 Partition of: gtest_parent FOR VALUES FROM ('07-01-2016') TO ('08-01-2016') \d gtest_child2 - Table "generated_virtual_tests.gtest_child2" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- + Table "generated_virtual_tests.gtest_child2" + Column | Type | Collation | Nullable | Default +--------+--------+-----------+----------+------------------------------ f1 | date | | not null | f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 22) + f3 | bigint | | | generated always as (f2 * 2) Partition of: gtest_parent FOR VALUES FROM ('08-01-2016') TO ('09-01-2016') \d gtest_child3 - Table "generated_virtual_tests.gtest_child3" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | + Table "generated_virtual_tests.gtest_child3" + Column | Type | Collation | Nullable | Default +--------+--------+-----------+----------+------------------------------ + f3 | bigint | | | generated always as (f2 * 2) f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 33) + f1 | date | | not null | Partition of: gtest_parent FOR VALUES FROM ('09-01-2016') TO ('10-01-2016') INSERT INTO gtest_parent (f1, f2) VALUES ('2016-07-15', 1); @@ -962,14 +1061,14 @@ SELECT tableoid::regclass, * FROM gtest_child ORDER BY 1, 2, 3; gtest_child | 07-15-2016 | 2 | 4 (2 rows) -SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; -- uses child's generation expression, not parent's +SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; tableoid | f1 | f2 | f3 --------------+------------+----+---- - gtest_child2 | 08-15-2016 | 3 | 66 + gtest_child2 | 08-15-2016 | 3 | 6 (1 row) SELECT tableoid::regclass, * FROM gtest_child3 ORDER BY 1, 2, 3; - tableoid | f1 | f2 | f3 + tableoid | f3 | f2 | f1 ----------+----+----+---- (0 rows) @@ -982,46 +1081,14 @@ SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; gtest_child3 | 09-13-2016 | 1 | 2 (3 rows) --- alter only parent's and one child's generation expression -ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -\d gtest_parent - Partitioned table "generated_virtual_tests.gtest_parent" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------ - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 4) -Partition key: RANGE (f1) -Number of partitions: 3 (Use \d+ to list them.) - -\d gtest_child - Table "generated_virtual_tests.gtest_child" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 10) -Partition of: gtest_parent FOR VALUES FROM ('07-01-2016') TO ('08-01-2016') - -\d gtest_child2 - Table "generated_virtual_tests.gtest_child2" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 22) -Partition of: gtest_parent FOR VALUES FROM ('08-01-2016') TO ('09-01-2016') - -\d gtest_child3 - Table "generated_virtual_tests.gtest_child3" - Column | Type | Collation | Nullable | Default ---------+--------+-----------+----------+------------------------------- - f1 | date | | not null | - f2 | bigint | | | - f3 | bigint | | | generated always as (f2 * 33) -Partition of: gtest_parent FOR VALUES FROM ('09-01-2016') TO ('10-01-2016') - +-- cannot alter only parent's or one partition's generation expression +ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -- error +ERROR: ALTER TABLE / SET EXPRESSION must be applied to child tables too +ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -- error +ERROR: cannot alter inherited column "f3" +HINT: Alter the generation expression of the top-level parent table instead. +-- alter generation expression of parent and all its children altogether +ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; tableoid | f1 | f2 | f3 --------------+------------+----+---- @@ -1030,7 +1097,10 @@ SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; gtest_child3 | 09-13-2016 | 1 | 4 (3 rows) --- alter generation expression of parent and all its children altogether +ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 12); -- error +ERROR: check constraint "cc1" of relation "gtest_child2" is violated by some row +ALTER TABLE gtest_parent ADD CONSTRAINT cc CHECK (f3 < 13); -- ok +ALTER TABLE gtest_parent DROP CONSTRAINT cc; ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 2); \d gtest_parent Partitioned table "generated_virtual_tests.gtest_parent" @@ -1064,9 +1134,9 @@ Partition of: gtest_parent FOR VALUES FROM ('08-01-2016') TO ('09-01-2016') Table "generated_virtual_tests.gtest_child3" Column | Type | Collation | Nullable | Default --------+--------+-----------+----------+------------------------------ - f1 | date | | not null | - f2 | bigint | | | f3 | bigint | | | generated always as (f2 * 2) + f2 | bigint | | | + f1 | date | | not null | Partition of: gtest_parent FOR VALUES FROM ('09-01-2016') TO ('10-01-2016') SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; @@ -1812,3 +1882,20 @@ select * from gtest_cursor order by id; commit; drop table gtest_cursor; +-- a partition cannot have a different generation expression, which would let +-- the partitioned table's NOT NULL virtual column read as NULL +CREATE TABLE gtestnn_parent2 (a int NOT NULL, b int GENERATED ALWAYS AS (nullif(a, 0)) VIRTUAL NOT NULL) PARTITION BY LIST (a); +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 (b GENERATED ALWAYS AS (a + 1) VIRTUAL) FOR VALUES IN (0); -- error +ERROR: column "b" of relation "gtestnn_child2" must have the same generation expression as in parent relation "gtestnn_parent2" +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 FOR VALUES IN (0, 1); +INSERT INTO gtestnn_parent2 VALUES (0); -- error +ERROR: null value in column "b" of relation "gtestnn_child2" violates not-null constraint +DETAIL: Failing row contains (0, virtual). +INSERT INTO gtestnn_parent2 VALUES (1); +SELECT a, b FROM gtestnn_parent2; + a | b +---+--- + 1 | 1 +(1 row) + +DROP TABLE gtestnn_parent2; diff --git a/src/test/regress/sql/generated_virtual.sql b/src/test/regress/sql/generated_virtual.sql index b1b92b2ced5..2d3862043d6 100644 --- a/src/test/regress/sql/generated_virtual.sql +++ b/src/test/regress/sql/generated_virtual.sql @@ -153,7 +153,8 @@ DROP TABLE gtest_normal, gtest_normal_child; CREATE TABLE gtestx (x int, b int DEFAULT 10) INHERITS (gtest1); -- error CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS IDENTITY) INHERITS (gtest1); -- error CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 22) STORED) INHERITS (gtest1); -- error -CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 22) VIRTUAL) INHERITS (gtest1); -- ok, overrides parent +CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 22) VIRTUAL) INHERITS (gtest1); -- error +CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL) INHERITS (gtest1); -- ok \d+ gtestx INSERT INTO gtestx (a, x) VALUES (11, 22); SELECT * FROM gtest1; @@ -177,8 +178,69 @@ DROP TABLE gtesty; CREATE TABLE gtesty (x int, b int GENERATED ALWAYS AS (x * 22) VIRTUAL); CREATE TABLE gtest1_y () INHERITS (gtest1, gtesty); -- error -CREATE TABLE gtest1_y (b int GENERATED ALWAYS AS (x + 1) VIRTUAL) INHERITS (gtest1, gtesty); -- ok -\d gtest1_y +CREATE TABLE gtest1_y (b int GENERATED ALWAYS AS (x + 1) VIRTUAL) INHERITS (gtest1, gtesty); -- error +DROP TABLE gtesty; + +-- adding a column merges it into an existing child column +CREATE TABLE gtesty (a int); +CREATE TABLE gtesty_1 (a int, b int GENERATED ALWAYS AS (a * 3) VIRTUAL) INHERITS (gtesty); +CREATE TABLE gtesty_2 (a int, b int) INHERITS (gtesty); +ALTER TABLE gtesty ADD COLUMN b int GENERATED ALWAYS AS (a * 2) VIRTUAL; -- error +DROP TABLE gtesty_1; +ALTER TABLE gtesty ADD COLUMN b int GENERATED ALWAYS AS (a * 2) VIRTUAL; -- error +DROP TABLE gtesty CASCADE; + +-- a child with two parents cannot have its expression changed through one +CREATE TABLE gtesty (a int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL); +CREATE TABLE gtestz (a int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL); +CREATE TABLE gtestyz () INHERITS (gtesty, gtestz); +ALTER TABLE gtesty ALTER COLUMN b SET EXPRESSION AS (a * 3); -- error +ALTER TABLE gtestyz ALTER COLUMN b SET EXPRESSION AS (a * 3); -- error, no hint +DROP TABLE gtesty, gtestz CASCADE; +-- also when the column is added by the same command +CREATE TABLE gtestq (a int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL); +CREATE TABLE gtestp (a int); +CREATE TABLE gtestpq () INHERITS (gtestp, gtestq); +ALTER TABLE gtestp ADD COLUMN b int GENERATED ALWAYS AS (a * 2) VIRTUAL, + ALTER COLUMN b SET EXPRESSION AS (a * 3); -- error +DROP TABLE gtestp, gtestq CASCADE; +-- Trees made by older minor versions can have a child whose expression +-- differs, which CREATE and ATTACH no longer allow. Emulate one by writing a +-- different expression directly into the child's pg_attrdef row. +CREATE TABLE gtestd (a int, b int GENERATED ALWAYS AS (a * 3) VIRTUAL); +CREATE TABLE gtestr (a int, b int GENERATED ALWAYS AS (a * 2) VIRTUAL) PARTITION BY LIST (a); +CREATE TABLE gtestr1 PARTITION OF gtestr FOR VALUES IN (1); +UPDATE pg_attrdef SET adbin = (SELECT adbin FROM pg_attrdef WHERE adrelid = 'gtestd'::regclass) + WHERE adrelid = 'gtestr1'::regclass; +-- adding a column checks only the new column, not the old one +ALTER TABLE gtestr ADD COLUMN c int GENERATED ALWAYS AS (a + 1) VIRTUAL; +INSERT INTO gtestr VALUES (1); +SELECT * FROM gtestr; +-- but the new column is still checked against a child that already has it +CREATE TABLE gtests (a int); +CREATE TABLE gtests1 (a int, c int GENERATED ALWAYS AS (a * 5) VIRTUAL) INHERITS (gtests); +ALTER TABLE gtests ADD COLUMN c int GENERATED ALWAYS AS (a + 1) VIRTUAL; -- error +ALTER TABLE gtests ADD COLUMN c int GENERATED ALWAYS AS (a * 5) VIRTUAL; -- ok +DROP TABLE gtestd, gtestr, gtests CASCADE; +-- constants that differ can have the same text, depending on settings +CREATE TABLE gtestf (a float4, b float4 GENERATED ALWAYS AS (a * '0.1'::float4) VIRTUAL); +SET extra_float_digits = 0; +CREATE TABLE gtestf1 (b float4 GENERATED ALWAYS AS (a * '0.10000001'::float4) VIRTUAL) INHERITS (gtestf); -- error +RESET extra_float_digits; +DROP TABLE gtestf; +CREATE TABLE gtestz (a timestamptz, b boolean GENERATED ALWAYS AS (a < '2014-10-25 21:30:00+00'::timestamptz) VIRTUAL); +SET DateStyle = 'SQL, MDY'; +SET TimeZone = 'Europe/Moscow'; +CREATE TABLE gtestz1 (b boolean GENERATED ALWAYS AS (a < '2014-10-25 22:30:00+00'::timestamptz) VIRTUAL) INHERITS (gtestz); -- error +RESET DateStyle; +RESET TimeZone; +DROP TABLE gtestz; +-- a child written by hand still matches after the parent's type was changed +CREATE TABLE gtestt (a int, b varchar(5), c varchar(5) GENERATED ALWAYS AS (b) VIRTUAL) PARTITION BY LIST (a); +ALTER TABLE gtestt ALTER COLUMN c TYPE varchar(10); +CREATE TABLE gtestt1 (a int, b varchar(5), c varchar(10) GENERATED ALWAYS AS (b) VIRTUAL); +ALTER TABLE gtestt ATTACH PARTITION gtestt1 FOR VALUES IN (1); +DROP TABLE gtestt; -- test correct handling of GENERATED column that's only in child CREATE TABLE gtestp (f1 int); @@ -514,7 +576,10 @@ CREATE TABLE gtest_parent (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWA CREATE TABLE gtest_child PARTITION OF gtest_parent FOR VALUES FROM ('2016-07-01') TO ('2016-08-01'); -- inherits gen expr CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( - f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- overrides gen expr + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 22) VIRTUAL -- error, must match parent +) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); +CREATE TABLE gtest_child2 PARTITION OF gtest_parent ( + f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 2) VIRTUAL -- same as parent, ok ) FOR VALUES FROM ('2016-08-01') TO ('2016-09-01'); CREATE TABLE gtest_child3 PARTITION OF gtest_parent ( f3 DEFAULT 42 -- error @@ -538,6 +603,15 @@ CREATE TABLE gtest_child3 (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWA ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); -- error DROP TABLE gtest_child3; CREATE TABLE gtest_child3 (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWAYS AS (f2 * 33) VIRTUAL); +ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); -- error +DROP TABLE gtest_child3; +-- an explicit cast is not the same as an implicit one +CREATE TABLE gtest_cast (a int, b numeric(10,0) GENERATED ALWAYS AS (a) VIRTUAL) PARTITION BY RANGE (a); +CREATE TABLE gtest_cast_1 (a int, b numeric(10,0) GENERATED ALWAYS AS (a::numeric(10,0)) VIRTUAL); +ALTER TABLE gtest_cast ATTACH PARTITION gtest_cast_1 FOR VALUES FROM (0) TO (10); -- error +DROP TABLE gtest_cast, gtest_cast_1; +-- different column order, so the parent's expression has to be mapped +CREATE TABLE gtest_child3 (f3 bigint GENERATED ALWAYS AS (f2 * 2) VIRTUAL, f2 bigint, f1 date NOT NULL); ALTER TABLE gtest_parent ATTACH PARTITION gtest_child3 FOR VALUES FROM ('2016-09-01') TO ('2016-10-01'); \d gtest_child \d gtest_child2 @@ -547,21 +621,21 @@ INSERT INTO gtest_parent (f1, f2) VALUES ('2016-07-15', 2); INSERT INTO gtest_parent (f1, f2) VALUES ('2016-08-15', 3); SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; SELECT tableoid::regclass, * FROM gtest_child ORDER BY 1, 2, 3; -SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; -- uses child's generation expression, not parent's +SELECT tableoid::regclass, * FROM gtest_child2 ORDER BY 1, 2, 3; SELECT tableoid::regclass, * FROM gtest_child3 ORDER BY 1, 2, 3; UPDATE gtest_parent SET f1 = f1 + 60 WHERE f2 = 1; SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; --- alter only parent's and one child's generation expression -ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -\d gtest_parent -\d gtest_child -\d gtest_child2 -\d gtest_child3 -SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; +-- cannot alter only parent's or one partition's generation expression +ALTER TABLE ONLY gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); -- error +ALTER TABLE gtest_child ALTER COLUMN f3 SET EXPRESSION AS (f2 * 10); -- error -- alter generation expression of parent and all its children altogether +ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 4); +SELECT tableoid::regclass, * FROM gtest_parent ORDER BY 1, 2, 3; +ALTER TABLE gtest_parent ADD CONSTRAINT cc1 CHECK (f3 < 12); -- error +ALTER TABLE gtest_parent ADD CONSTRAINT cc CHECK (f3 < 13); -- ok +ALTER TABLE gtest_parent DROP CONSTRAINT cc; ALTER TABLE gtest_parent ALTER COLUMN f3 SET EXPRESSION AS (f2 * 2); \d gtest_parent \d gtest_child @@ -969,3 +1043,13 @@ select * from gtest_cursor order by id; commit; drop table gtest_cursor; + +-- a partition cannot have a different generation expression, which would let +-- the partitioned table's NOT NULL virtual column read as NULL +CREATE TABLE gtestnn_parent2 (a int NOT NULL, b int GENERATED ALWAYS AS (nullif(a, 0)) VIRTUAL NOT NULL) PARTITION BY LIST (a); +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 (b GENERATED ALWAYS AS (a + 1) VIRTUAL) FOR VALUES IN (0); -- error +CREATE TABLE gtestnn_child2 PARTITION OF gtestnn_parent2 FOR VALUES IN (0, 1); +INSERT INTO gtestnn_parent2 VALUES (0); -- error +INSERT INTO gtestnn_parent2 VALUES (1); +SELECT a, b FROM gtestnn_parent2; +DROP TABLE gtestnn_parent2; -- 2.37.1 (Apple Git-137.1)
^ permalink raw reply [nested|flat] 24+ messages in thread

* Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned
  2026-10-10 00:23 pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Richard Guo <rguo@postgresql.org>
  2026-10-13 12:42 ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-10-13 14:34   ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Richard Guo <guofenglinux@gmail.com>
  2026-10-13 15:41     ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-10-13 16:00       ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-10-14 04:39         ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-10-26 17:40           ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Manu <manuelreyesbravo@gmail.com>
  2026-10-27 03:10             ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-11-11 15:41               ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-11-11 15:47                 ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-11-12 04:36                   ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-11-14 01:12                     ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Manu <manuelreyesbravo@gmail.com>
  2026-11-15 03:36                       ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-11-15 21:15                         ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Zsolt Parragi <zsolt.parragi@percona.com>
  2026-11-17 01:43                           ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-11-17 19:26                             ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Zsolt Parragi <zsolt.parragi@percona.com>
  2026-11-19 05:01                               ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-11-19 19:08                                 ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Manu <manuelreyesbravo@gmail.com>
  2026-11-24 03:31                                   ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
@ 2026-11-25 01:42                                     ` Manu <manuelreyesbravo@gmail.com>
  0 siblings, 0 replies; 24+ messages in thread

From: Manu @ 2026-11-25 01:42 UTC (permalink / raw)
  To: shihao zhong <zhong950419@gmail.com>; +Cc: Zsolt Parragi <zsolt.parragi@percona.com>; Álvaro Herrera <alvherre@kurilemu.de>; Richard Guo <guofenglinux@gmail.com>; pgsql-hackers@lists.postgresql.org

Hi Shihao,

On Mon, Nov 23, 2026 at 10:31 PM shihao zhong <zhong950419@gmail.com>
wrote:
> ADD COLUMN now checks only the new column, and the pg_upgrade message
> uses your text.

Thanks.  v7 fixes both cases on master (b4cc5e924b7), REL_19_STABLE
(698c390bbd6) and REL_18_STABLE (95d051fee16): ADD COLUMN works on the
divergent trees, and following the new pg_upgrade text repairs the
two-parent ones.  Everything else we had still passes.

Regards,
Manu






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

* Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned
  2026-10-10 00:23 pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Richard Guo <rguo@postgresql.org>
  2026-10-13 12:42 ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-10-13 14:34   ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Richard Guo <guofenglinux@gmail.com>
  2026-10-13 15:41     ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-10-13 16:00       ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-10-14 04:39         ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-10-26 17:40           ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Manu <manuelreyesbravo@gmail.com>
  2026-10-27 03:10             ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-11-11 15:41               ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-11-11 15:47                 ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-11-12 04:36                   ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
@ 2026-11-21 11:31                     ` Álvaro Herrera <alvherre@kurilemu.de>
  2026-11-24 03:32                       ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  1 sibling, 1 reply; 24+ messages in thread

From: Álvaro Herrera @ 2026-11-21 11:31 UTC (permalink / raw)
  To: shihao zhong <zhong950419@gmail.com>; +Cc: Manu <manuelreyesbravo@gmail.com>; Richard Guo <guofenglinux@gmail.com>; Richard Guo <rguo@postgresql.org>; pgsql-hackers@lists.postgresql.org

On 2026-Nov-11, shihao zhong wrote:

> Also, just curious. Your emails often end with a nice quote. Does a tool
> pick those for you?

Hah, yeah, sort of -- I wrote a ten-line Perl program that chooses one
from a silly line-based formatted text file I came up with for that
purpose; Mutt calls that to choose one for every email.  The set of
quotes changes over the years ... I think I first started collecting
such quotes back when I was using FidoNet in 1993 or so, but of course
it has evolved -- some of the old ones becoming cringe-worthy, whatever.

Regards

-- 
Álvaro Herrera         PostgreSQL Developer  —  https://www.EnterpriseDB.com/
"Si quieres ser creativo, aprende el arte de perder el tiempo"






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

* Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned
  2026-10-10 00:23 pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Richard Guo <rguo@postgresql.org>
  2026-10-13 12:42 ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-10-13 14:34   ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Richard Guo <guofenglinux@gmail.com>
  2026-10-13 15:41     ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-10-13 16:00       ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-10-14 04:39         ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-10-26 17:40           ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Manu <manuelreyesbravo@gmail.com>
  2026-10-27 03:10             ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-11-11 15:41               ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-11-11 15:47                 ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-11-12 04:36                   ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned shihao zhong <zhong950419@gmail.com>
  2026-11-21 11:31                     ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
@ 2026-11-24 03:32                       ` shihao zhong <zhong950419@gmail.com>
  0 siblings, 0 replies; 24+ messages in thread

From: shihao zhong @ 2026-11-24 03:32 UTC (permalink / raw)
  To: Álvaro Herrera <alvherre@kurilemu.de>; +Cc: Manu <manuelreyesbravo@gmail.com>; Richard Guo <guofenglinux@gmail.com>; Richard Guo <rguo@postgresql.org>; pgsql-hackers@lists.postgresql.org

> I wrote a ten-line Perl program that chooses one
> from a silly line-based formatted text file I came up with for that
> purpose;

This is pretty cool, I will be your hacker session tomorrow, we can talk
more about that here.

Thanks,
Shihao

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

* Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned
  2026-10-10 00:23 pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Richard Guo <rguo@postgresql.org>
  2026-10-13 12:42 ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Álvaro Herrera <alvherre@kurilemu.de>
  2026-10-13 14:34   ` Re: pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Richard Guo <guofenglinux@gmail.com>
@ 2026-10-13 15:45     ` Álvaro Herrera <alvherre@kurilemu.de>
  1 sibling, 0 replies; 24+ messages in thread

From: Álvaro Herrera @ 2026-10-13 15:45 UTC (permalink / raw)
  To: Richard Guo <guofenglinux@gmail.com>; +Cc: pgsql-hackers@lists.postgresql.org

On 2026-Oct-13, Richard Guo wrote:

> On Tue, Oct 13, 2026 at 9:43 PM Álvaro Herrera <alvherre@kurilemu.de> wrote:
> > I find this very surprising.  Are we sure that it makes sense for a
> > partition to have a generating expression that differs from the one in
> > the parent table?
> 
> No, I don't think it makes sense for a partition to have a different
> virtual generation expression than its parent.  I raised this exact
> same complaint in [1], the paragraph starting with "Regarding #4",
> quoted below:
> 
>   Regarding #4, the fix is to not trust NOT NULL on a virtual generated
>   column of a partitioned table.  But I don't like this fix at all.  I
>   think the real problem is that a partition is allowed to have a
>   different virtual generation expression than its parent.

It looks like we reached the same conclusion.  I propose we restrict
this.  Ideally we'd do that at least starting with 19.  (I would in fact
go even further and say that we should add restrictions to all affected
stable branches, and provide SQL scripts that users can run to find and
remove those that already exist there.)  I don't have a patch though,
but I imagine it should be easy.

-- 
Álvaro Herrera               48°01'N 7°57'E  —  https://www.EnterpriseDB.com/
"Hay quien adquiere la mala costumbre de ser infeliz" (M. A. Evans)





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

* pgsql: Don't trust NOT NULL on virtual generated columns of partitioned
@ 2026-10-10 00:23 Richard Guo <rguo@postgresql.org>
  0 siblings, 0 replies; 24+ messages in thread

From: Richard Guo @ 2026-10-10 00:23 UTC (permalink / raw)
  To: pgsql-committers@lists.postgresql.org

Don't trust NOT NULL on virtual generated columns of partitioned tables

Commit 383eb21eb taught the planner to convert a NOT IN sublink to an
anti-join when the sub-select's outputs are provably non-nullable.
Since the sub-select has not been through any planner processing at
that point, a reference to a virtual generated column is still a plain
Var, and query_outputs_are_not_nullable() relied on the column's NOT
NULL constraint to prove it non-nullable.

That is not safe for a partitioned table.  A partition can have a
generation expression different from its parent's, and it enforces the
NOT NULL constraint against its own expression, whereas a query on the
parent computes the column using the parent's expression.  So the
column can be NULL when read through the parent despite the
constraint, and the anti-join would then produce wrong results, as it
returns rows that NOT IN should have rejected.

To fix, make var_is_nonnullable() ignore the NOT NULL constraint on a
virtual generated column of a partitioned table when consulting the
catalogs.  The other sources of NOT NULL information are only used
after virtual generated columns have been expanded, so they are not
affected.

Author: Shihao Zhong <zhong950419@gmail.com>
Reviewed-by: Richard Guo <guofenglinux@gmail.com>
Discussion: https://postgr.es/m/CAGRkXqR7VXacmRP41UBaM5u4aseeCH5ECVmQgn_YS=L7=xdhTw@mail.gmail.com
Backpatch-through: 19

Branch
------
REL_19_STABLE

Details
-------
https://git.postgresql.org/pg/commitdiff/af2ff0a994d1e3149c827ef0dd2920aa62a8ed7f

Modified Files
--------------
src/backend/optimizer/util/clauses.c            | 12 ++++++++++++
src/test/regress/expected/generated_virtual.out | 21 +++++++++++++++++++++
src/test/regress/sql/generated_virtual.sql      | 10 ++++++++++
3 files changed, 43 insertions(+)



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


end of thread, other threads:[~2026-11-25 01:42 UTC | newest]

Thread overview: 24+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2026-10-10 00:23 pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Richard Guo <rguo@postgresql.org>
2026-10-13 12:42 ` Álvaro Herrera <alvherre@kurilemu.de>
2026-10-13 14:34   ` Richard Guo <guofenglinux@gmail.com>
2026-10-13 15:41     ` shihao zhong <zhong950419@gmail.com>
2026-10-13 16:00       ` Álvaro Herrera <alvherre@kurilemu.de>
2026-10-14 04:39         ` shihao zhong <zhong950419@gmail.com>
2026-10-26 17:40           ` Manu <manuelreyesbravo@gmail.com>
2026-10-27 03:10             ` shihao zhong <zhong950419@gmail.com>
2026-11-11 15:41               ` Álvaro Herrera <alvherre@kurilemu.de>
2026-11-11 15:47                 ` Álvaro Herrera <alvherre@kurilemu.de>
2026-11-12 04:36                   ` shihao zhong <zhong950419@gmail.com>
2026-11-14 01:12                     ` Manu <manuelreyesbravo@gmail.com>
2026-11-15 03:36                       ` shihao zhong <zhong950419@gmail.com>
2026-11-15 21:15                         ` Zsolt Parragi <zsolt.parragi@percona.com>
2026-11-17 01:43                           ` shihao zhong <zhong950419@gmail.com>
2026-11-17 19:26                             ` Zsolt Parragi <zsolt.parragi@percona.com>
2026-11-19 05:01                               ` shihao zhong <zhong950419@gmail.com>
2026-11-19 19:08                                 ` Manu <manuelreyesbravo@gmail.com>
2026-11-24 03:31                                   ` shihao zhong <zhong950419@gmail.com>
2026-11-25 01:42                                     ` Manu <manuelreyesbravo@gmail.com>
2026-11-21 11:31                     ` Álvaro Herrera <alvherre@kurilemu.de>
2026-11-24 03:32                       ` shihao zhong <zhong950419@gmail.com>
2026-10-13 15:45     ` Álvaro Herrera <alvherre@kurilemu.de>
2026-10-10 00:23 pgsql: Don't trust NOT NULL on virtual generated columns of partitioned Richard Guo <rguo@postgresql.org>

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox