Re: sql/json query function JsonBehavior default expression's collation may differ from returning type's collation

From: jian he <jian(dot)universality(at)gmail(dot)com>
To: PostgreSQL-development <pgsql-hackers(at)postgresql(dot)org>
Subject: Re: sql/json query function JsonBehavior default expression's collation may differ from returning type's collation
Date: 2025-07-21 08:57:41
Message-ID: CACJufxEkttT9LY_Wi7A3C4A4vpXxmvnTsTchDCZMsaiQwMe4=w@mail.gmail.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

On Mon, Jul 14, 2025 at 7:39 PM jian he <jian(dot)universality(at)gmail(dot)com> wrote:
>
> overall, raising an error if the collation of the
> JsonBehavior DEFAULT clause differs from that of the RETURNING clause
> is the best option.
>
> what do you think?

in exprSetCollation, the node can be T_CollateExpr.
In that case, CollateExpr->collOid should be the same as the collation
of the caller.

--- a/src/backend/nodes/nodeFuncs.c
+++ b/src/backend/nodes/nodeFuncs.c
@@ -1131,6 +1131,10 @@ exprSetCollation(Node *expr, Oid collation)
case T_Const:
((Const *) expr)->constcollid = collation;
break;
+ case T_CollateExpr:
+ if (((CollateExpr *) expr)->collOid != collation)
+ elog(ERROR, "COLLATE clause collation should be %u",
collation);
+ break;
case T_Param:
((Param *) expr)->paramcollid = collation;
break;
diff --git a/src/backend/parser/parse_expr.c b/src/backend/parser/parse_expr.c
index d66276801c6..9cbffff52c3 100644
--- a/src/backend/parser/parse_expr.c
+++ b/src/backend/parser/parse_expr.c
@@ -4825,6 +4825,15 @@ transformJsonBehavior(ParseState *pstate,
JsonBehavior *behavior,
parser_errposition(pstate, exprLocation(expr)));
}

+ if (typcategory == TYPCATEGORY_STRING &&
+ exprCollation(coerced_expr) !=
get_typcollation(returning->typid))
+ {
+ ereport(ERROR,
+ errcode(ERRCODE_DATATYPE_MISMATCH),
+ errmsg("DEFAULT expression collation does not
match with RETURNING type's collation"),
+ parser_errposition(pstate,
exprLocation(coerced_expr)));
+ }
+

create table t(a jsonb);
select json_value(a, '$.c' returning text default 'A' collate "C" on
empty) from t;
ERROR: DEFAULT expression collation does not match with RETURNING
type's collation

as you can see, this query returns a set of rows. If the collation of the
DEFAULT node differs from the default text collation, the resulting set may have
inconscient collations.
a set of rows all the collation should be the same.
overall I think it should error out.

Attachment Content-Type Size
v1-0001-fix-SQL-JSON-default-expression-with-CollateExpr-node.patch text/x-patch 2.3 KB

In response to

Browse pgsql-hackers by date

  From Date Subject
Next Message Bertrand Drouvot 2025-07-21 09:06:22 Fix incorrect comment in pg_get_shmem_allocations_numa()
Previous Message Nazir Bilal Yavuz 2025-07-21 08:53:00 Re: Improve error reporting in 027_stream_regress test