Enable fast default for domains with non-volatile constraints master github/master
authorAndrew Dunstan <andrew@dunslane.net>
Thu, 12 Mar 2026 21:53:09 +0000 (17:53 -0400)
committerAndrew Dunstan <andrew@dunslane.net>
Thu, 12 Mar 2026 22:05:01 +0000 (18:05 -0400)
commita0b6ef29a51818a4073a5f390ed10ef6453d5c11
treefab50cef20f91201dddf3d7e79a94e495ab99fac
parent487cf2cbd2f5a32cf9756eb9bd6dbf9f3956c8b7
Enable fast default for domains with non-volatile constraints

Previously, ALTER TABLE ADD COLUMN always forced a table rewrite when
the column type was a domain with constraints (CHECK or NOT NULL), even
if the default value satisfied those constraints.  This was because
contain_volatile_functions() considers CoerceToDomain immutable, so
the code conservatively assumed any constrained domain might fail.

Improve this by using soft error handling (ErrorSaveContext) to evaluate
the CoerceToDomain expression at ALTER TABLE time.  If the default value
passes the domain's constraints, the value is stored as a "missing"
attribute default and no table rewrite is needed.  If the constraint
check fails, we fall back to a table rewrite, preserving the historical
behavior that constraint violations are only raised when the table
actually contains rows.

Domains with volatile constraint expressions always require a table
rewrite since the constraint result could differ per evaluation and
cannot be cached.

Author: Jian He <jian.universality@gmail.com>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Andrew Dunstan <andrew@dunslane.net>
Reviewed-by: Viktor Holmberg <viktor.holmberg@aiven.io>
Discussion: https://postgr.es/m/CACJufxE_+iZBR1i49k_AHigppPwLTJi6km8NOsC7FWvKdEmmXg@mail.gmail.com
src/backend/commands/tablecmds.c
src/backend/executor/execExpr.c
src/include/executor/executor.h
src/test/regress/expected/fast_default.out
src/test/regress/sql/fast_default.sql