BUG #19943: Wrong results under partition with CHECK/NOT NULL on overridden VIRTUAL generated columns

Started by PG Bug reporting form4 days ago1 messagesbugs

Thread notes

1 note#bug
hackorum-bot#bug
hackorum-bot
2 days ago

@global #bug

#bug
Jump to latest
#1PG Bug reporting form
noreply@postgresql.org

The following bug has been logged on the website:

Bug reference: 19943
Logged by: Chi Zhang
Email address: 798604270@qq.com
PostgreSQL version: 19.0
Operating system: Ubuntu 24.04
Description:

Hi,

I found that when a partitioned (or inherited) table defines a CHECK or NOT
NULL constraint on a VIRTUAL generated column whose generation expression is
overridden by a child partition/table, get_relation_constraints() expands
the parent/intermediate table's constraint using its own virtual column
expression. Under the default constraint_exclusion = partition setting on a
subpartitioned table, the planner erroneously proves a contradiction
(One-Time Filter: false) and silently returns 0 rows instead of the matching
row.

This is the test case:
```
CREATE TEMP TABLE gp_003(
k1 int,
k2 int,
a int,
g int GENERATED ALWAYS AS (a - 10) VIRTUAL
) PARTITION BY RANGE (k1);

CREATE TEMP TABLE p_003(
k1 int,
k2 int,
a int,
g int GENERATED ALWAYS AS (a - 10) VIRTUAL
) PARTITION BY RANGE (k2);

CREATE TEMP TABLE c_003(
k1 int,
k2 int,
a int,
g int GENERATED ALWAYS AS (a * 10) VIRTUAL
);

ALTER TABLE gp_003 ATTACH PARTITION p_003 FOR VALUES FROM (0) TO (10);
ALTER TABLE p_003 ATTACH PARTITION c_003 FOR VALUES FROM (0) TO (10);
ALTER TABLE gp_003 ADD CONSTRAINT ck_003 CHECK (g > 0);

-- Valid row: in c_003, g = a * 10 = 50 > 0, so CHECK (g > 0) passes.
-- When queried via gp_003, SQL evaluates gp_003's expression g = a - 10 =
-5 < 0!
INSERT INTO c_003(k1, k2, a) VALUES (1, 1, 5);

-- Reference (constraint_exclusion = off): returns 1 row (1, 1, 5, -5)
SET constraint_exclusion = off;
SELECT 'OFF' AS mode, k1, k2, a, g FROM gp_003 WHERE g < 0;

-- 100% Default config (constraint_exclusion = partition): BUG -> silently
returns 0 rows!
RESET constraint_exclusion;
SHOW constraint_exclusion;
SELECT 'DEFAULT_PARTITION' AS mode, k1, k2, a, g FROM gp_003 WHERE g < 0;

```

I can reproduce this on PostgreSQL 20devel (master, commit b4cc5e924b7a)