pg.ddx.io pgsql-hackers@postgresql.org mailing list archive
help / color / mirror / Atom feedUPDATE run check constraints for affected columns only
11+ messages / 4 participants
[nested] [flat]
* UPDATE run check constraints for affected columns only
@ 2025-12-01 06:20 jian he <jian.universality@gmail.com>
2025-12-01 06:33 ` Re: UPDATE run check constraints for affected columns only Tom Lane <tgl@sss.pgh.pa.us>
0 siblings, 1 reply; 11+ messages in thread
From: jian he @ 2025-12-01 06:20 UTC (permalink / raw)
To: pgsql-hackers
hi.
while casually looking at https://wiki.postgresql.org/wiki/Todo
then I found out this thread:
https://postgr.es/m/1326055327.15293.13.camel%40vanquo.pezone.net
Seems easier to do nowadays.
The attached patch implements the $subject.
regress tests seems not enough to test it.
Following the approach in 001_constraint_validation.pl, we use
ereport(DEBUG1, errmsg_internal), then grep the logs to check whether the
enforced constraint verification was skipped or not.
we can not add check constraint to VIEW,
tests covered partitioned table scarenio.
DEMO:
CREATE TABLE upd_check_skip (a int, b int, c int, d int generated
always as (b+c) STORED);
ALTER TABLE upd_check_skip ADD CONSTRAINT cc2 CHECK(a+c < 100);
ALTER TABLE upd_check_skip ADD CONSTRAINT cc3 CHECK(b < 1);
ALTER TABLE upd_check_skip ADD CONSTRAINT cc4 CHECK(d < 2);
INSERT INTO upd_check_skip DEFAULT VALUES;
SET client_min_messages to DEBUG1;
--constraint verification will be skipped for cc3, cc4
UPDATE upd_check_skip SET a = 1;
--constraint verification will be skipped for cc2
UPDATE upd_check_skip SET b = -1;
--constraint verification will be skipped for cc3
UPDATE upd_check_skip SET c = -1;
--
jian
https://www.enterprisedb.com
Attachments:
v1-0001-UPDATE-run-check-constraints-for-affected-columns-only.patch (text/x-patch, 10.4K) download
From 51dca341ee334a04e5dc296fe1da8af6851c6781 Mon Sep 17 00:00:00 2001
From: jian he <jian.universality@gmail.com>
Date: Mon, 1 Dec 2025 12:45:08 +0800
Subject: [PATCH v1 1/1] UPDATE run check constraints for affected columns only
discussion: https://postgr.es/m/
context: https://postgr.es/m/1326055327.15293.13.camel%40vanquo.pezone.net
---
src/backend/commands/copyfrom.c | 2 +-
src/backend/executor/execMain.c | 45 +++++++++++++++--
src/backend/executor/execReplication.c | 4 +-
src/backend/executor/nodeModifyTable.c | 4 +-
src/include/executor/executor.h | 2 +-
src/include/nodes/execnodes.h | 7 +++
.../test_misc/t/001_constraint_validation.pl | 50 +++++++++++++++++++
7 files changed, 105 insertions(+), 9 deletions(-)
diff --git a/src/backend/commands/copyfrom.c b/src/backend/commands/copyfrom.c
index 12781963b4f..52e2bb983e6 100644
--- a/src/backend/commands/copyfrom.c
+++ b/src/backend/commands/copyfrom.c
@@ -1355,7 +1355,7 @@ CopyFrom(CopyFromState cstate)
*/
if (resultRelInfo->ri_FdwRoutine == NULL &&
resultRelInfo->ri_RelationDesc->rd_att->constr)
- ExecConstraints(resultRelInfo, myslot, estate);
+ ExecConstraints(CMD_INSERT, resultRelInfo, myslot, estate);
/*
* Also check the tuple against the partition constraint, if
diff --git a/src/backend/executor/execMain.c b/src/backend/executor/execMain.c
index 27c9eec697b..b157eacd1dc 100644
--- a/src/backend/executor/execMain.c
+++ b/src/backend/executor/execMain.c
@@ -52,6 +52,7 @@
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "nodes/queryjumble.h"
+#include "optimizer/optimizer.h"
#include "parser/parse_relation.h"
#include "pgstat.h"
#include "rewrite/rewriteHandler.h"
@@ -1775,7 +1776,7 @@ ExecutePlan(QueryDesc *queryDesc,
* Returns NULL if OK, else name of failed check constraint
*/
static const char *
-ExecRelCheck(ResultRelInfo *resultRelInfo,
+ExecRelCheck(CmdType operation, ResultRelInfo *resultRelInfo,
TupleTableSlot *slot, EState *estate)
{
Relation rel = resultRelInfo->ri_RelationDesc;
@@ -1800,8 +1801,16 @@ ExecRelCheck(ResultRelInfo *resultRelInfo,
*/
if (resultRelInfo->ri_CheckConstraintExprs == NULL)
{
+ Bitmapset *updatedCols;
+ Bitmapset *extraUpdatedCols;
+
oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
resultRelInfo->ri_CheckConstraintExprs = palloc0_array(ExprState *, ncheck);
+
+ resultRelInfo->ri_UpdateSkipConstrCheck = palloc0(sizeof(bool) * ncheck);
+ updatedCols = ExecGetUpdatedCols(resultRelInfo, estate);
+ extraUpdatedCols = ExecGetExtraUpdatedCols(resultRelInfo, estate);
+
for (int i = 0; i < ncheck; i++)
{
Expr *checkconstr;
@@ -1814,6 +1823,32 @@ ExecRelCheck(ResultRelInfo *resultRelInfo,
checkconstr = (Expr *) expand_generated_columns_in_expr((Node *) checkconstr, rel, 1);
resultRelInfo->ri_CheckConstraintExprs[i] =
ExecPrepareExpr(checkconstr, estate);
+
+ if (operation == CMD_UPDATE)
+ {
+ Bitmapset *check_attrs = NULL;
+
+ pull_varattnos((Node *) checkconstr, 1, &check_attrs);
+
+ /*
+ * If this constraint has no Var reference or contains a
+ * whole-row Var reference, then we cannot skip the
+ * verification.
+ */
+ if (!check_attrs || bms_is_member(0 - FirstLowInvalidHeapAttributeNumber, check_attrs))
+ continue;
+
+ if (!bms_overlap(check_attrs, updatedCols) &&
+ !bms_overlap(check_attrs, extraUpdatedCols))
+ {
+ resultRelInfo->ri_UpdateSkipConstrCheck[i] = true;
+
+ ereport(DEBUG1,
+ errmsg_internal("skipping verification for constraint \"%s\" on table \"%s\"",
+ check[i].ccname,
+ RelationGetRelationName(rel)));
+ }
+ }
}
MemoryContextSwitchTo(oldContext);
}
@@ -1837,6 +1872,10 @@ ExecRelCheck(ResultRelInfo *resultRelInfo,
* is not to be treated as a failure. Therefore, use ExecCheck not
* ExecQual.
*/
+ if (operation == CMD_UPDATE &&
+ resultRelInfo->ri_UpdateSkipConstrCheck[i] == true)
+ continue;
+
if (checkconstr && !ExecCheck(checkconstr, econtext))
return check[i].ccname;
}
@@ -1977,7 +2016,7 @@ ExecPartitionCheckEmitError(ResultRelInfo *resultRelInfo,
* 'resultRelInfo' is the final result relation, after tuple routing.
*/
void
-ExecConstraints(ResultRelInfo *resultRelInfo,
+ExecConstraints(CmdType operation, ResultRelInfo *resultRelInfo,
TupleTableSlot *slot, EState *estate)
{
Relation rel = resultRelInfo->ri_RelationDesc;
@@ -2027,7 +2066,7 @@ ExecConstraints(ResultRelInfo *resultRelInfo,
{
const char *failed;
- if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
+ if ((failed = ExecRelCheck(operation, resultRelInfo, slot, estate)) != NULL)
{
char *val_desc;
Relation orig_rel = rel;
diff --git a/src/backend/executor/execReplication.c b/src/backend/executor/execReplication.c
index def32774c90..a77ef6b26bd 100644
--- a/src/backend/executor/execReplication.c
+++ b/src/backend/executor/execReplication.c
@@ -835,7 +835,7 @@ ExecSimpleRelationInsert(ResultRelInfo *resultRelInfo,
/* Check the constraints of the tuple */
if (rel->rd_att->constr)
- ExecConstraints(resultRelInfo, slot, estate);
+ ExecConstraints(CMD_INSERT, resultRelInfo, slot, estate);
if (rel->rd_rel->relispartition)
ExecPartitionCheck(resultRelInfo, slot, estate, true);
@@ -932,7 +932,7 @@ ExecSimpleRelationUpdate(ResultRelInfo *resultRelInfo,
/* Check the constraints of the tuple */
if (rel->rd_att->constr)
- ExecConstraints(resultRelInfo, slot, estate);
+ ExecConstraints(CMD_INSERT, resultRelInfo, slot, estate);
if (rel->rd_rel->relispartition)
ExecPartitionCheck(resultRelInfo, slot, estate, true);
diff --git a/src/backend/executor/nodeModifyTable.c b/src/backend/executor/nodeModifyTable.c
index e44f1223886..1f1951cfd34 100644
--- a/src/backend/executor/nodeModifyTable.c
+++ b/src/backend/executor/nodeModifyTable.c
@@ -1094,7 +1094,7 @@ ExecInsert(ModifyTableContext *context,
* Check the constraints of the tuple.
*/
if (resultRelationDesc->rd_att->constr)
- ExecConstraints(resultRelInfo, slot, estate);
+ ExecConstraints(CMD_INSERT, resultRelInfo, slot, estate);
/*
* Also check the tuple against the partition constraint, if there is
@@ -2291,7 +2291,7 @@ lreplace:
* have it validate all remaining checks.
*/
if (resultRelationDesc->rd_att->constr)
- ExecConstraints(resultRelInfo, slot, estate);
+ ExecConstraints(CMD_UPDATE, resultRelInfo, slot, estate);
/*
* replace the heap tuple
diff --git a/src/include/executor/executor.h b/src/include/executor/executor.h
index f99fc26eb1f..378611488ae 100644
--- a/src/include/executor/executor.h
+++ b/src/include/executor/executor.h
@@ -257,7 +257,7 @@ extern void InitResultRelInfo(ResultRelInfo *resultRelInfo,
extern ResultRelInfo *ExecGetTriggerResultRel(EState *estate, Oid relid,
ResultRelInfo *rootRelInfo);
extern List *ExecGetAncestorResultRels(EState *estate, ResultRelInfo *resultRelInfo);
-extern void ExecConstraints(ResultRelInfo *resultRelInfo,
+extern void ExecConstraints(CmdType operation, ResultRelInfo *resultRelInfo,
TupleTableSlot *slot, EState *estate);
extern AttrNumber ExecRelGenVirtualNotNull(ResultRelInfo *resultRelInfo,
TupleTableSlot *slot,
diff --git a/src/include/nodes/execnodes.h b/src/include/nodes/execnodes.h
index 9018e190cc7..8a4878da48d 100644
--- a/src/include/nodes/execnodes.h
+++ b/src/include/nodes/execnodes.h
@@ -551,6 +551,13 @@ typedef struct ResultRelInfo
/* list of WithCheckOption expr states */
List *ri_WithCheckOptionExprs;
+ /*
+ * ri_UpdateSkipConstrCheck[checkconstr - 1] is true if the UPDATE does not
+ * touch any columns referenced by this check constraint. Except plain
+ * UPDATE, This applys to ON CONFLICT DO UPDATE, MERGE UPDATE too.
+ */
+ bool *ri_UpdateSkipConstrCheck;
+
/* array of expr states for checking check constraints */
ExprState **ri_CheckConstraintExprs;
diff --git a/src/test/modules/test_misc/t/001_constraint_validation.pl b/src/test/modules/test_misc/t/001_constraint_validation.pl
index bdc751724f4..0e99e9381ad 100644
--- a/src/test/modules/test_misc/t/001_constraint_validation.pl
+++ b/src/test/modules/test_misc/t/001_constraint_validation.pl
@@ -40,6 +40,56 @@ sub is_table_verified
my $output;
+note "test UPDATE operation skip enforced constraint vertification";
+# Check whether the run_sql_command output shows that the UPDATE operation
+# skipped constraint verification.
+sub is_update_constraint_skipped
+{
+ my $output = shift;
+ my $constr = shift;
+ return index($output, "DEBUG: skipping verification for constraint \"$constr\"") != -1;
+}
+
+run_sql_command(
+ 'CREATE TABLE upd_check_skip (
+ i int, a int default 11,
+ b int, c int,
+ d int generated always as (b+c) STORED,
+ e int generated always as (i) VIRTUAL) partition by range (i);
+
+ CREATE TABLE upd_check_skip_1(
+ a int default 12, i int,
+ c int, b int,
+ d int generated always as (b+1) STORED,
+ e int generated always as (b - 100) VIRTUAL);
+
+ ALTER TABLE upd_check_skip ATTACH PARTITION upd_check_skip_1 FOR VALUES FROM (0) TO (10);
+ CREATE TABLE upd_check_skip_2 PARTITION OF upd_check_skip FOR VALUES FROM (10) TO (30);
+ INSERT INTO upd_check_skip SELECT g + 8, g, -g-g, g+1 FROM generate_series(0, 7) g;
+ ALTER TABLE upd_check_skip ADD COLUMN f int DEFAULT 101;
+
+ ALTER TABLE upd_check_skip ADD CONSTRAINT cc1 CHECK(a+b < 1);
+ ALTER TABLE upd_check_skip ADD CONSTRAINT cc2 CHECK(a+c < 100);
+ ALTER TABLE upd_check_skip ADD CONSTRAINT cc3 CHECK(b < 1);
+ ALTER TABLE upd_check_skip ADD CONSTRAINT cc4 CHECK(d < 2); ');
+
+$output = run_sql_command('UPDATE upd_check_skip SET c = 3 WHERE i = 12;');
+ok(is_update_constraint_skipped($output, 'cc1'),
+ 'UPDATE skipped verification for constraint cc1');
+ok(is_update_constraint_skipped($output, 'cc3'),
+ 'UPDATE skipped verification for constraint cc3');
+
+$output = run_sql_command('UPDATE upd_check_skip SET b = -7 WHERE i = 11;');
+ok(is_update_constraint_skipped($output, 'cc2'),
+ 'UPDATE skipped verification for constraint cc2');
+ok(!is_update_constraint_skipped($output, 'cc4'),
+ 'UPDATE does not skipped verification for constraint cc4');
+
+$output = run_sql_command('UPDATE upd_check_skip SET f = 14 WHERE i = 15;');
+ok(is_update_constraint_skipped($output, 'cc4'),
+ 'UPDATE skipped verification for constraint cc4');
+run_sql_command('drop table upd_check_skip;');
+
note "test alter table set not null";
run_sql_command(
--
2.34.1
^ permalink raw reply [nested|flat] 11+ messages in thread
* Re: UPDATE run check constraints for affected columns only
2025-12-01 06:20 UPDATE run check constraints for affected columns only jian he <jian.universality@gmail.com>
@ 2025-12-01 06:33 ` Tom Lane <tgl@sss.pgh.pa.us>
2025-12-07 15:50 ` Re: UPDATE run check constraints for affected columns only jian he <jian.universality@gmail.com>
0 siblings, 1 reply; 11+ messages in thread
From: Tom Lane @ 2025-12-01 06:33 UTC (permalink / raw)
To: jian he <jian.universality@gmail.com>; +Cc: pgsql-hackers
jian he <jian.universality@gmail.com> writes:
> The attached patch implements the $subject.
Does this cover the case where a BEFORE UPDATE trigger has modified
columns that were not mentioned in UPDATE...SET?
regards, tom lane
^ permalink raw reply [nested|flat] 11+ messages in thread
* Re: UPDATE run check constraints for affected columns only
2025-12-01 06:20 UPDATE run check constraints for affected columns only jian he <jian.universality@gmail.com>
2025-12-01 06:33 ` Re: UPDATE run check constraints for affected columns only Tom Lane <tgl@sss.pgh.pa.us>
@ 2025-12-07 15:50 ` jian he <jian.universality@gmail.com>
2026-01-23 02:09 ` Re: UPDATE run check constraints for affected columns only jian he <jian.universality@gmail.com>
0 siblings, 1 reply; 11+ messages in thread
From: jian he @ 2025-12-07 15:50 UTC (permalink / raw)
To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: pgsql-hackers
On Mon, Dec 1, 2025 at 2:33 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:
>
> jian he <jian.universality@gmail.com> writes:
> > The attached patch implements the $subject.
>
> Does this cover the case where a BEFORE UPDATE trigger has modified
> columns that were not mentioned in UPDATE...SET?
>
> regards, tom lane
hi.
in ExecInitGenerated, we have:
/*
* In an UPDATE, we can skip computing any generated columns that do not
* depend on any UPDATE target column. But if there is a BEFORE ROW
* UPDATE trigger, we cannot skip because the trigger might change more
* columns.
*/
if (cmdtype == CMD_UPDATE &&
!(rel->trigdesc && rel->trigdesc->trig_update_before_row))
updatedCols = ExecGetUpdatedCols(resultRelInfo, estate);
else
updatedCols = NULL;
So I applied the equivalent approach. This should works fine, because if we are
able to skip computing certain generated columns, then we sure sure be able to
skip evaluating some check constraints.
--
jian
https://www.enterprisedb.com
Attachments:
v2-0001-UPDATE-run-check-constraints-for-affected-columns-only.patch (text/x-patch, 10.4K) download
From 72bdfcf59c22e33c881ad650273a1949cb378d64 Mon Sep 17 00:00:00 2001
From: jian he <jian.universality@gmail.com>
Date: Sun, 7 Dec 2025 23:01:43 +0800
Subject: [PATCH v2 1/1] UPDATE run check constraints for affected columns only
commitfest: https://commitfest.postgresql.org/patch/6270
discussion: https://postgr.es/m/CACJufxEtY1hdLcx=Fhnqp-ERcV1PhbvELG5COy_CZjoEW76ZPQ@mail.gmail.com
context: https://postgr.es/m/1326055327.15293.13.camel%40vanquo.pezone.net
---
src/backend/commands/copyfrom.c | 2 +-
src/backend/executor/execMain.c | 53 +++++++++++--
src/backend/executor/execReplication.c | 4 +-
src/backend/executor/nodeModifyTable.c | 4 +-
src/include/executor/executor.h | 2 +-
.../test_misc/t/001_constraint_validation.pl | 77 +++++++++++++++++++
6 files changed, 131 insertions(+), 11 deletions(-)
diff --git a/src/backend/commands/copyfrom.c b/src/backend/commands/copyfrom.c
index 12781963b4f..52e2bb983e6 100644
--- a/src/backend/commands/copyfrom.c
+++ b/src/backend/commands/copyfrom.c
@@ -1355,7 +1355,7 @@ CopyFrom(CopyFromState cstate)
*/
if (resultRelInfo->ri_FdwRoutine == NULL &&
resultRelInfo->ri_RelationDesc->rd_att->constr)
- ExecConstraints(resultRelInfo, myslot, estate);
+ ExecConstraints(CMD_INSERT, resultRelInfo, myslot, estate);
/*
* Also check the tuple against the partition constraint, if
diff --git a/src/backend/executor/execMain.c b/src/backend/executor/execMain.c
index 27c9eec697b..7dac86a2ae5 100644
--- a/src/backend/executor/execMain.c
+++ b/src/backend/executor/execMain.c
@@ -52,6 +52,7 @@
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "nodes/queryjumble.h"
+#include "optimizer/optimizer.h"
#include "parser/parse_relation.h"
#include "pgstat.h"
#include "rewrite/rewriteHandler.h"
@@ -1775,7 +1776,7 @@ ExecutePlan(QueryDesc *queryDesc,
* Returns NULL if OK, else name of failed check constraint
*/
static const char *
-ExecRelCheck(ResultRelInfo *resultRelInfo,
+ExecRelCheck(CmdType cmdtype, ResultRelInfo *resultRelInfo,
TupleTableSlot *slot, EState *estate)
{
Relation rel = resultRelInfo->ri_RelationDesc;
@@ -1800,11 +1801,20 @@ ExecRelCheck(ResultRelInfo *resultRelInfo,
*/
if (resultRelInfo->ri_CheckConstraintExprs == NULL)
{
+ Bitmapset *updatedCols;
+
+ if (cmdtype == CMD_UPDATE &&
+ !(rel->trigdesc && rel->trigdesc->trig_update_before_row))
+ updatedCols = ExecGetAllUpdatedCols(resultRelInfo, estate);
+ else
+ updatedCols = NULL;
+
oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
resultRelInfo->ri_CheckConstraintExprs = palloc0_array(ExprState *, ncheck);
for (int i = 0; i < ncheck; i++)
{
Expr *checkconstr;
+ bool skip = false;
/* Skip not enforced constraint */
if (!check[i].ccenforced)
@@ -1812,8 +1822,41 @@ ExecRelCheck(ResultRelInfo *resultRelInfo,
checkconstr = stringToNode(check[i].ccbin);
checkconstr = (Expr *) expand_generated_columns_in_expr((Node *) checkconstr, rel, 1);
- resultRelInfo->ri_CheckConstraintExprs[i] =
- ExecPrepareExpr(checkconstr, estate);
+
+ if (updatedCols)
+ {
+ Bitmapset *check_attrs = NULL;
+
+ pull_varattnos((Node *) checkconstr, 1, &check_attrs);
+
+ /*
+ * No Var reference and contain whole-row can not skip the
+ * verification.
+ */
+ if (check_attrs &&
+ !bms_is_member(0 - FirstLowInvalidHeapAttributeNumber, check_attrs))
+ {
+ /*
+ * If it's an update with a known set of update target
+ * columns, see if we can skip the verification.
+ */
+ if (!bms_overlap(check_attrs, updatedCols))
+ {
+ skip = true;
+
+ ereport(DEBUG1,
+ errmsg_internal("skipping verification for constraint \"%s\" on table \"%s\"",
+ check[i].ccname,
+ RelationGetRelationName(rel)));
+ }
+ }
+ }
+
+ if (!skip)
+ {
+ resultRelInfo->ri_CheckConstraintExprs[i] =
+ ExecPrepareExpr(checkconstr, estate);
+ }
}
MemoryContextSwitchTo(oldContext);
}
@@ -1977,7 +2020,7 @@ ExecPartitionCheckEmitError(ResultRelInfo *resultRelInfo,
* 'resultRelInfo' is the final result relation, after tuple routing.
*/
void
-ExecConstraints(ResultRelInfo *resultRelInfo,
+ExecConstraints(CmdType cmdtype, ResultRelInfo *resultRelInfo,
TupleTableSlot *slot, EState *estate)
{
Relation rel = resultRelInfo->ri_RelationDesc;
@@ -2027,7 +2070,7 @@ ExecConstraints(ResultRelInfo *resultRelInfo,
{
const char *failed;
- if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
+ if ((failed = ExecRelCheck(cmdtype, resultRelInfo, slot, estate)) != NULL)
{
char *val_desc;
Relation orig_rel = rel;
diff --git a/src/backend/executor/execReplication.c b/src/backend/executor/execReplication.c
index def32774c90..3c3f2d67b73 100644
--- a/src/backend/executor/execReplication.c
+++ b/src/backend/executor/execReplication.c
@@ -835,7 +835,7 @@ ExecSimpleRelationInsert(ResultRelInfo *resultRelInfo,
/* Check the constraints of the tuple */
if (rel->rd_att->constr)
- ExecConstraints(resultRelInfo, slot, estate);
+ ExecConstraints(CMD_INSERT, resultRelInfo, slot, estate);
if (rel->rd_rel->relispartition)
ExecPartitionCheck(resultRelInfo, slot, estate, true);
@@ -932,7 +932,7 @@ ExecSimpleRelationUpdate(ResultRelInfo *resultRelInfo,
/* Check the constraints of the tuple */
if (rel->rd_att->constr)
- ExecConstraints(resultRelInfo, slot, estate);
+ ExecConstraints(CMD_UPDATE, resultRelInfo, slot, estate);
if (rel->rd_rel->relispartition)
ExecPartitionCheck(resultRelInfo, slot, estate, true);
diff --git a/src/backend/executor/nodeModifyTable.c b/src/backend/executor/nodeModifyTable.c
index e44f1223886..1f1951cfd34 100644
--- a/src/backend/executor/nodeModifyTable.c
+++ b/src/backend/executor/nodeModifyTable.c
@@ -1094,7 +1094,7 @@ ExecInsert(ModifyTableContext *context,
* Check the constraints of the tuple.
*/
if (resultRelationDesc->rd_att->constr)
- ExecConstraints(resultRelInfo, slot, estate);
+ ExecConstraints(CMD_INSERT, resultRelInfo, slot, estate);
/*
* Also check the tuple against the partition constraint, if there is
@@ -2291,7 +2291,7 @@ lreplace:
* have it validate all remaining checks.
*/
if (resultRelationDesc->rd_att->constr)
- ExecConstraints(resultRelInfo, slot, estate);
+ ExecConstraints(CMD_UPDATE, resultRelInfo, slot, estate);
/*
* replace the heap tuple
diff --git a/src/include/executor/executor.h b/src/include/executor/executor.h
index fa2b657fb2f..f61347208d6 100644
--- a/src/include/executor/executor.h
+++ b/src/include/executor/executor.h
@@ -257,7 +257,7 @@ extern void InitResultRelInfo(ResultRelInfo *resultRelInfo,
extern ResultRelInfo *ExecGetTriggerResultRel(EState *estate, Oid relid,
ResultRelInfo *rootRelInfo);
extern List *ExecGetAncestorResultRels(EState *estate, ResultRelInfo *resultRelInfo);
-extern void ExecConstraints(ResultRelInfo *resultRelInfo,
+extern void ExecConstraints(CmdType cmdtype, ResultRelInfo *resultRelInfo,
TupleTableSlot *slot, EState *estate);
extern AttrNumber ExecRelGenVirtualNotNull(ResultRelInfo *resultRelInfo,
TupleTableSlot *slot,
diff --git a/src/test/modules/test_misc/t/001_constraint_validation.pl b/src/test/modules/test_misc/t/001_constraint_validation.pl
index bdc751724f4..36117ec824f 100644
--- a/src/test/modules/test_misc/t/001_constraint_validation.pl
+++ b/src/test/modules/test_misc/t/001_constraint_validation.pl
@@ -40,6 +40,83 @@ sub is_table_verified
my $output;
+note "test UPDATE operation skip enforced constraint vertification";
+# Check whether the run_sql_command output shows that the UPDATE operation
+# skipped constraint verification.
+sub is_update_constraint_skipped
+{
+ my $output = shift;
+ my $constr = shift;
+ return index($output, "DEBUG: skipping verification for constraint \"$constr\"") != -1;
+}
+
+run_sql_command(
+ 'CREATE TABLE upd_check_skip (
+ i int, a int default 11,
+ b int, c int,
+ d int generated always as (b+c) STORED,
+ e int generated always as (i) VIRTUAL) partition by range (i);
+
+ CREATE TABLE upd_check_skip_1(
+ a int default 12, i int,
+ c int, b int,
+ d int generated always as (b+1) STORED,
+ e int generated always as (b - 100) VIRTUAL);
+
+ ALTER TABLE upd_check_skip ATTACH PARTITION upd_check_skip_1 FOR VALUES FROM (0) TO (10);
+ CREATE TABLE upd_check_skip_2 PARTITION OF upd_check_skip FOR VALUES FROM (10) TO (30);
+ INSERT INTO upd_check_skip SELECT g + 8, g, -g-g, g+1 FROM generate_series(0, 7) g;
+ ALTER TABLE upd_check_skip ADD COLUMN f int DEFAULT 101;
+
+ ALTER TABLE upd_check_skip ADD CONSTRAINT cc1 CHECK(a+b < 1);
+ ALTER TABLE upd_check_skip ADD CONSTRAINT cc2 CHECK(a+c < 100);
+ ALTER TABLE upd_check_skip ADD CONSTRAINT cc3 CHECK(b < 1);
+ ALTER TABLE upd_check_skip ADD CONSTRAINT cc4 CHECK(d < 2); ');
+
+$output = run_sql_command('UPDATE upd_check_skip SET b = -7 WHERE i = 11;');
+ok(is_update_constraint_skipped($output, 'cc2'),
+ 'UPDATE skipped verification for constraint cc2');
+ok(!is_update_constraint_skipped($output, 'cc4'),
+ 'UPDATE does not skipped verification for constraint cc4');
+
+$output = run_sql_command('UPDATE upd_check_skip SET c = 3 WHERE i = 12;');
+ok(is_update_constraint_skipped($output, 'cc1'),
+ 'UPDATE skipped verification for constraint cc1');
+ok(is_update_constraint_skipped($output, 'cc3'),
+ 'UPDATE skipped verification for constraint cc3');
+
+$output = run_sql_command('UPDATE upd_check_skip SET f = 14 WHERE i = 15;');
+ok(is_update_constraint_skipped($output, 'cc4'),
+ 'UPDATE skipped verification for constraint cc4');
+
+run_sql_command(
+ 'CREATE FUNCTION dummy_update_func() RETURNS trigger AS $$
+ BEGIN
+ RETURN NEW;
+ END;
+ $$ LANGUAGE plpgsql;
+
+ CREATE TRIGGER upd_check_skip_row_trig_before
+ BEFORE UPDATE ON upd_check_skip
+ FOR EACH ROW
+ EXECUTE PROCEDURE dummy_update_func(); ');
+
+$output = run_sql_command('UPDATE upd_check_skip SET f = f');
+
+ok(!is_update_constraint_skipped($output, 'cc1'),
+ 'UPDATE does not skipped verification for constraint cc1');
+
+ok(!is_update_constraint_skipped($output, 'cc2'),
+ 'UPDATE does not skipped verification for constraint cc2');
+
+ok(!is_update_constraint_skipped($output, 'cc3'),
+ 'UPDATE does not skipped verification for constraint cc3');
+
+ok(!is_update_constraint_skipped($output, 'cc4'),
+ 'UPDATE does not skipped verification for constraint cc4');
+
+run_sql_command('drop table upd_check_skip;');
+
note "test alter table set not null";
run_sql_command(
--
2.34.1
^ permalink raw reply [nested|flat] 11+ messages in thread
* Re: UPDATE run check constraints for affected columns only
2025-12-01 06:20 UPDATE run check constraints for affected columns only jian he <jian.universality@gmail.com>
2025-12-01 06:33 ` Re: UPDATE run check constraints for affected columns only Tom Lane <tgl@sss.pgh.pa.us>
2025-12-07 15:50 ` Re: UPDATE run check constraints for affected columns only jian he <jian.universality@gmail.com>
@ 2026-01-23 02:09 ` jian he <jian.universality@gmail.com>
2026-03-04 01:04 ` Re: UPDATE run check constraints for affected columns only jian he <jian.universality@gmail.com>
0 siblings, 1 reply; 11+ messages in thread
From: jian he @ 2026-01-23 02:09 UTC (permalink / raw)
To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: pgsql-hackers
hi.
code has been further simplified and is now more neat.
The test is kind of verbose now.
--
jian
https://www.enterprisedb.com/
Attachments:
v3-0001-skip-unnecessary-check-constraint-verification-for-UPDATE.patch (text/x-patch, 10.8K) download
From 04e0850a13199f9709e30b46328a54dbb84aed80 Mon Sep 17 00:00:00 2001
From: jian he <jian.universality@gmail.com>
Date: Fri, 23 Jan 2026 10:00:15 +0800
Subject: [PATCH v3 1/1] skip unnecessary check constraint verification for
UPDATE
In an UPDATE, we can skip verification any columns that do not depend on any
UPDATE target column. But if there is a BEFORE ROW UPDATE trigger, we cannot
skip because the trigger might change more columns.
discussion: https://postgr.es/m/CACJufxEtY1hdLcx=Fhnqp-ERcV1PhbvELG5COy_CZjoEW76ZPQ@mail.gmail.com
context: https://postgr.es/m/1326055327.15293.13.camel%40vanquo.pezone.net
commitfest: https://commitfest.postgresql.org/patch/6270
---
src/backend/commands/copyfrom.c | 2 +-
src/backend/executor/execMain.c | 50 ++++++++++--
src/backend/executor/execReplication.c | 4 +-
src/backend/executor/nodeModifyTable.c | 4 +-
src/include/executor/executor.h | 2 +-
.../test_misc/t/001_constraint_validation.pl | 79 +++++++++++++++++++
6 files changed, 130 insertions(+), 11 deletions(-)
diff --git a/src/backend/commands/copyfrom.c b/src/backend/commands/copyfrom.c
index 25ee20b23db..0e2c3e3a59f 100644
--- a/src/backend/commands/copyfrom.c
+++ b/src/backend/commands/copyfrom.c
@@ -1355,7 +1355,7 @@ CopyFrom(CopyFromState cstate)
*/
if (resultRelInfo->ri_FdwRoutine == NULL &&
resultRelInfo->ri_RelationDesc->rd_att->constr)
- ExecConstraints(resultRelInfo, myslot, estate);
+ ExecConstraints(CMD_INSERT, resultRelInfo, myslot, estate);
/*
* Also check the tuple against the partition constraint, if
diff --git a/src/backend/executor/execMain.c b/src/backend/executor/execMain.c
index bfd3ebc601e..15712bd929a 100644
--- a/src/backend/executor/execMain.c
+++ b/src/backend/executor/execMain.c
@@ -52,6 +52,7 @@
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "nodes/queryjumble.h"
+#include "optimizer/optimizer.h"
#include "parser/parse_relation.h"
#include "pgstat.h"
#include "rewrite/rewriteHandler.h"
@@ -1779,7 +1780,7 @@ ExecutePlan(QueryDesc *queryDesc,
* Returns NULL if OK, else name of failed check constraint
*/
static const char *
-ExecRelCheck(ResultRelInfo *resultRelInfo,
+ExecRelCheck(CmdType cmdtype, ResultRelInfo *resultRelInfo,
TupleTableSlot *slot, EState *estate)
{
Relation rel = resultRelInfo->ri_RelationDesc;
@@ -1804,6 +1805,18 @@ ExecRelCheck(ResultRelInfo *resultRelInfo,
*/
if (resultRelInfo->ri_CheckConstraintExprs == NULL)
{
+ Bitmapset *updatedCols = NULL;
+
+ /*
+ * In an UPDATE, we can skip verification any columns that do not
+ * depend on any UPDATE target column. But if there is a BEFORE ROW
+ * UPDATE trigger, we cannot skip because the trigger might change
+ * more columns.
+ */
+ if (cmdtype == CMD_UPDATE &&
+ !(rel->trigdesc && rel->trigdesc->trig_update_before_row))
+ updatedCols = ExecGetAllUpdatedCols(resultRelInfo, estate);
+
oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
resultRelInfo->ri_CheckConstraintExprs = palloc0_array(ExprState *, ncheck);
for (int i = 0; i < ncheck; i++)
@@ -1816,8 +1829,35 @@ ExecRelCheck(ResultRelInfo *resultRelInfo,
checkconstr = stringToNode(check[i].ccbin);
checkconstr = (Expr *) expand_generated_columns_in_expr((Node *) checkconstr, rel, 1);
- resultRelInfo->ri_CheckConstraintExprs[i] =
- ExecPrepareExpr(checkconstr, estate);
+
+ if (!updatedCols)
+ resultRelInfo->ri_CheckConstraintExprs[i] =
+ ExecPrepareExpr(checkconstr, estate);
+ else
+ {
+ Bitmapset *check_attrs = NULL;
+
+ pull_varattnos((Node *) checkconstr, 1, &check_attrs);
+
+ /*
+ * We can bypass verification of this check constraint if the
+ * expression does not contain a whole-row reference and none
+ * of the referenced attributes overlap with the columns
+ * targeted for update.
+ */
+ if (check_attrs &&
+ !bms_is_member(-FirstLowInvalidHeapAttributeNumber, check_attrs) &&
+ !bms_overlap(check_attrs, updatedCols))
+ {
+ ereport(DEBUG1,
+ errmsg_internal("skipping verification for constraint \"%s\" on table \"%s\"",
+ check[i].ccname,
+ RelationGetRelationName(rel)));
+ }
+ else
+ resultRelInfo->ri_CheckConstraintExprs[i] =
+ ExecPrepareExpr(checkconstr, estate);
+ }
}
MemoryContextSwitchTo(oldContext);
}
@@ -1981,7 +2021,7 @@ ExecPartitionCheckEmitError(ResultRelInfo *resultRelInfo,
* 'resultRelInfo' is the final result relation, after tuple routing.
*/
void
-ExecConstraints(ResultRelInfo *resultRelInfo,
+ExecConstraints(CmdType cmdtype, ResultRelInfo *resultRelInfo,
TupleTableSlot *slot, EState *estate)
{
Relation rel = resultRelInfo->ri_RelationDesc;
@@ -2031,7 +2071,7 @@ ExecConstraints(ResultRelInfo *resultRelInfo,
{
const char *failed;
- if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
+ if ((failed = ExecRelCheck(cmdtype, resultRelInfo, slot, estate)) != NULL)
{
char *val_desc;
Relation orig_rel = rel;
diff --git a/src/backend/executor/execReplication.c b/src/backend/executor/execReplication.c
index 72f2bff7708..436e7043ea4 100644
--- a/src/backend/executor/execReplication.c
+++ b/src/backend/executor/execReplication.c
@@ -836,7 +836,7 @@ ExecSimpleRelationInsert(ResultRelInfo *resultRelInfo,
/* Check the constraints of the tuple */
if (rel->rd_att->constr)
- ExecConstraints(resultRelInfo, slot, estate);
+ ExecConstraints(CMD_INSERT, resultRelInfo, slot, estate);
if (rel->rd_rel->relispartition)
ExecPartitionCheck(resultRelInfo, slot, estate, true);
@@ -933,7 +933,7 @@ ExecSimpleRelationUpdate(ResultRelInfo *resultRelInfo,
/* Check the constraints of the tuple */
if (rel->rd_att->constr)
- ExecConstraints(resultRelInfo, slot, estate);
+ ExecConstraints(CMD_UPDATE, resultRelInfo, slot, estate);
if (rel->rd_rel->relispartition)
ExecPartitionCheck(resultRelInfo, slot, estate, true);
diff --git a/src/backend/executor/nodeModifyTable.c b/src/backend/executor/nodeModifyTable.c
index 7d7411a7056..ba454dbf010 100644
--- a/src/backend/executor/nodeModifyTable.c
+++ b/src/backend/executor/nodeModifyTable.c
@@ -1092,7 +1092,7 @@ ExecInsert(ModifyTableContext *context,
* Check the constraints of the tuple.
*/
if (resultRelationDesc->rd_att->constr)
- ExecConstraints(resultRelInfo, slot, estate);
+ ExecConstraints(CMD_INSERT, resultRelInfo, slot, estate);
/*
* Also check the tuple against the partition constraint, if there is
@@ -2289,7 +2289,7 @@ lreplace:
* have it validate all remaining checks.
*/
if (resultRelationDesc->rd_att->constr)
- ExecConstraints(resultRelInfo, slot, estate);
+ ExecConstraints(CMD_UPDATE, resultRelInfo, slot, estate);
/*
* replace the heap tuple
diff --git a/src/include/executor/executor.h b/src/include/executor/executor.h
index 5929aabc353..42c1729ff51 100644
--- a/src/include/executor/executor.h
+++ b/src/include/executor/executor.h
@@ -257,7 +257,7 @@ extern void InitResultRelInfo(ResultRelInfo *resultRelInfo,
extern ResultRelInfo *ExecGetTriggerResultRel(EState *estate, Oid relid,
ResultRelInfo *rootRelInfo);
extern List *ExecGetAncestorResultRels(EState *estate, ResultRelInfo *resultRelInfo);
-extern void ExecConstraints(ResultRelInfo *resultRelInfo,
+extern void ExecConstraints(CmdType cmdtype, ResultRelInfo *resultRelInfo,
TupleTableSlot *slot, EState *estate);
extern AttrNumber ExecRelGenVirtualNotNull(ResultRelInfo *resultRelInfo,
TupleTableSlot *slot,
diff --git a/src/test/modules/test_misc/t/001_constraint_validation.pl b/src/test/modules/test_misc/t/001_constraint_validation.pl
index 6121c5bcae5..88be546b840 100644
--- a/src/test/modules/test_misc/t/001_constraint_validation.pl
+++ b/src/test/modules/test_misc/t/001_constraint_validation.pl
@@ -40,6 +40,85 @@ sub is_table_verified
my $output;
+note "test UPDATE operation skip enforced constraint vertification";
+# Check whether the run_sql_command output shows that the UPDATE operation
+# skipped constraint verification.
+sub is_update_constraint_skipped
+{
+ my $output = shift;
+ my $constr = shift;
+ return index($output, "DEBUG: skipping verification for constraint \"$constr\"") != -1;
+}
+
+run_sql_command(
+ 'CREATE TABLE upd_check_skip (
+ i int, a int default 11,
+ b int, c int,
+ d int generated always as (b+c) STORED,
+ e int generated always as (i) VIRTUAL) partition by range (i);
+
+ CREATE TABLE upd_check_skip_1(
+ a int default 12, i int,
+ c int, b int,
+ d int generated always as (b+1) STORED,
+ e int generated always as (b - 100) VIRTUAL);
+
+ ALTER TABLE upd_check_skip ATTACH PARTITION upd_check_skip_1 FOR VALUES FROM (0) TO (10);
+ CREATE TABLE upd_check_skip_2 PARTITION OF upd_check_skip FOR VALUES FROM (10) TO (30);
+ INSERT INTO upd_check_skip SELECT g + 8, g, -g-g, g+1 FROM generate_series(0, 7) g;
+ ALTER TABLE upd_check_skip ADD COLUMN f int;
+
+ ALTER TABLE upd_check_skip ADD CONSTRAINT cc1 CHECK(a+b < 1);
+ ALTER TABLE upd_check_skip ADD CONSTRAINT cc2 CHECK(a+c < 100);
+ ALTER TABLE upd_check_skip ADD CONSTRAINT cc3 CHECK(b < 1);
+ ALTER TABLE upd_check_skip ADD CONSTRAINT cc4 CHECK(d < 2); ');
+
+$output = run_sql_command('UPDATE upd_check_skip SET b = -7 WHERE i = 11;');
+ok(is_update_constraint_skipped($output, 'cc2'),
+ 'UPDATE skipped verification for constraint cc2');
+ok(!is_update_constraint_skipped($output, 'cc4'),
+ 'UPDATE does not skipped verification for constraint cc4');
+
+$output = run_sql_command('UPDATE upd_check_skip SET c = 3 WHERE i = 12;');
+ok(is_update_constraint_skipped($output, 'cc1'),
+ 'UPDATE skipped verification for constraint cc1');
+ok(is_update_constraint_skipped($output, 'cc3'),
+ 'UPDATE skipped verification for constraint cc3');
+ok(!is_update_constraint_skipped($output, 'cc4'),
+ 'UPDATE does not skipped verification for constraint cc4');
+
+$output = run_sql_command('UPDATE upd_check_skip SET f = 14 WHERE i = 13;');
+ok(is_update_constraint_skipped($output, 'cc4'),
+ 'UPDATE skipped verification for constraint cc4');
+
+run_sql_command(
+ 'CREATE FUNCTION dummy_update_func() RETURNS trigger AS $$
+ BEGIN
+ RETURN NEW;
+ END;
+ $$ LANGUAGE plpgsql;
+
+ CREATE TRIGGER upd_check_skip_row_trig_before
+ BEFORE UPDATE ON upd_check_skip
+ FOR EACH ROW
+ EXECUTE PROCEDURE dummy_update_func(); ');
+
+$output = run_sql_command('UPDATE upd_check_skip SET f = f');
+
+ok(!is_update_constraint_skipped($output, 'cc1'),
+ 'UPDATE does not skipped verification for constraint cc1');
+
+ok(!is_update_constraint_skipped($output, 'cc2'),
+ 'UPDATE does not skipped verification for constraint cc2');
+
+ok(!is_update_constraint_skipped($output, 'cc3'),
+ 'UPDATE does not skipped verification for constraint cc3');
+
+ok(!is_update_constraint_skipped($output, 'cc4'),
+ 'UPDATE does not skipped verification for constraint cc4');
+
+run_sql_command('drop table upd_check_skip;');
+
note "test alter table set not null";
run_sql_command(
--
2.34.1
^ permalink raw reply [nested|flat] 11+ messages in thread
* Re: UPDATE run check constraints for affected columns only
2025-12-01 06:20 UPDATE run check constraints for affected columns only jian he <jian.universality@gmail.com>
2025-12-01 06:33 ` Re: UPDATE run check constraints for affected columns only Tom Lane <tgl@sss.pgh.pa.us>
2025-12-07 15:50 ` Re: UPDATE run check constraints for affected columns only jian he <jian.universality@gmail.com>
2026-01-23 02:09 ` Re: UPDATE run check constraints for affected columns only jian he <jian.universality@gmail.com>
@ 2026-03-04 01:04 ` jian he <jian.universality@gmail.com>
2026-03-05 03:12 ` Re: UPDATE run check constraints for affected columns only jian he <jian.universality@gmail.com>
0 siblings, 1 reply; 11+ messages in thread
From: jian he @ 2026-03-04 01:04 UTC (permalink / raw)
To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: pgsql-hackers
On Fri, Jan 23, 2026 at 10:09 AM jian he <jian.universality@gmail.com> wrote:
> code has been further simplified and is now more neat.
> The test is kind of verbose now.
>
if (check_attrs &&
!bms_is_member(-FirstLowInvalidHeapAttributeNumber, check_attrs) &&
!bms_overlap(check_attrs, updatedCols))
{
ereport(DEBUG1,
errmsg_internal("skipping verification for constraint
\"%s\" on table \"%s\"",
check[i].ccname,
RelationGetRelationName(rel)));
}
We need tests to reach the above ereport(DEBUG1, branch.
We can use
+SET log_statement to NONE;
+SET client_min_messages TO 'debug1';
to make sure the regress output has the DEBUG1 message.
--
jian
https://www.enterprisedb.com/
Attachments:
v4-0001-skip-unnecessary-check-constraint-verification-for-UPDATE.patch (text/x-patch, 14.6K) download
From d5a8d0d8cdc34b4f10a2bd98dcdaf54c49e99bb2 Mon Sep 17 00:00:00 2001
From: jian he <jian.universality@gmail.com>
Date: Tue, 3 Mar 2026 23:00:59 +0800
Subject: [PATCH v4 1/1] skip unnecessary check constraint verification for
UPDATE
In an UPDATE, we can skip verification any columns that do not depend on any
UPDATE target column. But if there is a BEFORE ROW UPDATE trigger, we cannot
skip because the trigger might change more columns.
discussion: https://postgr.es/m/CACJufxEtY1hdLcx=Fhnqp-ERcV1PhbvELG5COy_CZjoEW76ZPQ@mail.gmail.com
context: https://postgr.es/m/1326055327.15293.13.camel%40vanquo.pezone.net
commitfest: https://commitfest.postgresql.org/patch/6270
---
src/backend/commands/copyfrom.c | 2 +-
src/backend/executor/execMain.c | 49 +++++++++++++++--
src/backend/executor/execReplication.c | 4 +-
src/backend/executor/nodeModifyTable.c | 4 +-
src/include/executor/executor.h | 2 +-
src/test/regress/expected/constraints.out | 65 ++++++++++++++++++++++
src/test/regress/sql/constraints.sql | 67 +++++++++++++++++++++++
7 files changed, 182 insertions(+), 11 deletions(-)
diff --git a/src/backend/commands/copyfrom.c b/src/backend/commands/copyfrom.c
index 2f42f55e229..43354a3c454 100644
--- a/src/backend/commands/copyfrom.c
+++ b/src/backend/commands/copyfrom.c
@@ -1356,7 +1356,7 @@ CopyFrom(CopyFromState cstate)
*/
if (resultRelInfo->ri_FdwRoutine == NULL &&
resultRelInfo->ri_RelationDesc->rd_att->constr)
- ExecConstraints(resultRelInfo, myslot, estate);
+ ExecConstraints(CMD_INSERT, resultRelInfo, myslot, estate);
/*
* Also check the tuple against the partition constraint, if
diff --git a/src/backend/executor/execMain.c b/src/backend/executor/execMain.c
index bfd3ebc601e..e4ca2a0eb6f 100644
--- a/src/backend/executor/execMain.c
+++ b/src/backend/executor/execMain.c
@@ -52,6 +52,7 @@
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "nodes/queryjumble.h"
+#include "optimizer/optimizer.h"
#include "parser/parse_relation.h"
#include "pgstat.h"
#include "rewrite/rewriteHandler.h"
@@ -1779,7 +1780,7 @@ ExecutePlan(QueryDesc *queryDesc,
* Returns NULL if OK, else name of failed check constraint
*/
static const char *
-ExecRelCheck(ResultRelInfo *resultRelInfo,
+ExecRelCheck(CmdType cmdtype, ResultRelInfo *resultRelInfo,
TupleTableSlot *slot, EState *estate)
{
Relation rel = resultRelInfo->ri_RelationDesc;
@@ -1804,6 +1805,18 @@ ExecRelCheck(ResultRelInfo *resultRelInfo,
*/
if (resultRelInfo->ri_CheckConstraintExprs == NULL)
{
+ Bitmapset *updatedCols = NULL;
+
+ /*
+ * During an UPDATE, we can skip CHECK constraint verification if the
+ * constraint expressions do not depend on any of the target columns.
+ * However, if a BEFORE ROW UPDATE trigger is present, we must perform
+ * the verification, as the trigger might modify additional columns.
+ */
+ if (cmdtype == CMD_UPDATE &&
+ !(rel->trigdesc && rel->trigdesc->trig_update_before_row))
+ updatedCols = ExecGetAllUpdatedCols(resultRelInfo, estate);
+
oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
resultRelInfo->ri_CheckConstraintExprs = palloc0_array(ExprState *, ncheck);
for (int i = 0; i < ncheck; i++)
@@ -1816,8 +1829,34 @@ ExecRelCheck(ResultRelInfo *resultRelInfo,
checkconstr = stringToNode(check[i].ccbin);
checkconstr = (Expr *) expand_generated_columns_in_expr((Node *) checkconstr, rel, 1);
- resultRelInfo->ri_CheckConstraintExprs[i] =
- ExecPrepareExpr(checkconstr, estate);
+
+ if (!updatedCols)
+ resultRelInfo->ri_CheckConstraintExprs[i] =
+ ExecPrepareExpr(checkconstr, estate);
+ else
+ {
+ Bitmapset *check_attrs = NULL;
+
+ pull_varattnos((Node *) checkconstr, 1, &check_attrs);
+
+ /*
+ * Check constraint verification cannot be skipped if the
+ * constraint expression contains a whole-row reference, or if
+ * it references any of the UPDATE target columns.
+ */
+ if (check_attrs &&
+ !bms_is_member(-FirstLowInvalidHeapAttributeNumber, check_attrs) &&
+ !bms_overlap(check_attrs, updatedCols))
+ {
+ ereport(DEBUG1,
+ errmsg_internal("skipping verification for constraint \"%s\" on table \"%s\"",
+ check[i].ccname,
+ RelationGetRelationName(rel)));
+ }
+ else
+ resultRelInfo->ri_CheckConstraintExprs[i] =
+ ExecPrepareExpr(checkconstr, estate);
+ }
}
MemoryContextSwitchTo(oldContext);
}
@@ -1981,7 +2020,7 @@ ExecPartitionCheckEmitError(ResultRelInfo *resultRelInfo,
* 'resultRelInfo' is the final result relation, after tuple routing.
*/
void
-ExecConstraints(ResultRelInfo *resultRelInfo,
+ExecConstraints(CmdType cmdtype, ResultRelInfo *resultRelInfo,
TupleTableSlot *slot, EState *estate)
{
Relation rel = resultRelInfo->ri_RelationDesc;
@@ -2031,7 +2070,7 @@ ExecConstraints(ResultRelInfo *resultRelInfo,
{
const char *failed;
- if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
+ if ((failed = ExecRelCheck(cmdtype, resultRelInfo, slot, estate)) != NULL)
{
char *val_desc;
Relation orig_rel = rel;
diff --git a/src/backend/executor/execReplication.c b/src/backend/executor/execReplication.c
index 2497ee7edc5..157a21c1da3 100644
--- a/src/backend/executor/execReplication.c
+++ b/src/backend/executor/execReplication.c
@@ -836,7 +836,7 @@ ExecSimpleRelationInsert(ResultRelInfo *resultRelInfo,
/* Check the constraints of the tuple */
if (rel->rd_att->constr)
- ExecConstraints(resultRelInfo, slot, estate);
+ ExecConstraints(CMD_INSERT, resultRelInfo, slot, estate);
if (rel->rd_rel->relispartition)
ExecPartitionCheck(resultRelInfo, slot, estate, true);
@@ -940,7 +940,7 @@ ExecSimpleRelationUpdate(ResultRelInfo *resultRelInfo,
/* Check the constraints of the tuple */
if (rel->rd_att->constr)
- ExecConstraints(resultRelInfo, slot, estate);
+ ExecConstraints(CMD_UPDATE, resultRelInfo, slot, estate);
if (rel->rd_rel->relispartition)
ExecPartitionCheck(resultRelInfo, slot, estate, true);
diff --git a/src/backend/executor/nodeModifyTable.c b/src/backend/executor/nodeModifyTable.c
index 793c76d4f82..95969dbadb4 100644
--- a/src/backend/executor/nodeModifyTable.c
+++ b/src/backend/executor/nodeModifyTable.c
@@ -1101,7 +1101,7 @@ ExecInsert(ModifyTableContext *context,
* Check the constraints of the tuple.
*/
if (resultRelationDesc->rd_att->constr)
- ExecConstraints(resultRelInfo, slot, estate);
+ ExecConstraints(CMD_INSERT, resultRelInfo, slot, estate);
/*
* Also check the tuple against the partition constraint, if there is
@@ -2316,7 +2316,7 @@ lreplace:
* have it validate all remaining checks.
*/
if (resultRelationDesc->rd_att->constr)
- ExecConstraints(resultRelInfo, slot, estate);
+ ExecConstraints(CMD_UPDATE, resultRelInfo, slot, estate);
/*
* replace the heap tuple
diff --git a/src/include/executor/executor.h b/src/include/executor/executor.h
index d46ba59895d..0b1438d3f7c 100644
--- a/src/include/executor/executor.h
+++ b/src/include/executor/executor.h
@@ -257,7 +257,7 @@ extern void InitResultRelInfo(ResultRelInfo *resultRelInfo,
extern ResultRelInfo *ExecGetTriggerResultRel(EState *estate, Oid relid,
ResultRelInfo *rootRelInfo);
extern List *ExecGetAncestorResultRels(EState *estate, ResultRelInfo *resultRelInfo);
-extern void ExecConstraints(ResultRelInfo *resultRelInfo,
+extern void ExecConstraints(CmdType cmdtype, ResultRelInfo *resultRelInfo,
TupleTableSlot *slot, EState *estate);
extern AttrNumber ExecRelGenVirtualNotNull(ResultRelInfo *resultRelInfo,
TupleTableSlot *slot,
diff --git a/src/test/regress/expected/constraints.out b/src/test/regress/expected/constraints.out
index a6fa9cacb72..0fbb6b16fd7 100644
--- a/src/test/regress/expected/constraints.out
+++ b/src/test/regress/expected/constraints.out
@@ -1721,3 +1721,68 @@ COMMENT ON CONSTRAINT inv_ck ON DOMAIN constraint_comments_dom IS 'comment on in
CREATE TABLE regress_notnull1 (a integer);
CREATE TABLE regress_notnull2 () INHERITS (regress_notnull1);
ALTER TABLE ONLY regress_notnull2 ALTER COLUMN a SET NOT NULL;
+CREATE FUNCTION dummy_update_func_in_constr() RETURNS trigger AS $$
+BEGIN
+RETURN NEW;
+END;
+$$ LANGUAGE plpgsql;
+CREATE TABLE upd_check_skip0 (a int, CONSTRAINT cc CHECK (upd_check_skip0 IS NOT NULL));
+INSERT INTO upd_check_skip0 VALUES (1);
+CREATE TABLE upd_check_skip (
+ i int, a int DEFAULT 11, b int, c int,
+ d int GENERATED ALWAYS AS (b + c) STORED,
+ e int GENERATED ALWAYS AS (i) VIRTUAL) PARTITION BY RANGE (i);
+CREATE TABLE upd_check_skip_1 (
+ a int DEFAULT 12, i int, c int, b int,
+ d int GENERATED ALWAYS AS (b + 1) STORED,
+ e int GENERATED ALWAYS AS (b - 100) VIRTUAL);
+ALTER TABLE upd_check_skip ATTACH PARTITION upd_check_skip_1 FOR VALUES FROM (0) TO (10);
+CREATE TABLE upd_check_skip_2 PARTITION OF upd_check_skip FOR VALUES FROM (10) TO (30);
+INSERT INTO upd_check_skip SELECT g + 8, g, -g-g, g+1 FROM generate_series(0, 6) g;
+ALTER TABLE upd_check_skip ADD COLUMN f int;
+ALTER TABLE upd_check_skip ADD CONSTRAINT cc1 CHECK (a + b < 1);
+ALTER TABLE upd_check_skip ADD CONSTRAINT cc2 CHECK (a + c < 100);
+ALTER TABLE upd_check_skip ADD CONSTRAINT cc3 CHECK (b < 1);
+ALTER TABLE upd_check_skip ADD CONSTRAINT cc4 CHECK (d < 2);
+SET log_statement to NONE;
+SET client_min_messages TO 'debug1';
+-- Check constraint expression contain whole-row reference therefore cannot be
+-- skipped
+UPDATE upd_check_skip0 SET a = 2;
+-- Skipping verification for check constraints cc2, since cc2 check expression
+-- does not reference column b
+UPDATE upd_check_skip SET b = null WHERE i = 8 OR i = 10;
+DEBUG: skipping verification for constraint "cc2" on table "upd_check_skip_1"
+DEBUG: skipping verification for constraint "cc2" on table "upd_check_skip_2"
+-- Skipping verification for check constraints cc1 and cc3 because column c is
+-- not referenced in their expressions. However, in table upd_check_skip_2, the
+-- generated column d references column c, thus check constraint cc4 on
+-- upd_check_skip_2 cannot be skipped
+UPDATE upd_check_skip SET c = 3 WHERE i = 12 OR i = 8;
+DEBUG: skipping verification for constraint "cc1" on table "upd_check_skip_1"
+DEBUG: skipping verification for constraint "cc3" on table "upd_check_skip_1"
+DEBUG: skipping verification for constraint "cc4" on table "upd_check_skip_1"
+DEBUG: skipping verification for constraint "cc1" on table "upd_check_skip_2"
+DEBUG: skipping verification for constraint "cc3" on table "upd_check_skip_2"
+-- Skipping verification for all check constraints since column f is not
+-- referenced in any check constraint expression
+UPDATE upd_check_skip SET f = 14 WHERE i = 13;
+DEBUG: skipping verification for constraint "cc1" on table "upd_check_skip_2"
+DEBUG: skipping verification for constraint "cc2" on table "upd_check_skip_2"
+DEBUG: skipping verification for constraint "cc3" on table "upd_check_skip_2"
+DEBUG: skipping verification for constraint "cc4" on table "upd_check_skip_2"
+CREATE TRIGGER upd_check_skip_row_trig_before
+BEFORE UPDATE ON upd_check_skip
+FOR EACH ROW
+EXECUTE PROCEDURE dummy_update_func_in_constr();
+-- Cannot skip check constraint validation for this UPDATE because a trigger
+-- prevents it
+UPDATE upd_check_skip SET a = NULL, b = NULL, c = NULL, i = NULL;
+ERROR: no partition of relation "upd_check_skip" found for row
+DETAIL: Partition key of the failing row contains (i) = (null).
+DROP TRIGGER upd_check_skip_row_trig_before ON upd_check_skip;
+DROP FUNCTION dummy_update_func_in_constr;
+DROP TABLE upd_check_skip0;
+DROP TABLE upd_check_skip;
+RESET client_min_messages;
+RESET log_statement;
diff --git a/src/test/regress/sql/constraints.sql b/src/test/regress/sql/constraints.sql
index b7f6efdd814..1706bf57f57 100644
--- a/src/test/regress/sql/constraints.sql
+++ b/src/test/regress/sql/constraints.sql
@@ -1062,3 +1062,70 @@ COMMENT ON CONSTRAINT inv_ck ON DOMAIN constraint_comments_dom IS 'comment on in
CREATE TABLE regress_notnull1 (a integer);
CREATE TABLE regress_notnull2 () INHERITS (regress_notnull1);
ALTER TABLE ONLY regress_notnull2 ALTER COLUMN a SET NOT NULL;
+
+CREATE FUNCTION dummy_update_func_in_constr() RETURNS trigger AS $$
+BEGIN
+RETURN NEW;
+END;
+$$ LANGUAGE plpgsql;
+
+CREATE TABLE upd_check_skip0 (a int, CONSTRAINT cc CHECK (upd_check_skip0 IS NOT NULL));
+INSERT INTO upd_check_skip0 VALUES (1);
+
+CREATE TABLE upd_check_skip (
+ i int, a int DEFAULT 11, b int, c int,
+ d int GENERATED ALWAYS AS (b + c) STORED,
+ e int GENERATED ALWAYS AS (i) VIRTUAL) PARTITION BY RANGE (i);
+
+CREATE TABLE upd_check_skip_1 (
+ a int DEFAULT 12, i int, c int, b int,
+ d int GENERATED ALWAYS AS (b + 1) STORED,
+ e int GENERATED ALWAYS AS (b - 100) VIRTUAL);
+
+ALTER TABLE upd_check_skip ATTACH PARTITION upd_check_skip_1 FOR VALUES FROM (0) TO (10);
+CREATE TABLE upd_check_skip_2 PARTITION OF upd_check_skip FOR VALUES FROM (10) TO (30);
+INSERT INTO upd_check_skip SELECT g + 8, g, -g-g, g+1 FROM generate_series(0, 6) g;
+ALTER TABLE upd_check_skip ADD COLUMN f int;
+
+ALTER TABLE upd_check_skip ADD CONSTRAINT cc1 CHECK (a + b < 1);
+ALTER TABLE upd_check_skip ADD CONSTRAINT cc2 CHECK (a + c < 100);
+ALTER TABLE upd_check_skip ADD CONSTRAINT cc3 CHECK (b < 1);
+ALTER TABLE upd_check_skip ADD CONSTRAINT cc4 CHECK (d < 2);
+
+SET log_statement to NONE;
+SET client_min_messages TO 'debug1';
+
+-- Check constraint expression contain whole-row reference therefore cannot be
+-- skipped
+UPDATE upd_check_skip0 SET a = 2;
+
+-- Skipping verification for check constraints cc2, since cc2 check expression
+-- does not reference column b
+UPDATE upd_check_skip SET b = null WHERE i = 8 OR i = 10;
+
+-- Skipping verification for check constraints cc1 and cc3 because column c is
+-- not referenced in their expressions. However, in table upd_check_skip_2, the
+-- generated column d references column c, thus check constraint cc4 on
+-- upd_check_skip_2 cannot be skipped
+UPDATE upd_check_skip SET c = 3 WHERE i = 12 OR i = 8;
+
+-- Skipping verification for all check constraints since column f is not
+-- referenced in any check constraint expression
+UPDATE upd_check_skip SET f = 14 WHERE i = 13;
+
+CREATE TRIGGER upd_check_skip_row_trig_before
+BEFORE UPDATE ON upd_check_skip
+FOR EACH ROW
+EXECUTE PROCEDURE dummy_update_func_in_constr();
+
+-- Cannot skip check constraint validation for this UPDATE because a trigger
+-- prevents it
+UPDATE upd_check_skip SET a = NULL, b = NULL, c = NULL, i = NULL;
+
+DROP TRIGGER upd_check_skip_row_trig_before ON upd_check_skip;
+DROP FUNCTION dummy_update_func_in_constr;
+DROP TABLE upd_check_skip0;
+DROP TABLE upd_check_skip;
+
+RESET client_min_messages;
+RESET log_statement;
--
2.34.1
^ permalink raw reply [nested|flat] 11+ messages in thread
* Re: UPDATE run check constraints for affected columns only
2025-12-01 06:20 UPDATE run check constraints for affected columns only jian he <jian.universality@gmail.com>
2025-12-01 06:33 ` Re: UPDATE run check constraints for affected columns only Tom Lane <tgl@sss.pgh.pa.us>
2025-12-07 15:50 ` Re: UPDATE run check constraints for affected columns only jian he <jian.universality@gmail.com>
2026-01-23 02:09 ` Re: UPDATE run check constraints for affected columns only jian he <jian.universality@gmail.com>
2026-03-04 01:04 ` Re: UPDATE run check constraints for affected columns only jian he <jian.universality@gmail.com>
@ 2026-03-05 03:12 ` jian he <jian.universality@gmail.com>
2026-03-06 02:17 ` Re: UPDATE run check constraints for affected columns only jian he <jian.universality@gmail.com>
0 siblings, 1 reply; 11+ messages in thread
From: jian he @ 2026-03-05 03:12 UTC (permalink / raw)
To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: pgsql-hackers
Thank to Jacob Champion for the off-list review.
Now ExecRelCheck looks much neater.
--
jian
https://www.enterprisedb.com/
Attachments:
v5-0001-skip-unnecessary-check-constraint-verification-for-UPDATE.patch (text/x-patch, 14.9K) download
From 9c0764928bbf622057b25e4c11b98e73c13231bf Mon Sep 17 00:00:00 2001
From: jian he <jian.universality@gmail.com>
Date: Thu, 5 Mar 2026 11:09:14 +0800
Subject: [PATCH v5 1/1] skip unnecessary check constraint verification for
UPDATE
In an UPDATE, we can skip verification of any columns that do not depend on any
UPDATE target column. But if there is a BEFORE ROW UPDATE trigger, we cannot
skip because the trigger may modifies more column.
Author: jian he <jian.universality@gmail.com>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: li carol <carol.li2025@outlook.com>
Reviewed-by: Jacob Champion <jacob.champion@enterprisedb.com>
Discussion: https://postgr.es/m/CACJufxEtY1hdLcx=Fhnqp-ERcV1PhbvELG5COy_CZjoEW76ZPQ@mail.gmail.com
context: https://postgr.es/m/1326055327.15293.13.camel%40vanquo.pezone.net
commitfest: https://commitfest.postgresql.org/patch/6270
---
src/backend/commands/copyfrom.c | 2 +-
src/backend/executor/execMain.c | 46 +++++++++++++-
src/backend/executor/execReplication.c | 4 +-
src/backend/executor/nodeModifyTable.c | 4 +-
src/include/executor/executor.h | 2 +-
src/test/regress/expected/constraints.out | 75 +++++++++++++++++++++++
src/test/regress/sql/constraints.sql | 67 ++++++++++++++++++++
7 files changed, 191 insertions(+), 9 deletions(-)
diff --git a/src/backend/commands/copyfrom.c b/src/backend/commands/copyfrom.c
index 2f42f55e229..43354a3c454 100644
--- a/src/backend/commands/copyfrom.c
+++ b/src/backend/commands/copyfrom.c
@@ -1356,7 +1356,7 @@ CopyFrom(CopyFromState cstate)
*/
if (resultRelInfo->ri_FdwRoutine == NULL &&
resultRelInfo->ri_RelationDesc->rd_att->constr)
- ExecConstraints(resultRelInfo, myslot, estate);
+ ExecConstraints(CMD_INSERT, resultRelInfo, myslot, estate);
/*
* Also check the tuple against the partition constraint, if
diff --git a/src/backend/executor/execMain.c b/src/backend/executor/execMain.c
index bfd3ebc601e..b10de35aa6a 100644
--- a/src/backend/executor/execMain.c
+++ b/src/backend/executor/execMain.c
@@ -52,6 +52,7 @@
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "nodes/queryjumble.h"
+#include "optimizer/optimizer.h"
#include "parser/parse_relation.h"
#include "pgstat.h"
#include "rewrite/rewriteHandler.h"
@@ -1779,7 +1780,7 @@ ExecutePlan(QueryDesc *queryDesc,
* Returns NULL if OK, else name of failed check constraint
*/
static const char *
-ExecRelCheck(ResultRelInfo *resultRelInfo,
+ExecRelCheck(CmdType cmdtype, ResultRelInfo *resultRelInfo,
TupleTableSlot *slot, EState *estate)
{
Relation rel = resultRelInfo->ri_RelationDesc;
@@ -1804,6 +1805,17 @@ ExecRelCheck(ResultRelInfo *resultRelInfo,
*/
if (resultRelInfo->ri_CheckConstraintExprs == NULL)
{
+ Bitmapset *updatedCols = NULL;
+
+ /*
+ * During an UPDATE, we may skip CHECK constraint verification.
+ * However, if a BEFORE ROW UPDATE trigger is present, we must perform
+ * the verification, as the trigger might modify additional columns.
+ */
+ if (cmdtype == CMD_UPDATE &&
+ !(rel->trigdesc && rel->trigdesc->trig_update_before_row))
+ updatedCols = ExecGetAllUpdatedCols(resultRelInfo, estate);
+
oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
resultRelInfo->ri_CheckConstraintExprs = palloc0_array(ExprState *, ncheck);
for (int i = 0; i < ncheck; i++)
@@ -1816,6 +1828,34 @@ ExecRelCheck(ResultRelInfo *resultRelInfo,
checkconstr = stringToNode(check[i].ccbin);
checkconstr = (Expr *) expand_generated_columns_in_expr((Node *) checkconstr, rel, 1);
+
+ if (updatedCols)
+ {
+ Bitmapset *check_attrs = NULL;
+
+ pull_varattnos((Node *) checkconstr, 1, &check_attrs);
+
+ /*
+ * Skip check constraint verification during an UPDATE if the
+ * constraint expression references columns, contains no
+ * whole-row references, and does not reference any of the
+ * columns being updated.
+ */
+ if (check_attrs &&
+ !bms_is_member(0 - FirstLowInvalidHeapAttributeNumber, check_attrs) &&
+ !bms_overlap(check_attrs, updatedCols))
+ {
+ ereport(DEBUG1,
+ errmsg_internal("skipping verification for constraint \"%s\" on table \"%s\"",
+ check[i].ccname,
+ RelationGetRelationName(rel)));
+
+ bms_free(check_attrs);
+
+ continue;
+ }
+ }
+
resultRelInfo->ri_CheckConstraintExprs[i] =
ExecPrepareExpr(checkconstr, estate);
}
@@ -1981,7 +2021,7 @@ ExecPartitionCheckEmitError(ResultRelInfo *resultRelInfo,
* 'resultRelInfo' is the final result relation, after tuple routing.
*/
void
-ExecConstraints(ResultRelInfo *resultRelInfo,
+ExecConstraints(CmdType cmdtype, ResultRelInfo *resultRelInfo,
TupleTableSlot *slot, EState *estate)
{
Relation rel = resultRelInfo->ri_RelationDesc;
@@ -2031,7 +2071,7 @@ ExecConstraints(ResultRelInfo *resultRelInfo,
{
const char *failed;
- if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
+ if ((failed = ExecRelCheck(cmdtype, resultRelInfo, slot, estate)) != NULL)
{
char *val_desc;
Relation orig_rel = rel;
diff --git a/src/backend/executor/execReplication.c b/src/backend/executor/execReplication.c
index 2497ee7edc5..157a21c1da3 100644
--- a/src/backend/executor/execReplication.c
+++ b/src/backend/executor/execReplication.c
@@ -836,7 +836,7 @@ ExecSimpleRelationInsert(ResultRelInfo *resultRelInfo,
/* Check the constraints of the tuple */
if (rel->rd_att->constr)
- ExecConstraints(resultRelInfo, slot, estate);
+ ExecConstraints(CMD_INSERT, resultRelInfo, slot, estate);
if (rel->rd_rel->relispartition)
ExecPartitionCheck(resultRelInfo, slot, estate, true);
@@ -940,7 +940,7 @@ ExecSimpleRelationUpdate(ResultRelInfo *resultRelInfo,
/* Check the constraints of the tuple */
if (rel->rd_att->constr)
- ExecConstraints(resultRelInfo, slot, estate);
+ ExecConstraints(CMD_UPDATE, resultRelInfo, slot, estate);
if (rel->rd_rel->relispartition)
ExecPartitionCheck(resultRelInfo, slot, estate, true);
diff --git a/src/backend/executor/nodeModifyTable.c b/src/backend/executor/nodeModifyTable.c
index 793c76d4f82..95969dbadb4 100644
--- a/src/backend/executor/nodeModifyTable.c
+++ b/src/backend/executor/nodeModifyTable.c
@@ -1101,7 +1101,7 @@ ExecInsert(ModifyTableContext *context,
* Check the constraints of the tuple.
*/
if (resultRelationDesc->rd_att->constr)
- ExecConstraints(resultRelInfo, slot, estate);
+ ExecConstraints(CMD_INSERT, resultRelInfo, slot, estate);
/*
* Also check the tuple against the partition constraint, if there is
@@ -2316,7 +2316,7 @@ lreplace:
* have it validate all remaining checks.
*/
if (resultRelationDesc->rd_att->constr)
- ExecConstraints(resultRelInfo, slot, estate);
+ ExecConstraints(CMD_UPDATE, resultRelInfo, slot, estate);
/*
* replace the heap tuple
diff --git a/src/include/executor/executor.h b/src/include/executor/executor.h
index d46ba59895d..0b1438d3f7c 100644
--- a/src/include/executor/executor.h
+++ b/src/include/executor/executor.h
@@ -257,7 +257,7 @@ extern void InitResultRelInfo(ResultRelInfo *resultRelInfo,
extern ResultRelInfo *ExecGetTriggerResultRel(EState *estate, Oid relid,
ResultRelInfo *rootRelInfo);
extern List *ExecGetAncestorResultRels(EState *estate, ResultRelInfo *resultRelInfo);
-extern void ExecConstraints(ResultRelInfo *resultRelInfo,
+extern void ExecConstraints(CmdType cmdtype, ResultRelInfo *resultRelInfo,
TupleTableSlot *slot, EState *estate);
extern AttrNumber ExecRelGenVirtualNotNull(ResultRelInfo *resultRelInfo,
TupleTableSlot *slot,
diff --git a/src/test/regress/expected/constraints.out b/src/test/regress/expected/constraints.out
index a6fa9cacb72..5268827b1ef 100644
--- a/src/test/regress/expected/constraints.out
+++ b/src/test/regress/expected/constraints.out
@@ -1721,3 +1721,78 @@ COMMENT ON CONSTRAINT inv_ck ON DOMAIN constraint_comments_dom IS 'comment on in
CREATE TABLE regress_notnull1 (a integer);
CREATE TABLE regress_notnull2 () INHERITS (regress_notnull1);
ALTER TABLE ONLY regress_notnull2 ALTER COLUMN a SET NOT NULL;
+CREATE FUNCTION dummy_update_func_in_constr() RETURNS trigger AS $$
+BEGIN
+RETURN NEW;
+END;
+$$ LANGUAGE plpgsql;
+CREATE TABLE upd_check_skip0 (a int, CONSTRAINT cc CHECK (upd_check_skip0 IS NOT NULL));
+INSERT INTO upd_check_skip0 VALUES (1);
+CREATE TABLE upd_check_skip (
+ i int, a int DEFAULT 11, b int, c int,
+ d int GENERATED ALWAYS AS (b + c) STORED,
+ e int GENERATED ALWAYS AS (i) VIRTUAL) PARTITION BY RANGE (i);
+CREATE TABLE upd_check_skip_1 (
+ a int DEFAULT 12, i int, c int, b int,
+ d int GENERATED ALWAYS AS (b + 1) STORED,
+ e int GENERATED ALWAYS AS (b - 100) VIRTUAL);
+ALTER TABLE upd_check_skip ATTACH PARTITION upd_check_skip_1 FOR VALUES FROM (0) TO (10);
+CREATE TABLE upd_check_skip_2 PARTITION OF upd_check_skip FOR VALUES FROM (10) TO (30);
+INSERT INTO upd_check_skip SELECT g + 8, g, -g-g, g+1 FROM generate_series(0, 4) g;
+ALTER TABLE upd_check_skip ADD COLUMN f int;
+ALTER TABLE upd_check_skip ADD CONSTRAINT cc1 CHECK (a + b < 1);
+ALTER TABLE upd_check_skip ADD CONSTRAINT cc2 CHECK (a + c < 100);
+ALTER TABLE upd_check_skip ADD CONSTRAINT cc3 CHECK (b < 1);
+ALTER TABLE upd_check_skip ADD CONSTRAINT cc4 CHECK (d < 2);
+ALTER TABLE upd_check_skip ADD CONSTRAINT cc5 CHECK (e < 20);
+SELECT * FROM upd_check_skip ORDER BY i;
+ i | a | b | c | d | e | f
+----+---+----+---+----+----+---
+ 8 | 0 | 0 | 1 | 1 | 8 |
+ 9 | 1 | -2 | 2 | -1 | 9 |
+ 10 | 2 | -4 | 3 | -1 | 10 |
+ 11 | 3 | -6 | 4 | -2 | 11 |
+ 12 | 4 | -8 | 5 | -3 | 12 |
+(5 rows)
+
+SET log_statement to NONE;
+SET client_min_messages TO 'debug1';
+-- constraint cc contain whole-row reference therefore cannot be skipped
+UPDATE upd_check_skip0 SET a = 2;
+-- error, but cc2 on upd_check_skip_1 still being skipped
+UPDATE upd_check_skip SET b = 11 WHERE i = 8;
+DEBUG: skipping verification for constraint "cc2" on table "upd_check_skip_1"
+ERROR: new row for relation "upd_check_skip_1" violates check constraint "cc1"
+DETAIL: Failing row contains (8, 0, 11, 1, 12, virtual, null).
+-- Skipping verification for constraint cc1, cc3, cc5 because column c is not
+-- being referenced. However, in table upd_check_skip_2, the generated column d
+-- references column c, therefore constraint cc4 on upd_check_skip_2 cannot be skipped
+UPDATE upd_check_skip SET c = 3 WHERE i = 11 OR i = 8;
+DEBUG: skipping verification for constraint "cc1" on table "upd_check_skip_1"
+DEBUG: skipping verification for constraint "cc3" on table "upd_check_skip_1"
+DEBUG: skipping verification for constraint "cc4" on table "upd_check_skip_1"
+DEBUG: skipping verification for constraint "cc5" on table "upd_check_skip_1"
+DEBUG: skipping verification for constraint "cc1" on table "upd_check_skip_2"
+DEBUG: skipping verification for constraint "cc3" on table "upd_check_skip_2"
+DEBUG: skipping verification for constraint "cc5" on table "upd_check_skip_2"
+-- Column f is not referenced by any constraints, all constraint checks are skipped
+UPDATE upd_check_skip SET f = 14 WHERE i = 12;
+DEBUG: skipping verification for constraint "cc1" on table "upd_check_skip_2"
+DEBUG: skipping verification for constraint "cc2" on table "upd_check_skip_2"
+DEBUG: skipping verification for constraint "cc3" on table "upd_check_skip_2"
+DEBUG: skipping verification for constraint "cc4" on table "upd_check_skip_2"
+DEBUG: skipping verification for constraint "cc5" on table "upd_check_skip_2"
+-- cross partition update, cannot skip
+UPDATE upd_check_skip SET f = 14, i = 9 WHERE i = 12;
+CREATE TRIGGER upd_check_skip_row_trig_before
+BEFORE UPDATE ON upd_check_skip
+FOR EACH ROW
+EXECUTE PROCEDURE dummy_update_func_in_constr();
+-- BEFORE ROW UPDATE TRIGGER is there, cannot skip
+UPDATE upd_check_skip SET a = NULL, b = NULL, c = NULL;
+DROP TRIGGER upd_check_skip_row_trig_before ON upd_check_skip;
+DROP FUNCTION dummy_update_func_in_constr;
+DROP TABLE upd_check_skip0;
+DROP TABLE upd_check_skip;
+RESET client_min_messages;
+RESET log_statement;
diff --git a/src/test/regress/sql/constraints.sql b/src/test/regress/sql/constraints.sql
index b7f6efdd814..d22e251503e 100644
--- a/src/test/regress/sql/constraints.sql
+++ b/src/test/regress/sql/constraints.sql
@@ -1062,3 +1062,70 @@ COMMENT ON CONSTRAINT inv_ck ON DOMAIN constraint_comments_dom IS 'comment on in
CREATE TABLE regress_notnull1 (a integer);
CREATE TABLE regress_notnull2 () INHERITS (regress_notnull1);
ALTER TABLE ONLY regress_notnull2 ALTER COLUMN a SET NOT NULL;
+
+CREATE FUNCTION dummy_update_func_in_constr() RETURNS trigger AS $$
+BEGIN
+RETURN NEW;
+END;
+$$ LANGUAGE plpgsql;
+
+CREATE TABLE upd_check_skip0 (a int, CONSTRAINT cc CHECK (upd_check_skip0 IS NOT NULL));
+INSERT INTO upd_check_skip0 VALUES (1);
+
+CREATE TABLE upd_check_skip (
+ i int, a int DEFAULT 11, b int, c int,
+ d int GENERATED ALWAYS AS (b + c) STORED,
+ e int GENERATED ALWAYS AS (i) VIRTUAL) PARTITION BY RANGE (i);
+
+CREATE TABLE upd_check_skip_1 (
+ a int DEFAULT 12, i int, c int, b int,
+ d int GENERATED ALWAYS AS (b + 1) STORED,
+ e int GENERATED ALWAYS AS (b - 100) VIRTUAL);
+
+ALTER TABLE upd_check_skip ATTACH PARTITION upd_check_skip_1 FOR VALUES FROM (0) TO (10);
+CREATE TABLE upd_check_skip_2 PARTITION OF upd_check_skip FOR VALUES FROM (10) TO (30);
+INSERT INTO upd_check_skip SELECT g + 8, g, -g-g, g+1 FROM generate_series(0, 4) g;
+ALTER TABLE upd_check_skip ADD COLUMN f int;
+
+ALTER TABLE upd_check_skip ADD CONSTRAINT cc1 CHECK (a + b < 1);
+ALTER TABLE upd_check_skip ADD CONSTRAINT cc2 CHECK (a + c < 100);
+ALTER TABLE upd_check_skip ADD CONSTRAINT cc3 CHECK (b < 1);
+ALTER TABLE upd_check_skip ADD CONSTRAINT cc4 CHECK (d < 2);
+ALTER TABLE upd_check_skip ADD CONSTRAINT cc5 CHECK (e < 20);
+
+SELECT * FROM upd_check_skip ORDER BY i;
+
+SET log_statement to NONE;
+SET client_min_messages TO 'debug1';
+
+-- constraint cc contain whole-row reference therefore cannot be skipped
+UPDATE upd_check_skip0 SET a = 2;
+
+-- error, but cc2 on upd_check_skip_1 still being skipped
+UPDATE upd_check_skip SET b = 11 WHERE i = 8;
+
+-- Skipping verification for constraint cc1, cc3, cc5 because column c is not
+-- being referenced. However, in table upd_check_skip_2, the generated column d
+-- references column c, therefore constraint cc4 on upd_check_skip_2 cannot be skipped
+UPDATE upd_check_skip SET c = 3 WHERE i = 11 OR i = 8;
+
+-- Column f is not referenced by any constraints, all constraint checks are skipped
+UPDATE upd_check_skip SET f = 14 WHERE i = 12;
+-- cross partition update, cannot skip
+UPDATE upd_check_skip SET f = 14, i = 9 WHERE i = 12;
+
+CREATE TRIGGER upd_check_skip_row_trig_before
+BEFORE UPDATE ON upd_check_skip
+FOR EACH ROW
+EXECUTE PROCEDURE dummy_update_func_in_constr();
+
+-- BEFORE ROW UPDATE TRIGGER is there, cannot skip
+UPDATE upd_check_skip SET a = NULL, b = NULL, c = NULL;
+
+DROP TRIGGER upd_check_skip_row_trig_before ON upd_check_skip;
+DROP FUNCTION dummy_update_func_in_constr;
+DROP TABLE upd_check_skip0;
+DROP TABLE upd_check_skip;
+
+RESET client_min_messages;
+RESET log_statement;
--
2.34.1
^ permalink raw reply [nested|flat] 11+ messages in thread
* Re: UPDATE run check constraints for affected columns only
2025-12-01 06:20 UPDATE run check constraints for affected columns only jian he <jian.universality@gmail.com>
2025-12-01 06:33 ` Re: UPDATE run check constraints for affected columns only Tom Lane <tgl@sss.pgh.pa.us>
2025-12-07 15:50 ` Re: UPDATE run check constraints for affected columns only jian he <jian.universality@gmail.com>
2026-01-23 02:09 ` Re: UPDATE run check constraints for affected columns only jian he <jian.universality@gmail.com>
2026-03-04 01:04 ` Re: UPDATE run check constraints for affected columns only jian he <jian.universality@gmail.com>
2026-03-05 03:12 ` Re: UPDATE run check constraints for affected columns only jian he <jian.universality@gmail.com>
@ 2026-03-06 02:17 ` jian he <jian.universality@gmail.com>
2026-03-06 16:10 ` Re: UPDATE run check constraints for affected columns only Florin Irion <irionr@gmail.com>
0 siblings, 1 reply; 11+ messages in thread
From: jian he @ 2026-03-06 02:17 UTC (permalink / raw)
To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: pgsql-hackers
hi.
We cache ri_CheckConstraintExprs in ExecConstraints and must initialize them all
if different actions like INSERT and UPDATE, happen together in a query.
Both INSERT and UPDATE need to use these ri_CheckConstraintExprs.
Invoke INSERT AND UPDATE together can happen within MERGE command. We confirm
it's a MERGE operation by checking that resultRelInfo->ri_MergeActions is not
NIL. See ExecMergeNotMatched and ExecMergeMatched.
For cross-partition updates (ExecCrossPartitionUpdate), the operation splits
into an INSERT and DELETE, we can treat it as a single action.
--
jian
https://www.enterprisedb.com/
Attachments:
v6-0001-skip-unnecessary-check-constraint-verification-for-UPDATE.patch (text/x-patch, 16.3K) download
From 88e8da4782a7cee9e07fee256e09494267ef60b6 Mon Sep 17 00:00:00 2001
From: jian he <jian.universality@gmail.com>
Date: Fri, 6 Mar 2026 10:15:49 +0800
Subject: [PATCH v6 1/1] skip unnecessary check constraint verification for
UPDATE
In an UPDATE, we can skip verification of any columns that do not depend on any
UPDATE target column. But if there is a BEFORE ROW UPDATE trigger, we cannot
skip because the trigger may modifies more column.
We cache ri_CheckConstraintExprs in ExecConstraints and must initialize them all
if different actions like INSERT and UPDATE, happen together in a query.
Because both INSERT and UPDATE need to use these ri_CheckConstraintExprs.
Invoke INSERT AND UPDATE together will happen within MERGE command. We confirm
it's a MERGE operation by checking that resultRelInfo->ri_MergeActions is not
NIL. See ExecMergeNotMatched and ExecMergeMatched.
For cross-partition updates (ExecCrossPartitionUpdate), the operation splits
into an INSERT and DELETE, we can treat it as a single action.
Author: jian he <jian.universality@gmail.com>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: li carol <carol.li2025@outlook.com>
Reviewed-by: Jacob Champion <jacob.champion@enterprisedb.com>
Reviewed-by: Florin
Discussion: https://postgr.es/m/CACJufxEtY1hdLcx=Fhnqp-ERcV1PhbvELG5COy_CZjoEW76ZPQ@mail.gmail.com
context: https://postgr.es/m/1326055327.15293.13.camel%40vanquo.pezone.net
commitfest: https://commitfest.postgresql.org/patch/6270
---
src/backend/commands/copyfrom.c | 2 +-
src/backend/executor/execMain.c | 54 ++++++++++++++-
src/backend/executor/execReplication.c | 4 +-
src/backend/executor/nodeModifyTable.c | 4 +-
src/include/executor/executor.h | 2 +-
src/test/regress/expected/constraints.out | 80 +++++++++++++++++++++++
src/test/regress/sql/constraints.sql | 73 +++++++++++++++++++++
7 files changed, 210 insertions(+), 9 deletions(-)
diff --git a/src/backend/commands/copyfrom.c b/src/backend/commands/copyfrom.c
index 2f42f55e229..43354a3c454 100644
--- a/src/backend/commands/copyfrom.c
+++ b/src/backend/commands/copyfrom.c
@@ -1356,7 +1356,7 @@ CopyFrom(CopyFromState cstate)
*/
if (resultRelInfo->ri_FdwRoutine == NULL &&
resultRelInfo->ri_RelationDesc->rd_att->constr)
- ExecConstraints(resultRelInfo, myslot, estate);
+ ExecConstraints(CMD_INSERT, resultRelInfo, myslot, estate);
/*
* Also check the tuple against the partition constraint, if
diff --git a/src/backend/executor/execMain.c b/src/backend/executor/execMain.c
index bfd3ebc601e..851073f2bc0 100644
--- a/src/backend/executor/execMain.c
+++ b/src/backend/executor/execMain.c
@@ -52,6 +52,7 @@
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "nodes/queryjumble.h"
+#include "optimizer/optimizer.h"
#include "parser/parse_relation.h"
#include "pgstat.h"
#include "rewrite/rewriteHandler.h"
@@ -1779,7 +1780,7 @@ ExecutePlan(QueryDesc *queryDesc,
* Returns NULL if OK, else name of failed check constraint
*/
static const char *
-ExecRelCheck(ResultRelInfo *resultRelInfo,
+ExecRelCheck(CmdType cmdtype, ResultRelInfo *resultRelInfo,
TupleTableSlot *slot, EState *estate)
{
Relation rel = resultRelInfo->ri_RelationDesc;
@@ -1804,6 +1805,25 @@ ExecRelCheck(ResultRelInfo *resultRelInfo,
*/
if (resultRelInfo->ri_CheckConstraintExprs == NULL)
{
+ Bitmapset *updatedCols = NULL;
+
+ /*
+ * During an UPDATE, we may skip CHECK constraint verification.
+ * However, if a BEFORE ROW UPDATE trigger is present, we must perform
+ * the verification, as the trigger might modify additional columns.
+ * We cannot skip this if the UPDATE is from MERGE.
+ */
+ if (cmdtype == CMD_UPDATE &&
+ !(rel->trigdesc && rel->trigdesc->trig_update_before_row))
+ {
+ if (resultRelInfo->ri_MergeActions[MERGE_WHEN_MATCHED] == NIL &&
+ resultRelInfo->ri_MergeActions[MERGE_WHEN_NOT_MATCHED_BY_SOURCE] == NIL &&
+ resultRelInfo->ri_MergeActions[MERGE_WHEN_NOT_MATCHED_BY_TARGET] == NIL)
+ {
+ updatedCols = ExecGetAllUpdatedCols(resultRelInfo, estate);
+ }
+ }
+
oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
resultRelInfo->ri_CheckConstraintExprs = palloc0_array(ExprState *, ncheck);
for (int i = 0; i < ncheck; i++)
@@ -1816,6 +1836,34 @@ ExecRelCheck(ResultRelInfo *resultRelInfo,
checkconstr = stringToNode(check[i].ccbin);
checkconstr = (Expr *) expand_generated_columns_in_expr((Node *) checkconstr, rel, 1);
+
+ if (updatedCols)
+ {
+ Bitmapset *check_attrs = NULL;
+
+ pull_varattnos((Node *) checkconstr, 1, &check_attrs);
+
+ /*
+ * Skip check constraint verification during an UPDATE if the
+ * constraint expression references columns, contains no
+ * whole-row references, and does not reference any of the
+ * columns being updated.
+ */
+ if (check_attrs &&
+ !bms_is_member(0 - FirstLowInvalidHeapAttributeNumber, check_attrs) &&
+ !bms_overlap(check_attrs, updatedCols))
+ {
+ ereport(DEBUG1,
+ errmsg_internal("skipping verification for constraint \"%s\" on table \"%s\"",
+ check[i].ccname,
+ RelationGetRelationName(rel)));
+
+ bms_free(check_attrs);
+
+ continue;
+ }
+ }
+
resultRelInfo->ri_CheckConstraintExprs[i] =
ExecPrepareExpr(checkconstr, estate);
}
@@ -1981,7 +2029,7 @@ ExecPartitionCheckEmitError(ResultRelInfo *resultRelInfo,
* 'resultRelInfo' is the final result relation, after tuple routing.
*/
void
-ExecConstraints(ResultRelInfo *resultRelInfo,
+ExecConstraints(CmdType cmdtype, ResultRelInfo *resultRelInfo,
TupleTableSlot *slot, EState *estate)
{
Relation rel = resultRelInfo->ri_RelationDesc;
@@ -2031,7 +2079,7 @@ ExecConstraints(ResultRelInfo *resultRelInfo,
{
const char *failed;
- if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
+ if ((failed = ExecRelCheck(cmdtype, resultRelInfo, slot, estate)) != NULL)
{
char *val_desc;
Relation orig_rel = rel;
diff --git a/src/backend/executor/execReplication.c b/src/backend/executor/execReplication.c
index 2497ee7edc5..157a21c1da3 100644
--- a/src/backend/executor/execReplication.c
+++ b/src/backend/executor/execReplication.c
@@ -836,7 +836,7 @@ ExecSimpleRelationInsert(ResultRelInfo *resultRelInfo,
/* Check the constraints of the tuple */
if (rel->rd_att->constr)
- ExecConstraints(resultRelInfo, slot, estate);
+ ExecConstraints(CMD_INSERT, resultRelInfo, slot, estate);
if (rel->rd_rel->relispartition)
ExecPartitionCheck(resultRelInfo, slot, estate, true);
@@ -940,7 +940,7 @@ ExecSimpleRelationUpdate(ResultRelInfo *resultRelInfo,
/* Check the constraints of the tuple */
if (rel->rd_att->constr)
- ExecConstraints(resultRelInfo, slot, estate);
+ ExecConstraints(CMD_UPDATE, resultRelInfo, slot, estate);
if (rel->rd_rel->relispartition)
ExecPartitionCheck(resultRelInfo, slot, estate, true);
diff --git a/src/backend/executor/nodeModifyTable.c b/src/backend/executor/nodeModifyTable.c
index 793c76d4f82..95969dbadb4 100644
--- a/src/backend/executor/nodeModifyTable.c
+++ b/src/backend/executor/nodeModifyTable.c
@@ -1101,7 +1101,7 @@ ExecInsert(ModifyTableContext *context,
* Check the constraints of the tuple.
*/
if (resultRelationDesc->rd_att->constr)
- ExecConstraints(resultRelInfo, slot, estate);
+ ExecConstraints(CMD_INSERT, resultRelInfo, slot, estate);
/*
* Also check the tuple against the partition constraint, if there is
@@ -2316,7 +2316,7 @@ lreplace:
* have it validate all remaining checks.
*/
if (resultRelationDesc->rd_att->constr)
- ExecConstraints(resultRelInfo, slot, estate);
+ ExecConstraints(CMD_UPDATE, resultRelInfo, slot, estate);
/*
* replace the heap tuple
diff --git a/src/include/executor/executor.h b/src/include/executor/executor.h
index d46ba59895d..0b1438d3f7c 100644
--- a/src/include/executor/executor.h
+++ b/src/include/executor/executor.h
@@ -257,7 +257,7 @@ extern void InitResultRelInfo(ResultRelInfo *resultRelInfo,
extern ResultRelInfo *ExecGetTriggerResultRel(EState *estate, Oid relid,
ResultRelInfo *rootRelInfo);
extern List *ExecGetAncestorResultRels(EState *estate, ResultRelInfo *resultRelInfo);
-extern void ExecConstraints(ResultRelInfo *resultRelInfo,
+extern void ExecConstraints(CmdType cmdtype, ResultRelInfo *resultRelInfo,
TupleTableSlot *slot, EState *estate);
extern AttrNumber ExecRelGenVirtualNotNull(ResultRelInfo *resultRelInfo,
TupleTableSlot *slot,
diff --git a/src/test/regress/expected/constraints.out b/src/test/regress/expected/constraints.out
index a6fa9cacb72..9f3bb0e0d89 100644
--- a/src/test/regress/expected/constraints.out
+++ b/src/test/regress/expected/constraints.out
@@ -1721,3 +1721,83 @@ COMMENT ON CONSTRAINT inv_ck ON DOMAIN constraint_comments_dom IS 'comment on in
CREATE TABLE regress_notnull1 (a integer);
CREATE TABLE regress_notnull2 () INHERITS (regress_notnull1);
ALTER TABLE ONLY regress_notnull2 ALTER COLUMN a SET NOT NULL;
+CREATE FUNCTION dummy_update_func_in_constr() RETURNS trigger AS $$
+BEGIN
+RETURN NEW;
+END;
+$$ LANGUAGE plpgsql;
+CREATE TABLE upd_check_skip0 (a int, CONSTRAINT cc CHECK (upd_check_skip0 IS NOT NULL));
+INSERT INTO upd_check_skip0 VALUES (1);
+CREATE TABLE upd_check_skip (
+ i int, a int DEFAULT 11, b int, c int,
+ d int GENERATED ALWAYS AS (b + c) STORED,
+ e int GENERATED ALWAYS AS (i) VIRTUAL) PARTITION BY RANGE (i);
+CREATE TABLE upd_check_skip_1 (
+ a int DEFAULT 12, i int, c int, b int,
+ d int GENERATED ALWAYS AS (b + 1) STORED,
+ e int GENERATED ALWAYS AS (b - 100) VIRTUAL);
+ALTER TABLE upd_check_skip ATTACH PARTITION upd_check_skip_1 FOR VALUES FROM (0) TO (10);
+CREATE TABLE upd_check_skip_2 PARTITION OF upd_check_skip FOR VALUES FROM (10) TO (30);
+INSERT INTO upd_check_skip SELECT g + 8, g, -g-g, g+1 FROM generate_series(0, 4) g;
+ALTER TABLE upd_check_skip ADD COLUMN f int;
+ALTER TABLE upd_check_skip ADD CONSTRAINT cc1 CHECK (a + b < 1);
+ALTER TABLE upd_check_skip ADD CONSTRAINT cc2 CHECK (a + c < 100);
+ALTER TABLE upd_check_skip ADD CONSTRAINT cc3 CHECK (b < 1);
+ALTER TABLE upd_check_skip ADD CONSTRAINT cc4 CHECK (d < 2);
+ALTER TABLE upd_check_skip ADD CONSTRAINT cc5 CHECK (e < 20);
+SELECT * FROM upd_check_skip ORDER BY i;
+ i | a | b | c | d | e | f
+----+---+----+---+----+----+---
+ 8 | 0 | 0 | 1 | 1 | 8 |
+ 9 | 1 | -2 | 2 | -1 | 9 |
+ 10 | 2 | -4 | 3 | -1 | 10 |
+ 11 | 3 | -6 | 4 | -2 | 11 |
+ 12 | 4 | -8 | 5 | -3 | 12 |
+(5 rows)
+
+SET log_statement to NONE;
+SET client_min_messages TO 'debug1';
+-- constraint cc contain whole-row reference therefore cannot be skipped
+UPDATE upd_check_skip0 SET a = 2;
+-- error, but cc2, cc5 are still being skipped
+UPDATE upd_check_skip SET b = 11, d = default WHERE i = 12;
+DEBUG: skipping verification for constraint "cc2" on table "upd_check_skip_2"
+DEBUG: skipping verification for constraint "cc5" on table "upd_check_skip_2"
+ERROR: new row for relation "upd_check_skip_2" violates check constraint "cc1"
+DETAIL: Failing row contains (12, 4, 11, 5, 16, virtual, null).
+-- skipping verification for constraint cc1, cc3, cc5 because column c is not
+-- being referenced. However, in table upd_check_skip_2, the generated column d
+-- references column c, therefore constraint cc4 on upd_check_skip_2 cannot be skipped
+UPDATE upd_check_skip SET c = 3 WHERE i = 11 OR i = 8;
+DEBUG: skipping verification for constraint "cc1" on table "upd_check_skip_1"
+DEBUG: skipping verification for constraint "cc3" on table "upd_check_skip_1"
+DEBUG: skipping verification for constraint "cc4" on table "upd_check_skip_1"
+DEBUG: skipping verification for constraint "cc5" on table "upd_check_skip_1"
+DEBUG: skipping verification for constraint "cc1" on table "upd_check_skip_2"
+DEBUG: skipping verification for constraint "cc3" on table "upd_check_skip_2"
+DEBUG: skipping verification for constraint "cc5" on table "upd_check_skip_2"
+-- column f is not referenced by any constraints
+-- virtual generated column is expanded before constraint check
+UPDATE upd_check_skip SET f = 14, e = DEFAULT WHERE i = 12;
+DEBUG: skipping verification for constraint "cc1" on table "upd_check_skip_2"
+DEBUG: skipping verification for constraint "cc2" on table "upd_check_skip_2"
+DEBUG: skipping verification for constraint "cc3" on table "upd_check_skip_2"
+DEBUG: skipping verification for constraint "cc4" on table "upd_check_skip_2"
+DEBUG: skipping verification for constraint "cc5" on table "upd_check_skip_2"
+-- cross partition update cannot be skipped
+UPDATE upd_check_skip SET f = 14, i = 9 WHERE i = 12;
+-- MERGE UPDATE cannot be skipped
+MERGE INTO upd_check_skip t USING (VALUES (8, 2)) AS s(a, b)
+ ON t.i = s.a WHEN MATCHED THEN UPDATE SET f = s.b;
+CREATE TRIGGER upd_check_skip_row_trig_before
+BEFORE UPDATE ON upd_check_skip
+FOR EACH ROW
+EXECUTE PROCEDURE dummy_update_func_in_constr();
+-- BEFORE ROW UPDATE TRIGGER is there, cannot skip
+UPDATE upd_check_skip SET a = NULL, b = NULL, c = NULL;
+DROP TRIGGER upd_check_skip_row_trig_before ON upd_check_skip;
+DROP FUNCTION dummy_update_func_in_constr;
+DROP TABLE upd_check_skip0;
+DROP TABLE upd_check_skip;
+RESET client_min_messages;
+RESET log_statement;
diff --git a/src/test/regress/sql/constraints.sql b/src/test/regress/sql/constraints.sql
index b7f6efdd814..d1e4d7e5962 100644
--- a/src/test/regress/sql/constraints.sql
+++ b/src/test/regress/sql/constraints.sql
@@ -1062,3 +1062,76 @@ COMMENT ON CONSTRAINT inv_ck ON DOMAIN constraint_comments_dom IS 'comment on in
CREATE TABLE regress_notnull1 (a integer);
CREATE TABLE regress_notnull2 () INHERITS (regress_notnull1);
ALTER TABLE ONLY regress_notnull2 ALTER COLUMN a SET NOT NULL;
+
+CREATE FUNCTION dummy_update_func_in_constr() RETURNS trigger AS $$
+BEGIN
+RETURN NEW;
+END;
+$$ LANGUAGE plpgsql;
+
+CREATE TABLE upd_check_skip0 (a int, CONSTRAINT cc CHECK (upd_check_skip0 IS NOT NULL));
+INSERT INTO upd_check_skip0 VALUES (1);
+
+CREATE TABLE upd_check_skip (
+ i int, a int DEFAULT 11, b int, c int,
+ d int GENERATED ALWAYS AS (b + c) STORED,
+ e int GENERATED ALWAYS AS (i) VIRTUAL) PARTITION BY RANGE (i);
+
+CREATE TABLE upd_check_skip_1 (
+ a int DEFAULT 12, i int, c int, b int,
+ d int GENERATED ALWAYS AS (b + 1) STORED,
+ e int GENERATED ALWAYS AS (b - 100) VIRTUAL);
+
+ALTER TABLE upd_check_skip ATTACH PARTITION upd_check_skip_1 FOR VALUES FROM (0) TO (10);
+CREATE TABLE upd_check_skip_2 PARTITION OF upd_check_skip FOR VALUES FROM (10) TO (30);
+INSERT INTO upd_check_skip SELECT g + 8, g, -g-g, g+1 FROM generate_series(0, 4) g;
+ALTER TABLE upd_check_skip ADD COLUMN f int;
+
+ALTER TABLE upd_check_skip ADD CONSTRAINT cc1 CHECK (a + b < 1);
+ALTER TABLE upd_check_skip ADD CONSTRAINT cc2 CHECK (a + c < 100);
+ALTER TABLE upd_check_skip ADD CONSTRAINT cc3 CHECK (b < 1);
+ALTER TABLE upd_check_skip ADD CONSTRAINT cc4 CHECK (d < 2);
+ALTER TABLE upd_check_skip ADD CONSTRAINT cc5 CHECK (e < 20);
+
+SELECT * FROM upd_check_skip ORDER BY i;
+
+SET log_statement to NONE;
+SET client_min_messages TO 'debug1';
+
+-- constraint cc contain whole-row reference therefore cannot be skipped
+UPDATE upd_check_skip0 SET a = 2;
+
+-- error, but cc2, cc5 are still being skipped
+UPDATE upd_check_skip SET b = 11, d = default WHERE i = 12;
+
+-- skipping verification for constraint cc1, cc3, cc5 because column c is not
+-- being referenced. However, in table upd_check_skip_2, the generated column d
+-- references column c, therefore constraint cc4 on upd_check_skip_2 cannot be skipped
+UPDATE upd_check_skip SET c = 3 WHERE i = 11 OR i = 8;
+
+-- column f is not referenced by any constraints
+-- virtual generated column is expanded before constraint check
+UPDATE upd_check_skip SET f = 14, e = DEFAULT WHERE i = 12;
+
+-- cross partition update cannot be skipped
+UPDATE upd_check_skip SET f = 14, i = 9 WHERE i = 12;
+
+-- MERGE UPDATE cannot be skipped
+MERGE INTO upd_check_skip t USING (VALUES (8, 2)) AS s(a, b)
+ ON t.i = s.a WHEN MATCHED THEN UPDATE SET f = s.b;
+
+CREATE TRIGGER upd_check_skip_row_trig_before
+BEFORE UPDATE ON upd_check_skip
+FOR EACH ROW
+EXECUTE PROCEDURE dummy_update_func_in_constr();
+
+-- BEFORE ROW UPDATE TRIGGER is there, cannot skip
+UPDATE upd_check_skip SET a = NULL, b = NULL, c = NULL;
+
+DROP TRIGGER upd_check_skip_row_trig_before ON upd_check_skip;
+DROP FUNCTION dummy_update_func_in_constr;
+DROP TABLE upd_check_skip0;
+DROP TABLE upd_check_skip;
+
+RESET client_min_messages;
+RESET log_statement;
--
2.34.1
^ permalink raw reply [nested|flat] 11+ messages in thread
* Re: UPDATE run check constraints for affected columns only
2025-12-01 06:20 UPDATE run check constraints for affected columns only jian he <jian.universality@gmail.com>
2025-12-01 06:33 ` Re: UPDATE run check constraints for affected columns only Tom Lane <tgl@sss.pgh.pa.us>
2025-12-07 15:50 ` Re: UPDATE run check constraints for affected columns only jian he <jian.universality@gmail.com>
2026-01-23 02:09 ` Re: UPDATE run check constraints for affected columns only jian he <jian.universality@gmail.com>
2026-03-04 01:04 ` Re: UPDATE run check constraints for affected columns only jian he <jian.universality@gmail.com>
2026-03-05 03:12 ` Re: UPDATE run check constraints for affected columns only jian he <jian.universality@gmail.com>
2026-03-06 02:17 ` Re: UPDATE run check constraints for affected columns only jian he <jian.universality@gmail.com>
@ 2026-03-06 16:10 ` Florin Irion <irionr@gmail.com>
2026-03-07 09:46 ` Re: UPDATE run check constraints for affected columns only jian he <jian.universality@gmail.com>
0 siblings, 1 reply; 11+ messages in thread
From: Florin Irion @ 2026-03-06 16:10 UTC (permalink / raw)
To: jian he <jian.universality@gmail.com>; +Cc: pgsql-hackers; Haritabh Gupta <haritabh1992@gmail.com>
Hi Jian,
Haritabh and I have been reviewing this patch. The core optimization
is sound — the BEFORE ROW UPDATE trigger guard, the generated column
handling via expand_generated_columns_in_expr + ExecGetAllUpdatedCols,
and the whole-row reference check are all correct.
We independently found the same MERGE issue you fixed in v6, where
ri_CheckConstraintExprs is shared between INSERT and UPDATE actions on
the same ResultRelInfo. Nice catch on the fix.
That said, I think v6's approach of disabling the optimization entirely
for MERGE is more conservative than necessary. A MERGE with only WHEN
MATCHED THEN UPDATE (no INSERT action) would still benefit from skipping
unaffected constraints, but v6 disables it for all MERGE operations.
An alternative that preserves the optimization for MERGE UPDATE actions
would be to follow the existing ri_GeneratedExprsI/ri_GeneratedExprsU
pattern — split into two separate cached arrays:
```
/* array of expr states for checking check constraints */
ExprState **ri_CheckConstraintExprsI; /* for INSERT */
ExprState **ri_CheckConstraintExprsU; /* for UPDATE */
```
Then in ExecRelCheck, select the appropriate array based on cmdtype:
```
ExprState **checkExprs;
checkExprs = (cmdtype == CMD_UPDATE)
? resultRelInfo->ri_CheckConstraintExprsU
: resultRelInfo->ri_CheckConstraintExprsI;
if (checkExprs == NULL)
{
Bitmapset *updatedCols = NULL;
if (cmdtype == CMD_UPDATE &&
!(rel->trigdesc && rel->trigdesc->trig_update_before_row))
updatedCols = ExecGetAllUpdatedCols(resultRelInfo, estate);
/* ... alloc and populate checkExprs ... */
if (cmdtype == CMD_UPDATE)
resultRelInfo->ri_CheckConstraintExprsU = checkExprs;
else
resultRelInfo->ri_CheckConstraintExprsI = checkExprs;
}
```
This way INSERT always compiles and checks all constraints, UPDATE gets
the skip optimization even during MERGE, and both can safely coexist on
the same ResultRelInfo. The lazy-init cost for the second array only
applies when both code paths are actually taken, which matches the
generated-columns precedent. It also makes INSERT ON CONFLICT DO UPDATE
structurally safe rather than relying on INSERT always running first.
A few other items on v6:
1. The MERGE test case only tests MERGE with a single UPDATE action and
verifies the optimization is disabled. It doesn't test the actual
dangerous scenario — MERGE with both INSERT and UPDATE actions where
the INSERT row violates a constraint. Without that, a future refactor
could reintroduce the original bug without any test failing. Something
like:
```
CREATE TABLE merge_cc (id int PRIMARY KEY, a int, b int,
CONSTRAINT cc CHECK (a > 0));
INSERT INTO merge_cc VALUES (1, 10, 10);
MERGE INTO merge_cc t
USING (VALUES (1, 99, 20), (2, -5, 30)) AS s(id, a, b)
ON t.id = s.id
WHEN MATCHED THEN UPDATE SET b = s.b
WHEN NOT MATCHED THEN INSERT VALUES (s.id, s.a, s.b);
-- must ERROR on cc (a = -5), not silently succeed
```
2. The cross-partition update test comment says "cannot be skipped", but
cross-partition UPDATE goes through ExecCrossPartitionUpdate which
does DELETE + INSERT. The constraint check happens via ExecInsert with
CMD_INSERT on the destination partition, so the optimization was never
applicable. The test doesn't exercise anything specific to this patch.
Cheers,
Florin
--
* Florin Irion *
* https://www.enterprisedb.com <https://www.enterprisedb.com/>*
^ permalink raw reply [nested|flat] 11+ messages in thread
* Re: UPDATE run check constraints for affected columns only
2025-12-01 06:20 UPDATE run check constraints for affected columns only jian he <jian.universality@gmail.com>
2025-12-01 06:33 ` Re: UPDATE run check constraints for affected columns only Tom Lane <tgl@sss.pgh.pa.us>
2025-12-07 15:50 ` Re: UPDATE run check constraints for affected columns only jian he <jian.universality@gmail.com>
2026-01-23 02:09 ` Re: UPDATE run check constraints for affected columns only jian he <jian.universality@gmail.com>
2026-03-04 01:04 ` Re: UPDATE run check constraints for affected columns only jian he <jian.universality@gmail.com>
2026-03-05 03:12 ` Re: UPDATE run check constraints for affected columns only jian he <jian.universality@gmail.com>
2026-03-06 02:17 ` Re: UPDATE run check constraints for affected columns only jian he <jian.universality@gmail.com>
2026-03-06 16:10 ` Re: UPDATE run check constraints for affected columns only Florin Irion <irionr@gmail.com>
@ 2026-03-07 09:46 ` jian he <jian.universality@gmail.com>
2026-09-02 02:38 ` Re: UPDATE run check constraints for affected columns only jian he <jian.universality@gmail.com>
0 siblings, 1 reply; 11+ messages in thread
From: jian he @ 2026-03-07 09:46 UTC (permalink / raw)
To: Florin Irion <irionr@gmail.com>; +Cc: pgsql-hackers; Haritabh Gupta <haritabh1992@gmail.com>
On Sat, Mar 7, 2026 at 12:10 AM Florin Irion <irionr@gmail.com> wrote:
>
> Hi Jian,
>
> An alternative that preserves the optimization for MERGE UPDATE actions
> would be to follow the existing ri_GeneratedExprsI/ri_GeneratedExprsU
> pattern — split into two separate cached arrays:
>
> ```
> /* array of expr states for checking check constraints */
> ExprState **ri_CheckConstraintExprsI; /* for INSERT */
> ExprState **ri_CheckConstraintExprsU; /* for UPDATE */
> ```
I have given it a try, please see attached v7.
I don’t have a strong preference for either v6 or v7.
> 2. The cross-partition update test comment says "cannot be skipped", but
> cross-partition UPDATE goes through ExecCrossPartitionUpdate which
> does DELETE + INSERT. The constraint check happens via ExecInsert with
> CMD_INSERT on the destination partition, so the optimization was never
> applicable. The test doesn't exercise anything specific to this patch.
>
OK. I kept these tests. I think covering this scenario is useful. Perhaps it
has already been tested elsewhere, but including it here makes the tests more
complete
--
jian
https://www.enterprisedb.com/
Attachments:
v7-0001-skip-unnecessary-check-constraint-verification-for-UPDATE.patch (text/x-patch, 20.6K) download
From 2cdf1d47faa8a29c6b363335895488834a76620e Mon Sep 17 00:00:00 2001
From: jian he <jian.universality@gmail.com>
Date: Sat, 7 Mar 2026 17:35:24 +0800
Subject: [PATCH v7 1/1] skip unnecessary check constraint verification for
UPDATE
In an UPDATE, we can skip verification of any columns that do not depend on any
UPDATE target column. But if there is a BEFORE ROW UPDATE trigger, we cannot
skip because the trigger may modifies more column.
We cache ri_CheckConstraintExprs in ExecConstraints and must initialize them all
if different actions like INSERT and UPDATE, happen together in a query.
Because both INSERT and UPDATE need to use these ri_CheckConstraintExprs.
Invoke INSERT AND UPDATE together will happen within MERGE command. We confirm
it's a MERGE operation by checking that resultRelInfo->ri_MergeActions is not
NIL. See ExecMergeNotMatched and ExecMergeMatched.
For cross-partition updates (ExecCrossPartitionUpdate), the operation splits
into an INSERT and DELETE, we can treat it as a single action.
Author: jian he <jian.universality@gmail.com>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: li carol <carol.li2025@outlook.com>
Reviewed-by: Jacob Champion <jacob.champion@enterprisedb.com>
Reviewed-by: Florin Irion <irionr@gmail.com>
Reviewed-by: Haritabh Gupta <haritabh1992@gmail.com>
Discussion: https://postgr.es/m/CACJufxEtY1hdLcx=Fhnqp-ERcV1PhbvELG5COy_CZjoEW76ZPQ@mail.gmail.com
context: https://postgr.es/m/1326055327.15293.13.camel%40vanquo.pezone.net
commitfest: https://commitfest.postgresql.org/patch/6270
---
src/backend/commands/copyfrom.c | 2 +-
src/backend/executor/execMain.c | 69 +++++++++++++--
src/backend/executor/execReplication.c | 4 +-
src/backend/executor/nodeModifyTable.c | 4 +-
src/include/executor/executor.h | 2 +-
src/include/nodes/execnodes.h | 7 +-
src/test/regress/expected/constraints.out | 103 ++++++++++++++++++++++
src/test/regress/sql/constraints.sql | 85 ++++++++++++++++++
8 files changed, 259 insertions(+), 17 deletions(-)
diff --git a/src/backend/commands/copyfrom.c b/src/backend/commands/copyfrom.c
index 2f42f55e229..43354a3c454 100644
--- a/src/backend/commands/copyfrom.c
+++ b/src/backend/commands/copyfrom.c
@@ -1356,7 +1356,7 @@ CopyFrom(CopyFromState cstate)
*/
if (resultRelInfo->ri_FdwRoutine == NULL &&
resultRelInfo->ri_RelationDesc->rd_att->constr)
- ExecConstraints(resultRelInfo, myslot, estate);
+ ExecConstraints(CMD_INSERT, resultRelInfo, myslot, estate);
/*
* Also check the tuple against the partition constraint, if
diff --git a/src/backend/executor/execMain.c b/src/backend/executor/execMain.c
index bfd3ebc601e..f29f50afd71 100644
--- a/src/backend/executor/execMain.c
+++ b/src/backend/executor/execMain.c
@@ -52,6 +52,7 @@
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "nodes/queryjumble.h"
+#include "optimizer/optimizer.h"
#include "parser/parse_relation.h"
#include "pgstat.h"
#include "rewrite/rewriteHandler.h"
@@ -1292,7 +1293,8 @@ InitResultRelInfo(ResultRelInfo *resultRelInfo,
resultRelInfo->ri_projectNewInfoValid = false;
resultRelInfo->ri_FdwState = NULL;
resultRelInfo->ri_usesFdwDirectModify = false;
- resultRelInfo->ri_CheckConstraintExprs = NULL;
+ resultRelInfo->ri_CheckConstraintExprsI = NULL;
+ resultRelInfo->ri_CheckConstraintExprsU = NULL;
resultRelInfo->ri_GenVirtualNotNullConstraintExprs = NULL;
resultRelInfo->ri_GeneratedExprsI = NULL;
resultRelInfo->ri_GeneratedExprsU = NULL;
@@ -1779,7 +1781,7 @@ ExecutePlan(QueryDesc *queryDesc,
* Returns NULL if OK, else name of failed check constraint
*/
static const char *
-ExecRelCheck(ResultRelInfo *resultRelInfo,
+ExecRelCheck(CmdType cmdtype, ResultRelInfo *resultRelInfo,
TupleTableSlot *slot, EState *estate)
{
Relation rel = resultRelInfo->ri_RelationDesc;
@@ -1797,15 +1799,36 @@ ExecRelCheck(ResultRelInfo *resultRelInfo,
elog(ERROR, "%d pg_constraint record(s) missing for relation \"%s\"",
rel->rd_rel->relchecks - ncheck, RelationGetRelationName(rel));
+ Assert(cmdtype == CMD_UPDATE || cmdtype == CMD_INSERT);
+
/*
* If first time through for this result relation, build expression
* nodetrees for rel's constraint expressions. Keep them in the per-query
* memory context so they'll survive throughout the query.
*/
- if (resultRelInfo->ri_CheckConstraintExprs == NULL)
+ if ((!resultRelInfo->ri_CheckConstraintExprsU && cmdtype == CMD_UPDATE) ||
+ (!resultRelInfo->ri_CheckConstraintExprsI && cmdtype == CMD_INSERT))
{
+ Bitmapset *updatedCols = NULL;
+ ExprState **checkExprs;
+
+ /*
+ * During an UPDATE, we may skip CHECK constraint verification. But if
+ * BEFORE ROW UPDATE trigger is present, the verification cannot be
+ * skipped as the trigger might modify additional columns
+ */
+ if (cmdtype == CMD_UPDATE &&
+ !(rel->trigdesc && rel->trigdesc->trig_update_before_row))
+ updatedCols = ExecGetAllUpdatedCols(resultRelInfo, estate);
+
oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
- resultRelInfo->ri_CheckConstraintExprs = palloc0_array(ExprState *, ncheck);
+ checkExprs = palloc0_array(ExprState *, ncheck);
+
+ if (cmdtype == CMD_UPDATE)
+ resultRelInfo->ri_CheckConstraintExprsU = checkExprs;
+ else
+ resultRelInfo->ri_CheckConstraintExprsI = checkExprs;
+
for (int i = 0; i < ncheck; i++)
{
Expr *checkconstr;
@@ -1816,8 +1839,34 @@ ExecRelCheck(ResultRelInfo *resultRelInfo,
checkconstr = stringToNode(check[i].ccbin);
checkconstr = (Expr *) expand_generated_columns_in_expr((Node *) checkconstr, rel, 1);
- resultRelInfo->ri_CheckConstraintExprs[i] =
- ExecPrepareExpr(checkconstr, estate);
+
+ if (updatedCols)
+ {
+ Bitmapset *check_attrs = NULL;
+
+ pull_varattnos((Node *) checkconstr, 1, &check_attrs);
+
+ /*
+ * Skip check constraint verification during an UPDATE if the
+ * constraint expression references any columns, contains no
+ * whole-row references, and does not reference any of the
+ * columns being updated.
+ */
+ if (check_attrs &&
+ !bms_is_member(0 - FirstLowInvalidHeapAttributeNumber, check_attrs) &&
+ !bms_overlap(check_attrs, updatedCols))
+ {
+ ereport(DEBUG1,
+ errmsg_internal("skipping verification for constraint \"%s\" on table \"%s\"",
+ check[i].ccname,
+ RelationGetRelationName(rel)));
+
+ bms_free(check_attrs);
+
+ continue;
+ }
+ }
+ checkExprs[i] = ExecPrepareExpr(checkconstr, estate);
}
MemoryContextSwitchTo(oldContext);
}
@@ -1834,7 +1883,9 @@ ExecRelCheck(ResultRelInfo *resultRelInfo,
/* And evaluate the constraints */
for (int i = 0; i < ncheck; i++)
{
- ExprState *checkconstr = resultRelInfo->ri_CheckConstraintExprs[i];
+ ExprState *checkconstr = (cmdtype == CMD_INSERT)
+ ? resultRelInfo->ri_CheckConstraintExprsI[i]
+ : resultRelInfo->ri_CheckConstraintExprsU[i];
/*
* NOTE: SQL specifies that a NULL result from a constraint expression
@@ -1981,7 +2032,7 @@ ExecPartitionCheckEmitError(ResultRelInfo *resultRelInfo,
* 'resultRelInfo' is the final result relation, after tuple routing.
*/
void
-ExecConstraints(ResultRelInfo *resultRelInfo,
+ExecConstraints(CmdType cmdtype, ResultRelInfo *resultRelInfo,
TupleTableSlot *slot, EState *estate)
{
Relation rel = resultRelInfo->ri_RelationDesc;
@@ -2031,7 +2082,7 @@ ExecConstraints(ResultRelInfo *resultRelInfo,
{
const char *failed;
- if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
+ if ((failed = ExecRelCheck(cmdtype, resultRelInfo, slot, estate)) != NULL)
{
char *val_desc;
Relation orig_rel = rel;
diff --git a/src/backend/executor/execReplication.c b/src/backend/executor/execReplication.c
index 2497ee7edc5..157a21c1da3 100644
--- a/src/backend/executor/execReplication.c
+++ b/src/backend/executor/execReplication.c
@@ -836,7 +836,7 @@ ExecSimpleRelationInsert(ResultRelInfo *resultRelInfo,
/* Check the constraints of the tuple */
if (rel->rd_att->constr)
- ExecConstraints(resultRelInfo, slot, estate);
+ ExecConstraints(CMD_INSERT, resultRelInfo, slot, estate);
if (rel->rd_rel->relispartition)
ExecPartitionCheck(resultRelInfo, slot, estate, true);
@@ -940,7 +940,7 @@ ExecSimpleRelationUpdate(ResultRelInfo *resultRelInfo,
/* Check the constraints of the tuple */
if (rel->rd_att->constr)
- ExecConstraints(resultRelInfo, slot, estate);
+ ExecConstraints(CMD_UPDATE, resultRelInfo, slot, estate);
if (rel->rd_rel->relispartition)
ExecPartitionCheck(resultRelInfo, slot, estate, true);
diff --git a/src/backend/executor/nodeModifyTable.c b/src/backend/executor/nodeModifyTable.c
index 793c76d4f82..95969dbadb4 100644
--- a/src/backend/executor/nodeModifyTable.c
+++ b/src/backend/executor/nodeModifyTable.c
@@ -1101,7 +1101,7 @@ ExecInsert(ModifyTableContext *context,
* Check the constraints of the tuple.
*/
if (resultRelationDesc->rd_att->constr)
- ExecConstraints(resultRelInfo, slot, estate);
+ ExecConstraints(CMD_INSERT, resultRelInfo, slot, estate);
/*
* Also check the tuple against the partition constraint, if there is
@@ -2316,7 +2316,7 @@ lreplace:
* have it validate all remaining checks.
*/
if (resultRelationDesc->rd_att->constr)
- ExecConstraints(resultRelInfo, slot, estate);
+ ExecConstraints(CMD_UPDATE, resultRelInfo, slot, estate);
/*
* replace the heap tuple
diff --git a/src/include/executor/executor.h b/src/include/executor/executor.h
index d46ba59895d..0b1438d3f7c 100644
--- a/src/include/executor/executor.h
+++ b/src/include/executor/executor.h
@@ -257,7 +257,7 @@ extern void InitResultRelInfo(ResultRelInfo *resultRelInfo,
extern ResultRelInfo *ExecGetTriggerResultRel(EState *estate, Oid relid,
ResultRelInfo *rootRelInfo);
extern List *ExecGetAncestorResultRels(EState *estate, ResultRelInfo *resultRelInfo);
-extern void ExecConstraints(ResultRelInfo *resultRelInfo,
+extern void ExecConstraints(CmdType cmdtype, ResultRelInfo *resultRelInfo,
TupleTableSlot *slot, EState *estate);
extern AttrNumber ExecRelGenVirtualNotNull(ResultRelInfo *resultRelInfo,
TupleTableSlot *slot,
diff --git a/src/include/nodes/execnodes.h b/src/include/nodes/execnodes.h
index 63c067d5aae..45b321faac3 100644
--- a/src/include/nodes/execnodes.h
+++ b/src/include/nodes/execnodes.h
@@ -554,8 +554,11 @@ typedef struct ResultRelInfo
/* list of WithCheckOption expr states */
List *ri_WithCheckOptionExprs;
- /* array of expr states for checking check constraints */
- ExprState **ri_CheckConstraintExprs;
+ /*
+ * Arrays of check constraint ExprStates for INSERT/UPDATE/MERGE.
+ */
+ ExprState **ri_CheckConstraintExprsI;
+ ExprState **ri_CheckConstraintExprsU;
/*
* array of expr states for checking not-null constraints on virtual
diff --git a/src/test/regress/expected/constraints.out b/src/test/regress/expected/constraints.out
index a6fa9cacb72..99e2cd6ff4a 100644
--- a/src/test/regress/expected/constraints.out
+++ b/src/test/regress/expected/constraints.out
@@ -1721,3 +1721,106 @@ COMMENT ON CONSTRAINT inv_ck ON DOMAIN constraint_comments_dom IS 'comment on in
CREATE TABLE regress_notnull1 (a integer);
CREATE TABLE regress_notnull2 () INHERITS (regress_notnull1);
ALTER TABLE ONLY regress_notnull2 ALTER COLUMN a SET NOT NULL;
+CREATE FUNCTION dummy_update_func_in_constr() RETURNS trigger AS $$
+BEGIN
+RETURN NEW;
+END;
+$$ LANGUAGE plpgsql;
+CREATE TABLE upd_check_skip0 (a int, CONSTRAINT cc CHECK (upd_check_skip0 IS NOT NULL));
+INSERT INTO upd_check_skip0 VALUES (1);
+CREATE TABLE upd_check_skip (
+ i int, a int DEFAULT 11, b int, c int,
+ d int GENERATED ALWAYS AS (b + c) STORED,
+ e int GENERATED ALWAYS AS (i) VIRTUAL) PARTITION BY RANGE (i);
+CREATE TABLE upd_check_skip_1 (
+ a int DEFAULT 12, i int, c int, b int,
+ d int GENERATED ALWAYS AS (b + 1) STORED,
+ e int GENERATED ALWAYS AS (b - 100) VIRTUAL);
+ALTER TABLE upd_check_skip ATTACH PARTITION upd_check_skip_1 FOR VALUES FROM (0) TO (10);
+CREATE TABLE upd_check_skip_2 PARTITION OF upd_check_skip FOR VALUES FROM (10) TO (30);
+INSERT INTO upd_check_skip SELECT g + 8, g, -g-g, g+1 FROM generate_series(0, 4) g;
+ALTER TABLE upd_check_skip ADD COLUMN f int;
+ALTER TABLE upd_check_skip ADD CONSTRAINT cc1 CHECK (a + b < 1);
+ALTER TABLE upd_check_skip ADD CONSTRAINT cc2 CHECK (a + c < 100);
+ALTER TABLE upd_check_skip ADD CONSTRAINT cc3 CHECK (b < 1);
+ALTER TABLE upd_check_skip ADD CONSTRAINT cc4 CHECK (d < 2);
+ALTER TABLE upd_check_skip ADD CONSTRAINT cc5 CHECK (e < 20);
+SELECT * FROM upd_check_skip ORDER BY i;
+ i | a | b | c | d | e | f
+----+---+----+---+----+----+---
+ 8 | 0 | 0 | 1 | 1 | 8 |
+ 9 | 1 | -2 | 2 | -1 | 9 |
+ 10 | 2 | -4 | 3 | -1 | 10 |
+ 11 | 3 | -6 | 4 | -2 | 11 |
+ 12 | 4 | -8 | 5 | -3 | 12 |
+(5 rows)
+
+SET log_statement to NONE;
+SET client_min_messages TO 'debug1';
+-- constraint cc contain whole-row reference therefore cannot be skipped
+UPDATE upd_check_skip0 SET a = 2;
+-- error, but cc2, cc5 are still being skipped
+UPDATE upd_check_skip SET b = 11, d = default WHERE i = 12;
+DEBUG: skipping verification for constraint "cc2" on table "upd_check_skip_2"
+DEBUG: skipping verification for constraint "cc5" on table "upd_check_skip_2"
+ERROR: new row for relation "upd_check_skip_2" violates check constraint "cc1"
+DETAIL: Failing row contains (12, 4, 11, 5, 16, virtual, null).
+-- error, but cc2, cc5 are still being skipped
+MERGE INTO upd_check_skip t USING (VALUES (12, 11)) AS s(a, b)
+ ON t.i = s.a WHEN MATCHED THEN UPDATE SET b = s.b, d = default;
+DEBUG: skipping verification for constraint "cc2" on table "upd_check_skip_2"
+DEBUG: skipping verification for constraint "cc5" on table "upd_check_skip_2"
+ERROR: new row for relation "upd_check_skip_2" violates check constraint "cc1"
+DETAIL: Failing row contains (12, 4, 11, 5, 16, virtual, null).
+-- MERGE UPDATE referenced constraint will be skipped, but MERGE INSERT
+-- constraint check still need enforced
+MERGE INTO upd_check_skip t USING (VALUES (12, -5), (18, 0)) AS s(a, b)
+ ON t.i = s.a
+ WHEN MATCHED THEN UPDATE SET b = s.b
+ WHEN NOT MATCHED BY TARGET THEN INSERT(i, a, b, c) VALUES (12, -3, -1, 4);
+DEBUG: skipping verification for constraint "cc2" on table "upd_check_skip_2"
+DEBUG: skipping verification for constraint "cc5" on table "upd_check_skip_2"
+ERROR: new row for relation "upd_check_skip_2" violates check constraint "cc4"
+DETAIL: Failing row contains (12, -3, -1, 4, 3, virtual, null).
+MERGE INTO upd_check_skip t USING (VALUES (8, 0), (18, 0)) AS s(a, b)
+ ON t.i = s.a
+ WHEN MATCHED THEN UPDATE SET b = s.b
+ WHEN NOT MATCHED BY SOURCE AND i = 11 THEN UPDATE SET a = -3, b = -1, c = 4;
+DEBUG: skipping verification for constraint "cc5" on table "upd_check_skip_2"
+ERROR: new row for relation "upd_check_skip_2" violates check constraint "cc4"
+DETAIL: Failing row contains (11, -3, -1, 4, 3, virtual, null).
+-- skipping verification for constraint cc1, cc3, cc5 because column c is not
+-- being referenced. However, in table upd_check_skip_2, the generated column d
+-- references column c, therefore constraint cc4 on upd_check_skip_2 cannot be skipped
+UPDATE upd_check_skip SET c = 3 WHERE i = 11 OR i = 8;
+DEBUG: skipping verification for constraint "cc1" on table "upd_check_skip_1"
+DEBUG: skipping verification for constraint "cc3" on table "upd_check_skip_1"
+DEBUG: skipping verification for constraint "cc4" on table "upd_check_skip_1"
+DEBUG: skipping verification for constraint "cc5" on table "upd_check_skip_1"
+DEBUG: skipping verification for constraint "cc1" on table "upd_check_skip_2"
+DEBUG: skipping verification for constraint "cc3" on table "upd_check_skip_2"
+DEBUG: skipping verification for constraint "cc5" on table "upd_check_skip_2"
+-- column f is not referenced by any constraints
+-- virtual generated column is expanded before constraint check
+UPDATE upd_check_skip SET f = 14, e = DEFAULT WHERE i = 12;
+DEBUG: skipping verification for constraint "cc1" on table "upd_check_skip_2"
+DEBUG: skipping verification for constraint "cc2" on table "upd_check_skip_2"
+DEBUG: skipping verification for constraint "cc3" on table "upd_check_skip_2"
+DEBUG: skipping verification for constraint "cc4" on table "upd_check_skip_2"
+DEBUG: skipping verification for constraint "cc5" on table "upd_check_skip_2"
+-- test cross partition update
+UPDATE upd_check_skip SET b = 11, i = 9 WHERE i = 12;
+ERROR: new row for relation "upd_check_skip_1" violates check constraint "cc1"
+DETAIL: Failing row contains (9, 4, 11, 5, 12, virtual, 14).
+CREATE TRIGGER upd_check_skip_row_trig_before
+BEFORE UPDATE ON upd_check_skip
+FOR EACH ROW
+EXECUTE PROCEDURE dummy_update_func_in_constr();
+-- BEFORE ROW UPDATE TRIGGER is there, cannot skip
+UPDATE upd_check_skip SET a = NULL, b = NULL, c = NULL;
+DROP TRIGGER upd_check_skip_row_trig_before ON upd_check_skip;
+DROP FUNCTION dummy_update_func_in_constr;
+DROP TABLE upd_check_skip0;
+DROP TABLE upd_check_skip;
+RESET client_min_messages;
+RESET log_statement;
diff --git a/src/test/regress/sql/constraints.sql b/src/test/regress/sql/constraints.sql
index b7f6efdd814..37b23aa4b81 100644
--- a/src/test/regress/sql/constraints.sql
+++ b/src/test/regress/sql/constraints.sql
@@ -1062,3 +1062,88 @@ COMMENT ON CONSTRAINT inv_ck ON DOMAIN constraint_comments_dom IS 'comment on in
CREATE TABLE regress_notnull1 (a integer);
CREATE TABLE regress_notnull2 () INHERITS (regress_notnull1);
ALTER TABLE ONLY regress_notnull2 ALTER COLUMN a SET NOT NULL;
+
+CREATE FUNCTION dummy_update_func_in_constr() RETURNS trigger AS $$
+BEGIN
+RETURN NEW;
+END;
+$$ LANGUAGE plpgsql;
+
+CREATE TABLE upd_check_skip0 (a int, CONSTRAINT cc CHECK (upd_check_skip0 IS NOT NULL));
+INSERT INTO upd_check_skip0 VALUES (1);
+
+CREATE TABLE upd_check_skip (
+ i int, a int DEFAULT 11, b int, c int,
+ d int GENERATED ALWAYS AS (b + c) STORED,
+ e int GENERATED ALWAYS AS (i) VIRTUAL) PARTITION BY RANGE (i);
+
+CREATE TABLE upd_check_skip_1 (
+ a int DEFAULT 12, i int, c int, b int,
+ d int GENERATED ALWAYS AS (b + 1) STORED,
+ e int GENERATED ALWAYS AS (b - 100) VIRTUAL);
+
+ALTER TABLE upd_check_skip ATTACH PARTITION upd_check_skip_1 FOR VALUES FROM (0) TO (10);
+CREATE TABLE upd_check_skip_2 PARTITION OF upd_check_skip FOR VALUES FROM (10) TO (30);
+INSERT INTO upd_check_skip SELECT g + 8, g, -g-g, g+1 FROM generate_series(0, 4) g;
+ALTER TABLE upd_check_skip ADD COLUMN f int;
+
+ALTER TABLE upd_check_skip ADD CONSTRAINT cc1 CHECK (a + b < 1);
+ALTER TABLE upd_check_skip ADD CONSTRAINT cc2 CHECK (a + c < 100);
+ALTER TABLE upd_check_skip ADD CONSTRAINT cc3 CHECK (b < 1);
+ALTER TABLE upd_check_skip ADD CONSTRAINT cc4 CHECK (d < 2);
+ALTER TABLE upd_check_skip ADD CONSTRAINT cc5 CHECK (e < 20);
+
+SELECT * FROM upd_check_skip ORDER BY i;
+
+SET log_statement to NONE;
+SET client_min_messages TO 'debug1';
+
+-- constraint cc contain whole-row reference therefore cannot be skipped
+UPDATE upd_check_skip0 SET a = 2;
+
+-- error, but cc2, cc5 are still being skipped
+UPDATE upd_check_skip SET b = 11, d = default WHERE i = 12;
+
+-- error, but cc2, cc5 are still being skipped
+MERGE INTO upd_check_skip t USING (VALUES (12, 11)) AS s(a, b)
+ ON t.i = s.a WHEN MATCHED THEN UPDATE SET b = s.b, d = default;
+
+-- MERGE UPDATE referenced constraint will be skipped, but MERGE INSERT
+-- constraint check still need enforced
+MERGE INTO upd_check_skip t USING (VALUES (12, -5), (18, 0)) AS s(a, b)
+ ON t.i = s.a
+ WHEN MATCHED THEN UPDATE SET b = s.b
+ WHEN NOT MATCHED BY TARGET THEN INSERT(i, a, b, c) VALUES (12, -3, -1, 4);
+
+MERGE INTO upd_check_skip t USING (VALUES (8, 0), (18, 0)) AS s(a, b)
+ ON t.i = s.a
+ WHEN MATCHED THEN UPDATE SET b = s.b
+ WHEN NOT MATCHED BY SOURCE AND i = 11 THEN UPDATE SET a = -3, b = -1, c = 4;
+
+-- skipping verification for constraint cc1, cc3, cc5 because column c is not
+-- being referenced. However, in table upd_check_skip_2, the generated column d
+-- references column c, therefore constraint cc4 on upd_check_skip_2 cannot be skipped
+UPDATE upd_check_skip SET c = 3 WHERE i = 11 OR i = 8;
+
+-- column f is not referenced by any constraints
+-- virtual generated column is expanded before constraint check
+UPDATE upd_check_skip SET f = 14, e = DEFAULT WHERE i = 12;
+
+-- test cross partition update
+UPDATE upd_check_skip SET b = 11, i = 9 WHERE i = 12;
+
+CREATE TRIGGER upd_check_skip_row_trig_before
+BEFORE UPDATE ON upd_check_skip
+FOR EACH ROW
+EXECUTE PROCEDURE dummy_update_func_in_constr();
+
+-- BEFORE ROW UPDATE TRIGGER is there, cannot skip
+UPDATE upd_check_skip SET a = NULL, b = NULL, c = NULL;
+
+DROP TRIGGER upd_check_skip_row_trig_before ON upd_check_skip;
+DROP FUNCTION dummy_update_func_in_constr;
+DROP TABLE upd_check_skip0;
+DROP TABLE upd_check_skip;
+
+RESET client_min_messages;
+RESET log_statement;
--
2.34.1
^ permalink raw reply [nested|flat] 11+ messages in thread
* Re: UPDATE run check constraints for affected columns only
2025-12-01 06:20 UPDATE run check constraints for affected columns only jian he <jian.universality@gmail.com>
2025-12-01 06:33 ` Re: UPDATE run check constraints for affected columns only Tom Lane <tgl@sss.pgh.pa.us>
2025-12-07 15:50 ` Re: UPDATE run check constraints for affected columns only jian he <jian.universality@gmail.com>
2026-01-23 02:09 ` Re: UPDATE run check constraints for affected columns only jian he <jian.universality@gmail.com>
2026-03-04 01:04 ` Re: UPDATE run check constraints for affected columns only jian he <jian.universality@gmail.com>
2026-03-05 03:12 ` Re: UPDATE run check constraints for affected columns only jian he <jian.universality@gmail.com>
2026-03-06 02:17 ` Re: UPDATE run check constraints for affected columns only jian he <jian.universality@gmail.com>
2026-03-06 16:10 ` Re: UPDATE run check constraints for affected columns only Florin Irion <irionr@gmail.com>
2026-03-07 09:46 ` Re: UPDATE run check constraints for affected columns only jian he <jian.universality@gmail.com>
@ 2026-09-02 02:38 ` jian he <jian.universality@gmail.com>
2026-09-08 06:58 ` Re: UPDATE run check constraints for affected columns only solai v <solai.cdac@gmail.com>
0 siblings, 1 reply; 11+ messages in thread
From: jian he @ 2026-09-02 02:38 UTC (permalink / raw)
To: Florin Irion <irionr@gmail.com>; +Cc: pgsql-hackers; Haritabh Gupta <haritabh1992@gmail.com>
On Sat, Mar 7, 2026 at 5:46 PM jian he <jian.universality@gmail.com> wrote:
>
> OK. I kept these tests. I think covering this scenario is useful. Perhaps it
> has already been tested elsewhere, but including it here makes the tests more
> complete
>
+SET log_statement to NONE;
+SET client_min_messages TO 'debug1';
+
+-- constraint cc contain whole-row reference therefore cannot be skipped
+UPDATE upd_check_skip0 SET a = 2;
In V7, setting client_min_messages to capture DEBUG1 messages in
regression tests is not a good idea, as other messages may also be
emitted.
So I added some tests on test/modules/test_misc/t/001_constraint_validation.pl.
I also made some cosmetic changes to make ExecRelCheck more readable.
--
jian
https://www.enterprisedb.com/
Attachments:
v8-0001-skip-unnecessary-check-constraint-verification-for-UPDATE.patch (text/x-patch, 14.7K) download
From 482db334dcac0aeb1b2d4ec4c992e709150568f9 Mon Sep 17 00:00:00 2001
From: jian he <jian.universality@gmail.com>
Date: Wed, 2 Sep 2026 09:49:24 +0800
Subject: [PATCH v8 1/1] skip unnecessary check constraint verification for
UPDATE
If an UPDATE does not modify any column referenced by a CHECK
constraint, the new tuple satisfies the constraint whenever the old
tuple did, so re-verifying it is unnecessary.
Verification cannot be skipped if:
* a BEFORE ROW UPDATE trigger exists, since it may modify columns
beyond the UPDATE target list
* the constraint is NOT VALID since pre-existing rows may violate it
* the constraint contains a whole-row reference, or references no
columns at all.
* the constraint is NOT ENFORCED
Columns modified indirectly through stored generated columns count as updated,
per ExecGetAllUpdatedCols.
Author: jian he <jian.universality@gmail.com>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: li carol <carol.li2025@outlook.com>
Reviewed-by: Jacob Champion <jacob.champion@enterprisedb.com>
Reviewed-by: Florin Irion <irionr@gmail.com>
Reviewed-by: Haritabh Gupta <haritabh1992@gmail.com>
Discussion: https://postgr.es/m/CACJufxEtY1hdLcx=Fhnqp-ERcV1PhbvELG5COy_CZjoEW76ZPQ@mail.gmail.com
context: https://postgr.es/m/1326055327.15293.13.camel%40vanquo.pezone.net
commitfest: https://commitfest.postgresql.org/patch/6270
---
src/backend/commands/copyfrom.c | 2 +-
src/backend/executor/execMain.c | 80 +++++++++++++++--
src/backend/executor/execReplication.c | 4 +-
src/backend/executor/nodeModifyTable.c | 4 +-
src/include/executor/executor.h | 2 +-
src/include/nodes/execnodes.h | 7 +-
.../test_misc/t/001_constraint_validation.pl | 88 +++++++++++++++++++
7 files changed, 170 insertions(+), 17 deletions(-)
diff --git a/src/backend/commands/copyfrom.c b/src/backend/commands/copyfrom.c
index 3782db171be..169afa71a90 100644
--- a/src/backend/commands/copyfrom.c
+++ b/src/backend/commands/copyfrom.c
@@ -1357,7 +1357,7 @@ CopyFrom(CopyFromState cstate)
*/
if (resultRelInfo->ri_FdwRoutine == NULL &&
resultRelInfo->ri_RelationDesc->rd_att->constr)
- ExecConstraints(resultRelInfo, myslot, estate);
+ ExecConstraints(CMD_INSERT, resultRelInfo, myslot, estate);
/*
* Also check the tuple against the partition constraint, if
diff --git a/src/backend/executor/execMain.c b/src/backend/executor/execMain.c
index 6e47856cf25..a47efb3e49f 100644
--- a/src/backend/executor/execMain.c
+++ b/src/backend/executor/execMain.c
@@ -54,6 +54,7 @@
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "nodes/queryjumble.h"
+#include "optimizer/optimizer.h"
#include "parser/parse_relation.h"
#include "pgstat.h"
#include "rewrite/rewriteHandler.h"
@@ -1353,7 +1354,8 @@ InitResultRelInfo(ResultRelInfo *resultRelInfo,
resultRelInfo->ri_projectNewInfoValid = false;
resultRelInfo->ri_FdwState = NULL;
resultRelInfo->ri_usesFdwDirectModify = false;
- resultRelInfo->ri_CheckConstraintExprs = NULL;
+ resultRelInfo->ri_CheckConstraintExprsI = NULL;
+ resultRelInfo->ri_CheckConstraintExprsU = NULL;
resultRelInfo->ri_GenVirtualNotNullConstraintExprs = NULL;
resultRelInfo->ri_GeneratedExprsI = NULL;
resultRelInfo->ri_GeneratedExprsU = NULL;
@@ -1857,7 +1859,7 @@ ExecutePlan(QueryDesc *queryDesc,
* Returns NULL if OK, else name of failed check constraint
*/
static const char *
-ExecRelCheck(ResultRelInfo *resultRelInfo,
+ExecRelCheck(CmdType cmdtype, ResultRelInfo *resultRelInfo,
TupleTableSlot *slot, EState *estate)
{
Relation rel = resultRelInfo->ri_RelationDesc;
@@ -1865,6 +1867,7 @@ ExecRelCheck(ResultRelInfo *resultRelInfo,
ConstrCheck *check = rel->rd_att->constr->check;
ExprContext *econtext;
MemoryContext oldContext;
+ ExprState **checkExprs;
/*
* CheckNNConstraintFetch let this pass with only a warning, but now we
@@ -1875,15 +1878,35 @@ ExecRelCheck(ResultRelInfo *resultRelInfo,
elog(ERROR, "%d pg_constraint record(s) missing for relation \"%s\"",
rel->rd_rel->relchecks - ncheck, RelationGetRelationName(rel));
+ if (cmdtype != CMD_INSERT && cmdtype != CMD_UPDATE)
+ elog(ERROR, "unexpected command type: %d", (int) cmdtype);
+
+ if (cmdtype == CMD_INSERT)
+ checkExprs = resultRelInfo->ri_CheckConstraintExprsI;
+ else
+ checkExprs = resultRelInfo->ri_CheckConstraintExprsU;
+
/*
* If first time through for this result relation, build expression
* nodetrees for rel's constraint expressions. Keep them in the per-query
* memory context so they'll survive throughout the query.
*/
- if (resultRelInfo->ri_CheckConstraintExprs == NULL)
+ if (!checkExprs)
{
+ Bitmapset *updatedCols = NULL;
+
+ /*
+ * During an UPDATE, we may skip CHECK constraint verification. But if
+ * BEFORE ROW UPDATE trigger is present, the verification cannot be
+ * skipped as the trigger might modify additional columns
+ */
+ if (cmdtype == CMD_UPDATE &&
+ !(rel->trigdesc && rel->trigdesc->trig_update_before_row))
+ updatedCols = ExecGetAllUpdatedCols(resultRelInfo, estate);
+
oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
- resultRelInfo->ri_CheckConstraintExprs = palloc0_array(ExprState *, ncheck);
+ checkExprs = palloc0_array(ExprState *, ncheck);
+
for (int i = 0; i < ncheck; i++)
{
Expr *checkconstr;
@@ -1894,9 +1917,48 @@ ExecRelCheck(ResultRelInfo *resultRelInfo,
checkconstr = stringToNode(check[i].ccbin);
checkconstr = (Expr *) expand_generated_columns_in_expr((Node *) checkconstr, rel, 1);
- resultRelInfo->ri_CheckConstraintExprs[i] =
- ExecPrepareExpr(checkconstr, estate);
+
+ if (updatedCols)
+ {
+ bool skip = false;
+ Bitmapset *check_attrs = NULL;
+
+ pull_varattnos((Node *) checkconstr, 1, &check_attrs);
+
+ /*
+ * Skip verification of a check constraint during UPDATE if it
+ * is validated, references at least one column, contains no
+ * whole-row reference, and references none of the columns
+ * being updated: the unchanged columns already satisfied the
+ * constraint in the old tuple, so the new tuple satisfies it
+ * too.
+ */
+ skip = check_attrs &&
+ check[i].ccvalid &&
+ !bms_is_member(InvalidAttrNumber - FirstLowInvalidHeapAttributeNumber, check_attrs) &&
+ !bms_overlap(check_attrs, updatedCols);
+
+ bms_free(check_attrs);
+
+ if (skip)
+ {
+ ereport(DEBUG1,
+ errmsg_internal("skipping verification for constraint \"%s\" on table \"%s\"",
+ check[i].ccname,
+ RelationGetRelationName(rel)));
+
+ checkExprs[i] = NULL;
+ continue;
+ }
+ }
+ checkExprs[i] = ExecPrepareExpr(checkconstr, estate);
}
+
+ if (cmdtype == CMD_INSERT)
+ resultRelInfo->ri_CheckConstraintExprsI = checkExprs;
+ else
+ resultRelInfo->ri_CheckConstraintExprsU = checkExprs;
+
MemoryContextSwitchTo(oldContext);
}
@@ -1912,7 +1974,7 @@ ExecRelCheck(ResultRelInfo *resultRelInfo,
/* And evaluate the constraints */
for (int i = 0; i < ncheck; i++)
{
- ExprState *checkconstr = resultRelInfo->ri_CheckConstraintExprs[i];
+ ExprState *checkconstr = checkExprs[i];
/*
* NOTE: SQL specifies that a NULL result from a constraint expression
@@ -2059,7 +2121,7 @@ ExecPartitionCheckEmitError(ResultRelInfo *resultRelInfo,
* 'resultRelInfo' is the final result relation, after tuple routing.
*/
void
-ExecConstraints(ResultRelInfo *resultRelInfo,
+ExecConstraints(CmdType cmdtype, ResultRelInfo *resultRelInfo,
TupleTableSlot *slot, EState *estate)
{
Relation rel = resultRelInfo->ri_RelationDesc;
@@ -2109,7 +2171,7 @@ ExecConstraints(ResultRelInfo *resultRelInfo,
{
const char *failed;
- if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
+ if ((failed = ExecRelCheck(cmdtype, resultRelInfo, slot, estate)) != NULL)
{
char *val_desc;
Relation orig_rel = rel;
diff --git a/src/backend/executor/execReplication.c b/src/backend/executor/execReplication.c
index b2ca5cbf117..bdfb1356c3c 100644
--- a/src/backend/executor/execReplication.c
+++ b/src/backend/executor/execReplication.c
@@ -840,7 +840,7 @@ ExecSimpleRelationInsert(ResultRelInfo *resultRelInfo,
/* Check the constraints of the tuple */
if (rel->rd_att->constr)
- ExecConstraints(resultRelInfo, slot, estate);
+ ExecConstraints(CMD_INSERT, resultRelInfo, slot, estate);
if (rel->rd_rel->relispartition)
ExecPartitionCheck(resultRelInfo, slot, estate, true);
@@ -944,7 +944,7 @@ ExecSimpleRelationUpdate(ResultRelInfo *resultRelInfo,
/* Check the constraints of the tuple */
if (rel->rd_att->constr)
- ExecConstraints(resultRelInfo, slot, estate);
+ ExecConstraints(CMD_UPDATE, resultRelInfo, slot, estate);
if (rel->rd_rel->relispartition)
ExecPartitionCheck(resultRelInfo, slot, estate, true);
diff --git a/src/backend/executor/nodeModifyTable.c b/src/backend/executor/nodeModifyTable.c
index 3056b850f73..d8310ee4d48 100644
--- a/src/backend/executor/nodeModifyTable.c
+++ b/src/backend/executor/nodeModifyTable.c
@@ -1115,7 +1115,7 @@ ExecInsert(ModifyTableContext *context,
* Check the constraints of the tuple.
*/
if (resultRelationDesc->rd_att->constr)
- ExecConstraints(resultRelInfo, slot, estate);
+ ExecConstraints(CMD_INSERT, resultRelInfo, slot, estate);
/*
* Also check the tuple against the partition constraint, if there is
@@ -2577,7 +2577,7 @@ lreplace:
* have it validate all remaining checks.
*/
if (resultRelationDesc->rd_att->constr)
- ExecConstraints(resultRelInfo, slot, estate);
+ ExecConstraints(CMD_UPDATE, resultRelInfo, slot, estate);
/*
* replace the heap tuple
diff --git a/src/include/executor/executor.h b/src/include/executor/executor.h
index 190e8a4897a..e43173c1f46 100644
--- a/src/include/executor/executor.h
+++ b/src/include/executor/executor.h
@@ -258,7 +258,7 @@ extern void InitResultRelInfo(ResultRelInfo *resultRelInfo,
extern ResultRelInfo *ExecGetTriggerResultRel(EState *estate, Oid relid,
ResultRelInfo *rootRelInfo);
extern List *ExecGetAncestorResultRels(EState *estate, ResultRelInfo *resultRelInfo);
-extern void ExecConstraints(ResultRelInfo *resultRelInfo,
+extern void ExecConstraints(CmdType cmdtype, ResultRelInfo *resultRelInfo,
TupleTableSlot *slot, EState *estate);
extern AttrNumber ExecRelGenVirtualNotNull(ResultRelInfo *resultRelInfo,
TupleTableSlot *slot,
diff --git a/src/include/nodes/execnodes.h b/src/include/nodes/execnodes.h
index f0cb21444b2..08d3cd6d75b 100644
--- a/src/include/nodes/execnodes.h
+++ b/src/include/nodes/execnodes.h
@@ -584,8 +584,11 @@ typedef struct ResultRelInfo
/* list of WithCheckOption expr states */
List *ri_WithCheckOptionExprs;
- /* array of expr states for checking check constraints */
- ExprState **ri_CheckConstraintExprs;
+ /*
+ * Arrays of check constraint ExprStates for INSERT/UPDATE/MERGE.
+ */
+ ExprState **ri_CheckConstraintExprsI;
+ ExprState **ri_CheckConstraintExprsU;
/*
* array of expr states for checking not-null constraints on virtual
diff --git a/src/test/modules/test_misc/t/001_constraint_validation.pl b/src/test/modules/test_misc/t/001_constraint_validation.pl
index 6121c5bcae5..93cb8577dc1 100644
--- a/src/test/modules/test_misc/t/001_constraint_validation.pl
+++ b/src/test/modules/test_misc/t/001_constraint_validation.pl
@@ -333,6 +333,94 @@ like(
'updated partition constraint for default partition quuux_default1');
run_sql_command('DROP TABLE quuux;');
+note "test UPDATE operation skip enforced constraint vertification";
+
+# Check whether the run_sql_command output shows that the UPDATE operation
+# skipped constraint verification.
+sub is_constraint_skipped_by_update
+{
+ my $output = shift;
+ my $constr = shift;
+ return index($output, "DEBUG: skipping verification for constraint \"$constr\"") != -1;
+}
+
+run_sql_command(
+ 'CREATE TABLE upd_check_skip (
+ i int, a int default 11,
+ b int, c int,
+ d int generated always as (b+c) STORED,
+ e int generated always as (i) VIRTUAL) partition by range (i);
+
+ CREATE TABLE upd_check_skip_1(
+ a int default 12, i int,
+ c int, b int,
+ d int generated always as (b+1) STORED,
+ e int generated always as (b - 100) VIRTUAL);
+
+ ALTER TABLE upd_check_skip ATTACH PARTITION upd_check_skip_1 FOR VALUES FROM (0) TO (10);
+ CREATE TABLE upd_check_skip_2 PARTITION OF upd_check_skip FOR VALUES FROM (10) TO (30);
+ INSERT INTO upd_check_skip SELECT g + 8, g, -g-g, g+1 FROM generate_series(0, 7) g;
+ ALTER TABLE upd_check_skip ADD COLUMN f int;
+
+ ALTER TABLE upd_check_skip ADD CONSTRAINT cc1 CHECK(a + b < 1);
+ ALTER TABLE upd_check_skip ADD CONSTRAINT cc2 CHECK(a + c < 100);
+ ALTER TABLE upd_check_skip ADD CONSTRAINT cc3 CHECK(b < 1);
+ ALTER TABLE upd_check_skip ADD CONSTRAINT cc4 CHECK(d < 2); ');
+
+$output = run_sql_command('UPDATE upd_check_skip SET b = -7 WHERE i = 11;');
+ok(is_constraint_skipped_by_update($output, 'cc2'),
+ 'UPDATE skipped verification for constraint cc2');
+ok(!is_constraint_skipped_by_update($output, 'cc4'),
+ 'UPDATE does not skipped verification for constraint cc4');
+
+$output = run_sql_command('UPDATE upd_check_skip SET c = 3 WHERE i = 12;');
+ok(is_constraint_skipped_by_update($output, 'cc1'),
+ 'UPDATE skipped verification for constraint cc1');
+ok(is_constraint_skipped_by_update($output, 'cc3'),
+ 'UPDATE skipped verification for constraint cc3');
+ok(!is_constraint_skipped_by_update($output, 'cc4'),
+ 'UPDATE does not skipped verification for constraint cc4');
+
+$output = run_sql_command('UPDATE upd_check_skip SET f = 14 WHERE i = 13;');
+ok(is_constraint_skipped_by_update($output, 'cc4'),
+ 'UPDATE skipped verification for constraint cc4');
+
+$output = run_sql_command('
+ MERGE INTO upd_check_skip t USING (VALUES (12, -5), (18, 0)) AS s(a, b)
+ ON t.i = s.a
+ WHEN MATCHED THEN UPDATE SET b = s.b
+ WHEN NOT MATCHED BY TARGET THEN INSERT(i, a, b, c) VALUES (12, -3, -1, 2);');
+ok(is_constraint_skipped_by_update($output, 'cc2'),
+ 'UPDATE skipped verification for constraint cc2');
+
+run_sql_command(
+ 'CREATE FUNCTION dummy_update_func() RETURNS trigger AS $$
+ BEGIN
+ RETURN NEW;
+ END;
+ $$ LANGUAGE plpgsql;
+
+ CREATE TRIGGER upd_check_skip_row_trig_before
+ BEFORE UPDATE ON upd_check_skip
+ FOR EACH ROW
+ EXECUTE PROCEDURE dummy_update_func(); ');
+
+$output = run_sql_command('UPDATE upd_check_skip SET f = NULL');
+
+ok(!is_constraint_skipped_by_update($output, 'cc1'),
+ 'UPDATE does not skipped verification for constraint cc1');
+
+ok(!is_constraint_skipped_by_update($output, 'cc2'),
+ 'UPDATE does not skipped verification for constraint cc2');
+
+ok(!is_constraint_skipped_by_update($output, 'cc3'),
+ 'UPDATE does not skipped verification for constraint cc3');
+
+ok(!is_constraint_skipped_by_update($output, 'cc4'),
+ 'UPDATE does not skipped verification for constraint cc4');
+
+run_sql_command('drop table upd_check_skip;');
+
$node->stop('fast');
done_testing();
--
2.34.1
^ permalink raw reply [nested|flat] 11+ messages in thread
* Re: UPDATE run check constraints for affected columns only
2025-12-01 06:20 UPDATE run check constraints for affected columns only jian he <jian.universality@gmail.com>
2025-12-01 06:33 ` Re: UPDATE run check constraints for affected columns only Tom Lane <tgl@sss.pgh.pa.us>
2025-12-07 15:50 ` Re: UPDATE run check constraints for affected columns only jian he <jian.universality@gmail.com>
2026-01-23 02:09 ` Re: UPDATE run check constraints for affected columns only jian he <jian.universality@gmail.com>
2026-03-04 01:04 ` Re: UPDATE run check constraints for affected columns only jian he <jian.universality@gmail.com>
2026-03-05 03:12 ` Re: UPDATE run check constraints for affected columns only jian he <jian.universality@gmail.com>
2026-03-06 02:17 ` Re: UPDATE run check constraints for affected columns only jian he <jian.universality@gmail.com>
2026-03-06 16:10 ` Re: UPDATE run check constraints for affected columns only Florin Irion <irionr@gmail.com>
2026-03-07 09:46 ` Re: UPDATE run check constraints for affected columns only jian he <jian.universality@gmail.com>
2026-09-02 02:38 ` Re: UPDATE run check constraints for affected columns only jian he <jian.universality@gmail.com>
@ 2026-09-08 06:58 ` solai v <solai.cdac@gmail.com>
0 siblings, 0 replies; 11+ messages in thread
From: solai v @ 2026-09-08 06:58 UTC (permalink / raw)
To: jian he <jian.universality@gmail.com>; +Cc: Florin Irion <irionr@gmail.com>; pgsql-hackers; Haritabh Gupta <haritabh1992@gmail.com>
Hi,
I reviewed and tested the v8 patch for skipping unnecessary CHECK
constraint verification during UPDATE.
I reproduced the existing behavior before applying the patch and
tested the behavior again after applying it.
My observations after applying the patch:
-CHECK constraints on unaffected columns are skipped during UPDATE.
-CHECK constraints related to updated columns continue to be verified.
-CHECK constraint violations are still detected correctly.
-Generated column cases behaved as expected.
-The BEFORE UPDATE trigger case behaved correctly.
-MERGE with UPDATE and INSERT actions also behaved as expected.
I reviewed the regression tests added in 001_constraint_validation.pl
for the UPDATE, MERGE, and trigger cases.
git diff --check completed without any issues.
Overall, I did not observe any issues during my testing and the patch
behaved as expected.
Regards,
solai
^ permalink raw reply [nested|flat] 11+ messages in thread
end of thread, other threads:[~2026-09-08 06:58 UTC | newest]
Thread overview: 11+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2025-12-01 06:20 UPDATE run check constraints for affected columns only jian he <jian.universality@gmail.com>
2025-12-01 06:33 ` Tom Lane <tgl@sss.pgh.pa.us>
2025-12-07 15:50 ` jian he <jian.universality@gmail.com>
2026-01-23 02:09 ` jian he <jian.universality@gmail.com>
2026-03-04 01:04 ` jian he <jian.universality@gmail.com>
2026-03-05 03:12 ` jian he <jian.universality@gmail.com>
2026-03-06 02:17 ` jian he <jian.universality@gmail.com>
2026-03-06 16:10 ` Florin Irion <irionr@gmail.com>
2026-03-07 09:46 ` jian he <jian.universality@gmail.com>
2026-09-02 02:38 ` jian he <jian.universality@gmail.com>
2026-09-08 06:58 ` solai v <solai.cdac@gmail.com>
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