From 994a3c95bcc28c2586088083d034d9ef45f28c92 Mon Sep 17 00:00:00 2001
From: Tomas Vondra <tomas@vondra.me>
Date: Sun, 15 Nov 2026 21:03:11 +0100
Subject: [PATCH v1 10/11] Refine strictness checks for domain coercions

The unconditional CoerceToDomain check protects NULL-rejecting
domains, but also treats unconstrained casts as nonstrict. That
prevents otherwise valid STRICT SQL-function inlining and introduces
unnecessary PlaceHolderVars during subquery pull-up.

Use DomainHasConstraints() to distinguish these cases. Keep a
conservative nonstrict classification for any domain with constraints,
without trying to prove that individual CHECK expressions accept NULL.
For an unconstrained domain, continue checking the argument instead
of rejecting strictness immediately.

eval_const_expressions() replaces unconstrained CoerceToDomain nodes
with RelabelType and records a dependency on the domain. Adding
constraints to that same domain after planning invalidates the cached
plan, so replanning applies the conservative strictness check.
Dropping constraints from a retained coercion only makes its existing
placement or refusal to inline unnecessarily conservative.

Also remove the ERROR ON ERROR and NULL-constant exceptions for
JsonExpr domain results using JSON coercion. These cases can raise a
domain error for a NULL context item or path, violating the same
strictness requirement as returning a non-NULL value. These coercions
record no domain dependency, so their classification must not depend
on the current constraints.

Restore the original subselect plan and its comment now that the
unconstrained information_schema domain no longer needs a placeholder.

This does not close the planning-time invalidation window. Concurrent
ALTER DOMAIN can become visible between the strictness decision and
constant folding, leaving a constrained coercion where a strict one
was assumed, without the dependency used for removed coercions.
The original query need not depend on a domain introduced by SQL
inlining, and a generic plan still being built is not checked by the
invalidation callback. Cached executions can then keep raising
errors on NULL until the plan is invalidated for another reason.

Plans depending only on a derived domain can also miss invalidation
when constraints are added to its base domain, allowing an elided
coercion to skip the new checks. These pre-existing invalidation
problems are left for separate work.
---
 src/backend/optimizer/util/clauses.c    | 70 ++++++++++++-------------
 src/test/regress/expected/subselect.out | 10 ++--
 src/test/regress/sql/subselect.sql      |  4 +-
 3 files changed, 42 insertions(+), 42 deletions(-)

diff --git a/src/backend/optimizer/util/clauses.c b/src/backend/optimizer/util/clauses.c
index 1388d774eee..9f8f6d54715 100644
--- a/src/backend/optimizer/util/clauses.c
+++ b/src/backend/optimizer/util/clauses.c
@@ -1062,7 +1062,8 @@ max_parallel_hazard_walker(Node *node, max_parallel_hazard_context *context)
  *	  Recursively search for nonstrict functions within a clause.
  *
  * Returns true if any nonstrict construct is found --- ie, anything that
- * could produce non-NULL output with a NULL input.
+ * could produce non-NULL output with a NULL input, or raise an error for it
+ * (like a coercion to a domain rejecting NULL).
  *
  * The idea here is that the caller has verified that the expression contains
  * one or more Var or Param nodes (as appropriate for the caller's need), and
@@ -1163,11 +1164,25 @@ contain_nonstrict_functions_walker(Node *node, void *context)
 		return true;
 	else if (IsA(node, CoerceToDomain))
 	{
+		CoerceToDomain *cdomain = (CoerceToDomain *) node;
+
 		/*
-		 * Domain constraints can reject NULL.  Pull-up or strict-function
-		 * inlining must not introduce new constraint violations.
+		 * A coercion to a domain fails for NULL input if the domain has a NOT
+		 * NULL constraint, or a CHECK constraint that is false for NULL.  We
+		 * don't analyze the constraints, and treat the coercion as nonstrict
+		 * if there are any.  Relying on the current constraints is fine, as
+		 * eval_const_expressions() replaces a coercion to a domain without
+		 * constraints by a RelabelType, and makes the plan depend on the
+		 * domain, so that it gets rebuilt if constraints are added.
+		 *
+		 * XXX eval_const_expressions() replaces unconstrained coercions
+		 * with RelabelType and records a dependency on the domain. This
+		 * handles later changes to that domain, but not concurrent DDL
+		 * during planning or changes to a base domain.
 		 */
-		return true;
+		if (DomainHasConstraints(cdomain->resulttype, NULL))
+			return true;
+		/* else fall through to check args */
 	}
 	else if (IsA(node, CoerceViaIO))
 	{
@@ -1227,47 +1242,32 @@ contain_nonstrict_functions_walker(Node *node, void *context)
 
 /*
  * jsonexpr_has_nonstrict_inputs
- *		Check for variable inputs in non-strict parts of a JsonExpr.
- *
- * A JsonExpr is strict in its context item and path specification, whose
- * subexpressions the caller checks separately.  It is not strict in PASSING
- * arguments or ON EMPTY / ON ERROR defaults.  Callers may find their only
- * Var, PlaceHolderVar or Param there, so reject those cases.  Variable-free
- * inputs such as DEFAULT 0 do not preclude strictness.
- *
- * So the JsonExpr has to be considered nonstrict if any of those contains a
- * Var, PlaceHolderVar or Param. Constants are harmless there, and common
- * enough that we don't want to reject them (e.g. it would prevent inlining
- * SQL functions with DEFAULT 0).
- *
- * NULL propagation from the evaluated context/path does not prove strictness
- * of arbitrary subexpressions inside them.
- *
- * The exception is a JsonExpr with use_json_coercion and a domain RETURNING
- * type, as ExecEvalJsonExprPath() coerces even the NULL result to the domain
- * to check its constraints.  If the domain rejects NULL, ON ERROR applies,
- * so a NULL context item or path specification may produce a non-NULL ON
- * ERROR value, and the JsonExpr is not strict in any of its inputs.  We
- * don't check whether the domain actually rejects NULL, as its constraints
- * might change after planning.  If ON ERROR is ERROR or a NULL constant, the
- * result is either NULL or an error, which is fine (we treat CoerceToDomain
- * as strict too).
+ *      Check JsonExpr-specific reasons to reject strictness.
+ *
+ * Except for the domain case below, JsonExpr propagates NULL from its
+ * evaluated context item or path.  The caller must still check
+ * subexpressions for nonstrict constructs.
+ *
+ * PASSING values and ON EMPTY / ON ERROR defaults need not propagate
+ * NULL.  Reject Vars, PlaceHolderVars and Params there; constants alone
+ * do not preclude strictness.
+ *
+ * With use_json_coercion and a domain RETURNING type, even a NULL result
+ * is checked against the domain.  A rejected NULL can raise an error or
+ * produce a non-NULL ON ERROR value.  Treat this case as nonstrict
+ * regardless of current constraints, since this coercion records no
+ * domain dependency.
  */
 static bool
 jsonexpr_has_nonstrict_inputs(JsonExpr *jsexpr)
 {
-	JsonBehavior *on_error = jsexpr->on_error;
-
 	if (contain_var_or_param_walker((Node *) jsexpr->passing_values, NULL))
 		return true;
 	if (contain_var_or_param_walker((Node *) jsexpr->on_empty, NULL))
 		return true;
-	if (contain_var_or_param_walker((Node *) on_error, NULL))
+	if (contain_var_or_param_walker((Node *) jsexpr->on_error, NULL))
 		return true;
 	if (jsexpr->use_json_coercion &&
-		on_error->btype != JSON_BEHAVIOR_ERROR &&
-		!(IsA(on_error->expr, Const) &&
-		  ((Const *) on_error->expr)->constisnull) &&
 		get_typtype(jsexpr->returning->typid) == TYPTYPE_DOMAIN)
 		return true;
 	return false;
diff --git a/src/test/regress/expected/subselect.out b/src/test/regress/expected/subselect.out
index ac7646a3961..ef73218d9db 100644
--- a/src/test/regress/expected/subselect.out
+++ b/src/test/regress/expected/subselect.out
@@ -2457,8 +2457,8 @@ select * from json_tab t1 left join (select json_array(1, a) from json_tab t2) s
 
 rollback;
 --
--- Verify that a PlaceHolderVar around a subquery output domain cast
--- doesn't prevent index use after outer-join reduction
+-- Verify that we correctly flatten cases involving a subquery output
+-- expression that doesn't need to be wrapped in a PlaceHolderVar
 --
 explain (costs off)
 select tname, attname from (
@@ -2466,11 +2466,11 @@ select relname::information_schema.sql_identifier as tname, * from
   (select * from pg_class c) ss1) ss2
   right join pg_attribute a on a.attrelid = ss2.oid
 where tname = 'tenk1' and attnum = 1;
-                                         QUERY PLAN                                         
---------------------------------------------------------------------------------------------
+                                QUERY PLAN                                
+--------------------------------------------------------------------------
  Nested Loop
    ->  Index Scan using pg_class_relname_nsp_index on pg_class c
-         Index Cond: (((relname)::information_schema.sql_identifier)::name = 'tenk1'::name)
+         Index Cond: (relname = 'tenk1'::name)
    ->  Index Scan using pg_attribute_relid_attnum_index on pg_attribute a
          Index Cond: ((attrelid = c.oid) AND (attnum = 1))
 (5 rows)
diff --git a/src/test/regress/sql/subselect.sql b/src/test/regress/sql/subselect.sql
index 5c4d047ea6a..6db56b24b60 100644
--- a/src/test/regress/sql/subselect.sql
+++ b/src/test/regress/sql/subselect.sql
@@ -1225,8 +1225,8 @@ select * from json_tab t1 left join (select json_array(1, a) from json_tab t2) s
 rollback;
 
 --
--- Verify that a PlaceHolderVar around a subquery output domain cast
--- doesn't prevent index use after outer-join reduction
+-- Verify that we correctly flatten cases involving a subquery output
+-- expression that doesn't need to be wrapped in a PlaceHolderVar
 --
 
 explain (costs off)
-- 
2.56.0

