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 <[email protected]> Author: Richard Guo <[email protected]> Author: Dean Rasheed <[email protected]> Reviewed-by: Chao Li <[email protected]> Discussion: https://postgr.es/m/CAHg+QDexGTmCZzx=73gxky2zads6lrhpnu+-8y_qmrdts6y...@mail.gmail.com Backpatch-through: 14 Branch ------ REL_16_STABLE Details ------- https://git.postgresql.org/pg/commitdiff/07b257189ea4fc949a36fd341ba2ba6b49e5f718 Modified Files -------------- src/backend/rewrite/rewriteHandler.c | 134 ++++++++++++++++++++++++++++++-- src/test/regress/expected/generated.out | 34 ++++++++ src/test/regress/sql/generated.sql | 24 ++++++ 3 files changed, 187 insertions(+), 5 deletions(-)
