postgresql/src/backend/rewrite
Richard Guo 07b257189e Fix incorrect NEW references to generated columns in rule rewriting
When a rule action or rule qualification references NEW.col where col
is a generated column (stored or virtual), the rewriter produces
incorrect results.

rewriteTargetListIU removes generated columns from the query's target
list, since stored generated columns are recomputed by the executor
and virtual ones store nothing.  However, ReplaceVarsFromTargetList
then cannot find these columns when resolving NEW references during
rule rewriting.  For UPDATE, the REPLACEVARS_CHANGE_VARNO fallback
redirects NEW.col to the original target relation, making it read the
pre-update value (same as OLD.col).  For INSERT,
REPLACEVARS_SUBSTITUTE_NULL replaces it with NULL.  Both are wrong
when the generated column depends on columns being modified.

Fix by building target list entries for generated columns from their
generation expressions, pre-resolving the NEW.attribute references
within those expressions against the query's targetlist, and passing
them together with the query's targetlist to ReplaceVarsFromTargetList.

Back-patch to all supported branches.  Virtual generated columns were
added in v18, so the back-patches in pre-v18 branches only handle
stored generated columns.

Reported-by: SATYANARAYANA NARLAPURAM <satyanarlapuram@gmail.com>
Author: Richard Guo <guofenglinux@gmail.com>
Author: Dean Rasheed <dean.a.rasheed@gmail.com>
Reviewed-by: Chao Li <li.evan.chao@gmail.com>
Discussion: https://postgr.es/m/CAHg+QDexGTmCZzx=73gXkY2ZADS6LRhpnU+-8Y_QmrdTS6yUhA@mail.gmail.com
Backpatch-through: 14
2026-04-21 14:33:07 +09:00
..
Makefile SEARCH and CYCLE clauses 2021-02-01 14:32:51 +01:00
meson.build Update copyright for 2023 2023-01-02 15:00:37 -05:00
rewriteDefine.c Get rid of the "new" and "old" entries in a view's rangetable. 2023-01-18 13:23:57 -05:00
rewriteHandler.c Fix incorrect NEW references to generated columns in rule rewriting 2026-04-21 14:33:07 +09:00
rewriteManip.c Handle default NULL insertion a little better. 2025-01-29 15:31:55 -05:00
rewriteRemove.c Update copyright for 2023 2023-01-02 15:00:37 -05:00
rewriteSearchCycle.c Update copyright for 2023 2023-01-02 15:00:37 -05:00
rewriteSupport.c Update copyright for 2023 2023-01-02 15:00:37 -05:00
rowsecurity.c Fix RLS policy usage in MERGE. 2023-08-07 09:27:09 +01:00