From 6d37030020b95069fd3e57aa771355df406444a6 Mon Sep 17 00:00:00 2001 From: Amit Langote Date: Fri, 4 Dec 2026 12:13:17 +0900 Subject: [PATCH v2-REL_18] SQL/JSON: Decide how to coerce JsonExpr result in the executor JSON_VALUE() RETURNING a domain used a different method to coerce its result depending on whether the domain had constraints, so the result could differ from that of RETURNING the base type and could change when a constraint was added. The method was also chosen in the parser and stored in JsonExpr, so it could be out of date at execution. Choose the method in ExecInitJsonExpr() instead, based only on the function and the RETURNING type. The JsonExpr fields that stored the parser's choice, and the parser code that sets them, are left in place in this branch but no longer have any effect. JSON_VALUE() now always passes its result to the RETURNING type's input function, unless that type is text. That includes a NULL result if the input function is not strict, as domain_in() is, so that a domain's constraints are still checked for a NULL. The user-visible changes are: * JSON_VALUE() RETURNING a domain that has constraints now returns what RETURNING the domain's base type does. Its result used to be converted using json_populate_type(), which, for example, turns a JSON boolean into 'true' or 'false' where RETURNING text gives 't' or 'f', and formats a datetime item in ISO style regardless of DateStyle. * JSON_VALUE() RETURNING a domain over json or jsonb, with or without constraints, now returns what RETURNING json or jsonb does. It used to give the type's input function a string item without its quotes, so that, for example, "abc" was rejected as invalid JSON, which by default gave NULL, and "1" became the number 1. * A JSON_VALUE() expression stored before constraints were added to its RETURNING domain, in a view for instance, now behaves the same as one created afterwards. It used to keep the method chosen when it was parsed, which did not pass a NULL result to the input function, so that it could return NULL for a domain that had since been marked NOT NULL. * A jsonb string given as the DEFAULT for ON EMPTY or ON ERROR of JSON_VALUE() RETURNING json or jsonb, or a domain over one of them, now keeps its quotes when coerced to the RETURNING type. The coercion used to omit them as it does for other RETURNING types, so that "abc" was rejected as invalid JSON and "123" became the number 123. Indexes, stored generated columns and CHECK constraints that use such expressions may contain or have accepted values computed the old way, so they may need to be rebuilt or rechecked. To treat a domain over json or jsonb like its base type, the executor needs to know the RETURNING type's base type, which is looked up once in ExecInitJsonExpr() and saved in a new field, returning_json. The field is added to the EEOP_JSONEXPR_PATH step's member of the ExprEvalStep union, which has room to spare, so that no struct changes size in the back branches. While at it, improve the comments about how a JsonExpr is evaluated: describe the layout of the steps that ExecInitJsonExpr() emits, what JsonBehavior.coerce means, and a few things in ExecEvalJsonExprPath() that were left unexplained. Bug: #19851 Bug: #19825 Bug: #19971 Reported-by: Chunling Qin <303677365@qq.com> Reported-by: Yibo Dong Suggested-by: Tom Lane Reviewed-by: Ishjaap Singh Discussion: https://postgr.es/m/19851-f88328048ff9770a@postgresql.org Discussion: https://postgr.es/m/CA+Y2Bmcrp+aKua4nxip-nY17t4nhwHQxEr9Js_pvRnckBgH+YA@mail.gmail.com Discussion: https://postgr.es/m/19971-5a844714bd6f89f8@postgresql.org Backpatch-through: 17 --- src/backend/executor/execExpr.c | 92 +++++++++++-- src/backend/executor/execExprInterp.c | 96 ++++++++----- src/backend/parser/parse_expr.c | 5 + src/include/executor/execExpr.h | 11 +- src/include/nodes/execnodes.h | 12 +- src/include/nodes/primnodes.h | 17 ++- .../regress/expected/sqljson_jsontable.out | 4 +- .../regress/expected/sqljson_queryfuncs.out | 127 ++++++++++++++++++ src/test/regress/sql/sqljson_queryfuncs.sql | 58 ++++++++ 9 files changed, 372 insertions(+), 50 deletions(-) diff --git a/src/backend/executor/execExpr.c b/src/backend/executor/execExpr.c index 6f237be710e..41f49353ea8 100644 --- a/src/backend/executor/execExpr.c +++ b/src/backend/executor/execExpr.c @@ -4775,6 +4775,23 @@ ExecBuildParamSetEqual(TupleDesc desc, /* * Push steps to evaluate a JsonExpr and its various subsidiary expressions. + * + * The steps are laid out as follows, with those in brackets added only if + * needed: + * + * steps to evaluate formatted_expr, path_spec, and PASSING arguments + * EEOP_JSONEXPR_PATH + * [EEOP_JSONEXPR_COERCION, EEOP_JSONEXPR_COERCION_FINISH] + * [steps to check for an error and evaluate the ON ERROR expression] + * [steps to check for no items and evaluate the ON EMPTY expression] + * + * EEOP_JSONEXPR_PATH evaluates the jsonpath and returns the address of the + * step to continue with, which is the first step of one of the groups that + * follow it, or the address just past the last step if there is nothing more + * to do. Those addresses are saved in JsonExprState as jump_eval_coercion, + * jump_error, jump_empty, and jump_end, respectively. The ON ERROR steps + * come right after the coercion steps so that an error saved by the latter + * is handled by the former as well. */ static void ExecInitJsonExpr(JsonExpr *jsexpr, ExprState *state, @@ -4788,8 +4805,16 @@ ExecInitJsonExpr(JsonExpr *jsexpr, ExprState *state, List *jumps_to_end = NIL; ListCell *lc; ErrorSaveContext *escontext; + Oid returning_typid = jsexpr->returning->typid; bool returning_domain = - get_typtype(jsexpr->returning->typid) == TYPTYPE_DOMAIN; + get_typtype(returning_typid) == TYPTYPE_DOMAIN; + Oid returning_basetypid = returning_domain ? + getBaseType(returning_typid) : returning_typid; + bool returning_json = (returning_basetypid == JSONOID || + returning_basetypid == JSONBOID); + bool behavior_omit_quotes; + bool use_io_coercion = false; + bool use_json_coercion = false; Assert(jsexpr->on_error != NULL); @@ -4863,6 +4888,7 @@ ExecInitJsonExpr(JsonExpr *jsexpr, ExprState *state, scratch->resvalue = resv; scratch->resnull = resnull; scratch->d.jsonexpr.jsestate = jsestate; + scratch->d.jsonexpr.returning_json = returning_json; ExprEvalPushStep(state, scratch); escontext = jsexpr->on_error->btype != JSON_BEHAVIOR_ERROR ? @@ -4876,11 +4902,51 @@ ExecInitJsonExpr(JsonExpr *jsexpr, ExprState *state, jsestate->escontext.type = T_ErrorSaveContext; /* - * Steps to coerce the result value computed by EEOP_JSONEXPR_PATH or the - * NULL that it returns on NULL input. + * Decide how to coerce the result value computed by EEOP_JSONEXPR_PATH, + * or the NULL that it returns on NULL input, to the RETURNING type. There + * are two methods: + * + * "JSON coercion" adds an EEOP_JSONEXPR_COERCION step that passes the + * jsonb-valued result to json_populate_type(), which, unlike a type's + * input function, can convert a JSON object or array to a composite or + * array type. It is used for JSON_QUERY(), whose result can be an object + * or an array, and for JSON_EXISTS() when a JSON_TABLE() column specifies + * a non-boolean type. + * + * "I/O coercion" converts the scalar result of JSON_VALUE() to a string + * and passes it to the RETURNING type's input function, which is done by + * ExecEvalJsonExprPath() itself without an additional step. The string + * is the item's JSON text if the RETURNING type is json or jsonb, or a + * domain over one of them, and its plain text value otherwise. + * + * No coercion is needed if the result is already of the RETURNING type. + * + * Note that the two methods do not always produce the same value for a + * given JSON item; for example, a JSON boolean converted to text is 't' + * with I/O coercion and 'true' with JSON coercion. Either method checks + * the constraints of a domain: I/O coercion in domain_in() and JSON + * coercion in populate_domain(). */ + switch (jsexpr->op) + { + case JSON_EXISTS_OP: + use_json_coercion = (returning_typid != BOOLOID); + break; + case JSON_QUERY_OP: + use_json_coercion = (returning_typid != JSONBOID || + jsexpr->omit_quotes); + break; + case JSON_VALUE_OP: + use_io_coercion = (returning_typid != TEXTOID); + break; + default: + elog(ERROR, "unrecognized SQL/JSON expression op %d", + (int) jsexpr->op); + break; + } + jsestate->jump_eval_coercion = -1; - if (jsexpr->use_json_coercion) + if (use_json_coercion) { jsestate->jump_eval_coercion = state->steps_len; @@ -4889,7 +4955,7 @@ ExecInitJsonExpr(JsonExpr *jsexpr, ExprState *state, jsexpr->op == JSON_EXISTS_OP, resv, resnull); } - else if (jsexpr->use_io_coercion) + else if (use_io_coercion) { /* * Here we only need to initialize the FunctionCallInfo for the target @@ -4901,7 +4967,7 @@ ExecInitJsonExpr(JsonExpr *jsexpr, ExprState *state, FmgrInfo *finfo; FunctionCallInfo fcinfo; - getTypeInputInfo(jsexpr->returning->typid, &typinput, &typioparam); + getTypeInputInfo(returning_typid, &typinput, &typioparam); finfo = palloc0(sizeof(FmgrInfo)); fcinfo = palloc0(SizeForFunctionCallInfo(3)); fmgr_info(typinput, finfo); @@ -4935,6 +5001,16 @@ ExecInitJsonExpr(JsonExpr *jsexpr, ExprState *state, jsestate->jump_empty = jsestate->jump_error = -1; + /* + * JSON_VALUE() normally omits the quotes of a JSON string, but not when + * the RETURNING type is json or jsonb, or a domain over one of them; see + * ExecEvalJsonExprPath(). Do likewise when coercing the ON ERROR and ON + * EMPTY expressions, so that, for example, a jsonb string given as the + * DEFAULT is not turned into a number or rejected as invalid JSON. + */ + behavior_omit_quotes = jsexpr->omit_quotes && + !(jsexpr->op == JSON_VALUE_OP && returning_json); + /* * Step to check jsestate->error and return the ON ERROR expression if * there is one. This handles both the errors that occur during jsonpath @@ -4977,7 +5053,7 @@ ExecInitJsonExpr(JsonExpr *jsexpr, ExprState *state, /* Step to coerce the ON ERROR expression if needed */ if (jsexpr->on_error->coerce) ExecInitJsonCoercion(state, jsexpr->returning, escontext, - jsexpr->omit_quotes, false, + behavior_omit_quotes, false, resv, resnull); /* @@ -5037,7 +5113,7 @@ ExecInitJsonExpr(JsonExpr *jsexpr, ExprState *state, /* Step to coerce the ON EMPTY expression if needed */ if (jsexpr->on_empty->coerce) ExecInitJsonCoercion(state, jsexpr->returning, escontext, - jsexpr->omit_quotes, false, + behavior_omit_quotes, false, resv, resnull); /* diff --git a/src/backend/executor/execExprInterp.c b/src/backend/executor/execExprInterp.c index 47ef4714df6..6537e8c281e 100644 --- a/src/backend/executor/execExprInterp.c +++ b/src/backend/executor/execExprInterp.c @@ -4895,15 +4895,23 @@ ExecEvalJsonIsPredicate(ExprState *state, ExprEvalStep *op) * JsonExprState.error and JsonExprState.empty are reset for every row before * the ON ERROR / ON EMPTY steps look at them. In that case, the result is * NULL and jsonpath evaluation is skipped, as are the ON ERROR / ON EMPTY - * steps; the NULL is still passed through the coercion steps, if any, so that - * the constraints of a RETURNING domain type are checked. + * steps; the NULL is still coerced to the RETURNING type if that is a domain, + * so that its constraints are checked. + * + * The result is converted to the RETURNING type in one of the two ways that + * ExecInitJsonExpr() chooses between. If JsonExprState.input_fcinfo is set, + * which can only be the case for JSON_VALUE(), that is done right here by + * passing the result's string form to the RETURNING type's input function. + * Otherwise, if JsonExprState.jump_eval_coercion is valid, that address is + * returned so that the EEOP_JSONEXPR_COERCION step found there does it. If + * neither is the case, the result is already of the RETURNING type. * * If an error occurs during JsonPath* evaluation or when coercing its result - * to the RETURNING type, JsonExprState.error is set to true, provided the - * ON ERROR behavior is not ERROR. Similarly, if JsonPath{Query|Value}() found - * no matching items, JsonExprState.empty is set to true, provided the ON EMPTY - * behavior is not ERROR. That is to signal to the subsequent steps that check - * those flags to return the ON ERROR / ON EMPTY expression. + * to the RETURNING type here, JsonExprState.error is set to true, provided + * the ON ERROR behavior is not ERROR. Similarly, if JsonPath{Query|Value}() + * found no matching items, JsonExprState.empty is set to true, provided the + * ON EMPTY behavior is not ERROR. That is to signal to the subsequent steps + * that check those flags to return the ON ERROR / ON EMPTY expression. * * Return value is the step address to be performed next. It will be one of * jump_error, jump_empty, jump_eval_coercion, or jump_end, all given in @@ -4937,9 +4945,9 @@ ExecEvalJsonExprPath(ExprState *state, ExprEvalStep *op, /* * Return NULL if formatted_expr or pathspec is NULL, skipping the ON - * ERROR and ON EMPTY steps. If the RETURNING type is a domain with - * constraints, the NULL must still be coerced to it so that the - * constraints are checked. + * ERROR and ON EMPTY steps. The NULL still goes through whichever + * coercion ExecInitJsonExpr() set up, if any, because if the RETURNING + * type is a domain, its constraints must be checked. */ if (jsestate->formatted_expr.isnull || jsestate->pathspec.isnull) { @@ -4948,6 +4956,8 @@ ExecEvalJsonExprPath(ExprState *state, ExprEvalStep *op, if (jump_eval_coercion >= 0) return jump_eval_coercion; + else if (jsestate->input_fcinfo != NULL) + goto coerce_via_input; else return jsestate->jump_end; } @@ -4987,36 +4997,46 @@ ExecEvalJsonExprPath(ExprState *state, ExprEvalStep *op, jsestate->args, jsexpr->column_name); + /* + * JsonPathValue() returns NULL if an error occurred, if no + * item was found, or if the item found is a JSON null. The + * first two cases are dealt with further below by looking at + * 'error' and 'empty'. A JSON null becomes an SQL NULL. + */ if (jbv == NULL) { - /* Will be coerced with json_populate_type(), if needed. */ + /* Will be passed to the input function, if needed. */ *op->resvalue = (Datum) 0; *op->resnull = true; } else if (!error && !empty) { - if (jsexpr->returning->typid == JSONOID || - jsexpr->returning->typid == JSONBOID) + if (op->d.jsonexpr.returning_json) { + /* + * The item is to be returned as json or jsonb, so + * pass it to the input function as JSON text; for + * example, a string item keeps its quotes. + */ val_string = DatumGetCString(DirectFunctionCall1(jsonb_out, JsonbPGetDatum(JsonbValueToJsonb(jbv)))); *op->resnull = false; } - else if (jsexpr->use_json_coercion) - { - *op->resvalue = JsonbPGetDatum(JsonbValueToJsonb(jbv)); - *op->resnull = false; - } else { - /* ExecGetJsonValueItemString() sets *op->resnull. */ + /* + * Otherwise, pass the item's value as plain text; for + * example, a string item without its quotes. + * + * ExecGetJsonValueItemString() sets *op->resnull. + */ val_string = ExecGetJsonValueItemString(jbv, op->resnull); /* * Simply convert to the default RETURNING type (text) * if no coercion needed. */ - if (!jsexpr->use_io_coercion) + if (jsestate->input_fcinfo == NULL) *op->resvalue = DirectFunctionCall1(textin, CStringGetDatum(val_string)); } @@ -5032,18 +5052,27 @@ ExecEvalJsonExprPath(ExprState *state, ExprEvalStep *op, return false; } +coerce_via_input: + /* * Coerce the result value to the RETURNING type by calling its input - * function. + * function, if ExecInitJsonExpr() decided to do it that way. + * + * As in InputFunctionCall(), a NULL is passed only to an input function + * that is not strict. That matters for domain_in(), which must get to + * see a NULL result to be able to check the domain's constraints. + * + * This is skipped if an error occurred or no item was found. The result + * is NULL in those cases too, but what to return is for the ON ERROR and + * ON EMPTY handling below to decide. */ - if (!*op->resnull && jsexpr->use_io_coercion) + if (jsestate->input_fcinfo != NULL && !error && !empty && + (!*op->resnull || !jsestate->input_fcinfo->flinfo->fn_strict)) { - FunctionCallInfo fcinfo; + FunctionCallInfo fcinfo = jsestate->input_fcinfo; Assert(jump_eval_coercion == -1); - fcinfo = jsestate->input_fcinfo; - Assert(fcinfo != NULL); - Assert(val_string != NULL); + Assert(*op->resnull || val_string != NULL); fcinfo->args[0].value = PointerGetDatum(val_string); fcinfo->args[0].isnull = *op->resnull; @@ -5054,16 +5083,21 @@ ExecEvalJsonExprPath(ExprState *state, ExprEvalStep *op, fcinfo->isnull = false; *op->resvalue = FunctionCallInvoke(fcinfo); + /* The result can be NULL if a NULL was passed. */ + *op->resnull = fcinfo->isnull; if (SOFT_ERROR_OCCURRED(&jsestate->escontext)) error = true; } /* - * When setting up the ErrorSaveContext (if needed) for capturing the - * errors that occur when coercing the JsonBehavior expression, set - * details_wanted to be able to show the actual error message as the - * DETAIL of the error message that tells that it is the JsonBehavior - * expression that caused the error; see ExecEvalJsonCoercionFinish(). + * Now figure out which step to continue with. + * + * In the cases below where an ON EMPTY or ON ERROR expression is going to + * be evaluated next, the ErrorSaveContext is set up afresh to capture any + * error that occurs when evaluating or coercing that expression. + * details_wanted is set so as to be able to show the actual error message + * as the DETAIL of the error that says that it is the ON EMPTY or ON + * ERROR expression that caused it; see ExecEvalJsonCoercionFinish(). */ /* Handle ON EMPTY. */ diff --git a/src/backend/parser/parse_expr.c b/src/backend/parser/parse_expr.c index 47ab7600177..e6f29fd05c9 100644 --- a/src/backend/parser/parse_expr.c +++ b/src/backend/parser/parse_expr.c @@ -4547,6 +4547,11 @@ transformJsonFuncExpr(ParseState *pstate, JsonFuncExpr *func) /* Transform the JsonOutput into JsonReturning. */ jsexpr->returning = transformJsonOutput(pstate, func->output, false); + /* + * Note that the settings of use_io_coercion and use_json_coercion made + * below have no effect, because the executor does not look at them; see + * the comments for those fields in primnodes.h. + */ switch (func->op) { case JSON_EXISTS_OP: diff --git a/src/include/executor/execExpr.h b/src/include/executor/execExpr.h index c890138e7a5..b512af8a372 100644 --- a/src/include/executor/execExpr.h +++ b/src/include/executor/execExpr.h @@ -751,10 +751,19 @@ typedef struct ExprEvalStep JsonIsPredicate *pred; /* original expression node */ } is_json; - /* for EEOP_JSONEXPR_PATH */ + /* for EEOP_JSONEXPR_PATH and EEOP_JSONEXPR_COERCION_FINISH */ struct { struct JsonExprState *jsestate; + + /* + * Only used by EEOP_JSONEXPR_PATH. + * + * True if the RETURNING type is json or jsonb, or a domain over + * one of them. JSON_VALUE() then passes its result to the type's + * input function in JSON text form. + */ + bool returning_json; } jsonexpr; /* for EEOP_JSONEXPR_COERCION */ diff --git a/src/include/nodes/execnodes.h b/src/include/nodes/execnodes.h index 25efeb1a8a6..17ac115abed 100644 --- a/src/include/nodes/execnodes.h +++ b/src/include/nodes/execnodes.h @@ -1091,9 +1091,10 @@ typedef struct JsonExprState int jump_error; /* - * Address of the step to coerce the result value of jsonpath evaluation - * to the RETURNING type. -1 if no coercion if JsonExpr.use_io_coercion - * is true. + * Address of the EEOP_JSONEXPR_COERCION step to coerce the result value + * of jsonpath evaluation to the RETURNING type using + * json_populate_type(). -1 if the result needs no coercion or is coerced + * by calling the RETURNING type's input function (see input_fcinfo). */ int jump_eval_coercion; @@ -1106,8 +1107,9 @@ typedef struct JsonExprState int jump_end; /* - * RETURNING type input function invocation info when - * JsonExpr.use_io_coercion is true. + * RETURNING type input function invocation info, if the result value of + * jsonpath evaluation is to be coerced by ExecEvalJsonExprPath() itself + * by calling that function; NULL otherwise. */ FunctionCallInfo input_fcinfo; diff --git a/src/include/nodes/primnodes.h b/src/include/nodes/primnodes.h index 42a9df89a31..1ce048c40ef 100644 --- a/src/include/nodes/primnodes.h +++ b/src/include/nodes/primnodes.h @@ -1794,9 +1794,16 @@ typedef enum JsonBehaviorType * query functions specified by a JsonExpr * * 'expr' is the expression to emit when a given behavior (EMPTY or ERROR) - * occurs on evaluating the SQL/JSON query function. 'coerce' is set to true - * if 'expr' isn't already of the expected target type given by - * JsonExpr.returning. + * occurs on evaluating the SQL/JSON query function. It is NULL if the + * behavior is to throw the error. + * + * The value emitted must be of the type given by JsonExpr.returning. If + * 'expr' is not of that type to begin with, the parser arranges for it to be + * converted in one of two ways. Either it adds a cast to that type on top + * of 'expr', and 'coerce' is false; or it adds no cast and sets 'coerce' to + * true, which tells the executor to convert the value of 'expr' at run time + * by passing it to json_populate_type(), as is done for the result of + * JSON_QUERY(). See transformJsonBehavior() for which is used when. */ typedef struct JsonBehavior { @@ -1857,6 +1864,10 @@ typedef struct JsonExpr /* * Information about converting the result of jsonpath functions * JsonPathQuery() and JsonPathValue() to the RETURNING type. + * + * No longer used; the executor decides on its own how to coerce the + * result, see ExecInitJsonExpr(). Kept, and still set by the parser, to + * preserve the stored representation of JsonExpr in this branch. */ bool use_io_coercion; bool use_json_coercion; diff --git a/src/test/regress/expected/sqljson_jsontable.out b/src/test/regress/expected/sqljson_jsontable.out index 35d974c1016..7b160519677 100644 --- a/src/test/regress/expected/sqljson_jsontable.out +++ b/src/test/regress/expected/sqljson_jsontable.out @@ -106,8 +106,8 @@ FROM json_table_test vals [1, 1.23, "2", "aaaaaaa", "foo", null, false, true, {"aaa": 123}, "[1,2]", "\"str\""] | 4 | | aaaaaaa | | | | aaaaaaa | "aaaaaaa" | "aaaaaaa" [1, 1.23, "2", "aaaaaaa", "foo", null, false, true, {"aaa": 123}, "[1,2]", "\"str\""] | 5 | | foo | foo | | | | "foo" | "foo" [1, 1.23, "2", "aaaaaaa", "foo", null, false, true, {"aaa": 123}, "[1,2]", "\"str\""] | 6 | | | | | | | null | null - [1, 1.23, "2", "aaaaaaa", "foo", null, false, true, {"aaa": 123}, "[1,2]", "\"str\""] | 7 | | f | f | f | | false | false | false - [1, 1.23, "2", "aaaaaaa", "foo", null, false, true, {"aaa": 123}, "[1,2]", "\"str\""] | 8 | | t | t | t | | true | true | true + [1, 1.23, "2", "aaaaaaa", "foo", null, false, true, {"aaa": 123}, "[1,2]", "\"str\""] | 7 | | f | f | f | | f | false | false + [1, 1.23, "2", "aaaaaaa", "foo", null, false, true, {"aaa": 123}, "[1,2]", "\"str\""] | 8 | | t | t | t | | t | true | true [1, 1.23, "2", "aaaaaaa", "foo", null, false, true, {"aaa": 123}, "[1,2]", "\"str\""] | 9 | | | | | | | {"aaa": 123} | {"aaa": 123} [1, 1.23, "2", "aaaaaaa", "foo", null, false, true, {"aaa": 123}, "[1,2]", "\"str\""] | 10 | | [1,2] | | | | [1,2] | "[1,2]" | "[1,2]" [1, 1.23, "2", "aaaaaaa", "foo", null, false, true, {"aaa": 123}, "[1,2]", "\"str\""] | 11 | | "str" | | | | "str" | "\"str\"" | "\"str\"" diff --git a/src/test/regress/expected/sqljson_queryfuncs.out b/src/test/regress/expected/sqljson_queryfuncs.out index 84de879ac18..bb7c3c587fa 100644 --- a/src/test/regress/expected/sqljson_queryfuncs.out +++ b/src/test/regress/expected/sqljson_queryfuncs.out @@ -1778,3 +1778,130 @@ SELECT JSON_VALUE(x, '$' RETURNING jsonb) FROM (VALUES ('1'::jsonb), (NULL), ('2 2 (3 rows) +-- JSON_VALUE() RETURNING a domain must give the same result as RETURNING +-- its base type, whether or not the domain has constraints (bug #19851). +CREATE DOMAIN queryfuncs_dtext AS text; +CREATE DOMAIN queryfuncs_dtext_chk AS text CHECK (true); +CREATE DOMAIN queryfuncs_dchar3 AS char(3); +CREATE DOMAIN queryfuncs_dchar3_chk AS char(3) CHECK (true); +CREATE DOMAIN queryfuncs_djsonb AS jsonb; +CREATE DOMAIN queryfuncs_djsonb_chk AS jsonb CHECK (true); +CREATE DOMAIN queryfuncs_djson AS json; +CREATE DOMAIN queryfuncs_djson_chk AS json CHECK (true); +SELECT JSON_VALUE(jsonb 'true', '$' RETURNING text) AS base, + JSON_VALUE(jsonb 'true', '$' RETURNING queryfuncs_dtext) AS dom, + JSON_VALUE(jsonb 'true', '$' RETURNING queryfuncs_dtext_chk) AS dom_chk; + base | dom | dom_chk +------+-----+--------- + t | t | t +(1 row) + +SELECT JSON_VALUE(jsonb 'true', '$' RETURNING char(3)) AS base, + JSON_VALUE(jsonb 'true', '$' RETURNING queryfuncs_dchar3) AS dom, + JSON_VALUE(jsonb 'true', '$' RETURNING queryfuncs_dchar3_chk) AS dom_chk; + base | dom | dom_chk +------+-----+--------- + t | t | t +(1 row) + +SELECT JSON_VALUE(x, '$' RETURNING jsonb) AS base, + JSON_VALUE(x, '$' RETURNING queryfuncs_djsonb) AS dom, + JSON_VALUE(x, '$' RETURNING queryfuncs_djsonb_chk) AS dom_chk + FROM (VALUES (jsonb 'true'), ('"1"'), ('null'), ('1.5')) v(x); + base | dom | dom_chk +------+------+--------- + true | true | true + "1" | "1" | "1" + | | + 1.5 | 1.5 | 1.5 +(4 rows) + +SELECT JSON_VALUE(x, '$' RETURNING json) AS base, + JSON_VALUE(x, '$' RETURNING queryfuncs_djson) AS dom, + JSON_VALUE(x, '$' RETURNING queryfuncs_djson_chk) AS dom_chk + FROM (VALUES (jsonb 'true'), ('"1"'), ('null'), ('1.5')) v(x); + base | dom | dom_chk +------+------+--------- + true | true | true + "1" | "1" | "1" + | | + 1.5 | 1.5 | 1.5 +(4 rows) + +-- Likewise for the ON EMPTY and ON ERROR expressions: a jsonb string given +-- as the DEFAULT must keep its quotes when coerced to json, jsonb, or a +-- domain over one of them (bug #19971). +SELECT JSON_VALUE(jsonb '{}', '$.a' RETURNING json DEFAULT '"123"'::jsonb ON EMPTY) AS on_empty, + JSON_VALUE(jsonb '{}', 'strict $.a' RETURNING json DEFAULT '"123"'::jsonb ON ERROR) AS on_error, + JSON_VALUE(jsonb '{}', '$.a' RETURNING json DEFAULT '"abc"'::jsonb ON EMPTY) AS not_a_number; + on_empty | on_error | not_a_number +----------+----------+-------------- + "123" | "123" | "abc" +(1 row) + +SELECT JSON_VALUE(jsonb '{}', '$.a' RETURNING queryfuncs_djson DEFAULT '"123"'::jsonb ON EMPTY) AS djson, + JSON_VALUE(jsonb '{}', '$.a' RETURNING queryfuncs_djson_chk DEFAULT '"123"'::jsonb ON EMPTY) AS djson_chk, + JSON_VALUE(jsonb '{}', '$.a' RETURNING queryfuncs_djsonb DEFAULT '"123"'::jsonb ON EMPTY) AS djsonb, + JSON_VALUE(jsonb '{}', '$.a' RETURNING queryfuncs_djsonb_chk DEFAULT '"123"'::jsonb ON EMPTY) AS djsonb_chk; + djson | djson_chk | djsonb | djsonb_chk +-------+-----------+--------+------------ + "123" | "123" | "123" | "123" +(1 row) + +-- but not when coerced to other types +SELECT JSON_VALUE(jsonb '{}', '$.a' RETURNING text DEFAULT '"abc"'::jsonb ON EMPTY) AS text, + JSON_VALUE(jsonb '{}', '$.a' RETURNING int DEFAULT '"123"'::jsonb ON EMPTY) AS int; + text | int +------+----- + abc | 123 +(1 row) + +-- a JsonExpr stored before the domain got a constraint behaves the same as +-- one created after +CREATE VIEW queryfuncs_dtext_view AS + SELECT JSON_VALUE(x, '$' RETURNING queryfuncs_dtext) AS v + FROM (VALUES (jsonb 'true'), ('"a"'), ('null')) v(x); +SELECT * FROM queryfuncs_dtext_view; + v +--- + t + a + +(3 rows) + +ALTER DOMAIN queryfuncs_dtext ADD CHECK (VALUE <> 't'); +SELECT * FROM queryfuncs_dtext_view; + v +--- + + a + +(3 rows) + +SELECT JSON_VALUE(jsonb 'true', '$' RETURNING queryfuncs_dtext); + json_value +------------ + +(1 row) + +SELECT JSON_VALUE(jsonb 'true', '$' RETURNING queryfuncs_dtext ERROR ON ERROR); +ERROR: value for domain queryfuncs_dtext violates check constraint "queryfuncs_dtext_check" +-- a NULL result must still be checked against the domain's constraints +ALTER DOMAIN queryfuncs_dtext ADD CHECK (VALUE IS NOT NULL); +SELECT * FROM queryfuncs_dtext_view; +ERROR: could not coerce ON ERROR expression (NULL) to the RETURNING type +DETAIL: value for domain queryfuncs_dtext violates check constraint "queryfuncs_dtext_check1" +SELECT JSON_VALUE(jsonb 'null', '$' RETURNING queryfuncs_dtext ERROR ON ERROR); +ERROR: value for domain queryfuncs_dtext violates check constraint "queryfuncs_dtext_check1" +SELECT JSON_VALUE(NULL::jsonb, '$' RETURNING queryfuncs_dtext ERROR ON ERROR); +ERROR: value for domain queryfuncs_dtext violates check constraint "queryfuncs_dtext_check1" +SELECT JSON_VALUE(NULL::jsonb, '$' RETURNING queryfuncs_dtext DEFAULT 'dflt' ON ERROR); + json_value +------------ + dflt +(1 row) + +DROP VIEW queryfuncs_dtext_view; +DROP DOMAIN queryfuncs_dtext, queryfuncs_dtext_chk, queryfuncs_dchar3, + queryfuncs_dchar3_chk, queryfuncs_djsonb, queryfuncs_djsonb_chk, + queryfuncs_djson, queryfuncs_djson_chk; diff --git a/src/test/regress/sql/sqljson_queryfuncs.sql b/src/test/regress/sql/sqljson_queryfuncs.sql index 5f2b5077ed8..353b3581f30 100644 --- a/src/test/regress/sql/sqljson_queryfuncs.sql +++ b/src/test/regress/sql/sqljson_queryfuncs.sql @@ -616,3 +616,61 @@ SELECT JSON_VALUE(x, '$' RETURNING json) FROM (VALUES ('1'::json), ('null'), ('2 SELECT JSON_VALUE(x, '$.a' RETURNING jsonb) FROM (VALUES ('{"a": 1}'::jsonb), ('{}'), ('{"a": 2}')) v(x); SELECT JSON_VALUE(x, 'strict $.a' RETURNING jsonb) FROM (VALUES ('{"a": 1}'::jsonb), ('[]'), ('{"a": 2}')) v(x); SELECT JSON_VALUE(x, '$' RETURNING jsonb) FROM (VALUES ('1'::jsonb), (NULL), ('2')) v(x); + +-- JSON_VALUE() RETURNING a domain must give the same result as RETURNING +-- its base type, whether or not the domain has constraints (bug #19851). +CREATE DOMAIN queryfuncs_dtext AS text; +CREATE DOMAIN queryfuncs_dtext_chk AS text CHECK (true); +CREATE DOMAIN queryfuncs_dchar3 AS char(3); +CREATE DOMAIN queryfuncs_dchar3_chk AS char(3) CHECK (true); +CREATE DOMAIN queryfuncs_djsonb AS jsonb; +CREATE DOMAIN queryfuncs_djsonb_chk AS jsonb CHECK (true); +CREATE DOMAIN queryfuncs_djson AS json; +CREATE DOMAIN queryfuncs_djson_chk AS json CHECK (true); +SELECT JSON_VALUE(jsonb 'true', '$' RETURNING text) AS base, + JSON_VALUE(jsonb 'true', '$' RETURNING queryfuncs_dtext) AS dom, + JSON_VALUE(jsonb 'true', '$' RETURNING queryfuncs_dtext_chk) AS dom_chk; +SELECT JSON_VALUE(jsonb 'true', '$' RETURNING char(3)) AS base, + JSON_VALUE(jsonb 'true', '$' RETURNING queryfuncs_dchar3) AS dom, + JSON_VALUE(jsonb 'true', '$' RETURNING queryfuncs_dchar3_chk) AS dom_chk; +SELECT JSON_VALUE(x, '$' RETURNING jsonb) AS base, + JSON_VALUE(x, '$' RETURNING queryfuncs_djsonb) AS dom, + JSON_VALUE(x, '$' RETURNING queryfuncs_djsonb_chk) AS dom_chk + FROM (VALUES (jsonb 'true'), ('"1"'), ('null'), ('1.5')) v(x); +SELECT JSON_VALUE(x, '$' RETURNING json) AS base, + JSON_VALUE(x, '$' RETURNING queryfuncs_djson) AS dom, + JSON_VALUE(x, '$' RETURNING queryfuncs_djson_chk) AS dom_chk + FROM (VALUES (jsonb 'true'), ('"1"'), ('null'), ('1.5')) v(x); +-- Likewise for the ON EMPTY and ON ERROR expressions: a jsonb string given +-- as the DEFAULT must keep its quotes when coerced to json, jsonb, or a +-- domain over one of them (bug #19971). +SELECT JSON_VALUE(jsonb '{}', '$.a' RETURNING json DEFAULT '"123"'::jsonb ON EMPTY) AS on_empty, + JSON_VALUE(jsonb '{}', 'strict $.a' RETURNING json DEFAULT '"123"'::jsonb ON ERROR) AS on_error, + JSON_VALUE(jsonb '{}', '$.a' RETURNING json DEFAULT '"abc"'::jsonb ON EMPTY) AS not_a_number; +SELECT JSON_VALUE(jsonb '{}', '$.a' RETURNING queryfuncs_djson DEFAULT '"123"'::jsonb ON EMPTY) AS djson, + JSON_VALUE(jsonb '{}', '$.a' RETURNING queryfuncs_djson_chk DEFAULT '"123"'::jsonb ON EMPTY) AS djson_chk, + JSON_VALUE(jsonb '{}', '$.a' RETURNING queryfuncs_djsonb DEFAULT '"123"'::jsonb ON EMPTY) AS djsonb, + JSON_VALUE(jsonb '{}', '$.a' RETURNING queryfuncs_djsonb_chk DEFAULT '"123"'::jsonb ON EMPTY) AS djsonb_chk; +-- but not when coerced to other types +SELECT JSON_VALUE(jsonb '{}', '$.a' RETURNING text DEFAULT '"abc"'::jsonb ON EMPTY) AS text, + JSON_VALUE(jsonb '{}', '$.a' RETURNING int DEFAULT '"123"'::jsonb ON EMPTY) AS int; +-- a JsonExpr stored before the domain got a constraint behaves the same as +-- one created after +CREATE VIEW queryfuncs_dtext_view AS + SELECT JSON_VALUE(x, '$' RETURNING queryfuncs_dtext) AS v + FROM (VALUES (jsonb 'true'), ('"a"'), ('null')) v(x); +SELECT * FROM queryfuncs_dtext_view; +ALTER DOMAIN queryfuncs_dtext ADD CHECK (VALUE <> 't'); +SELECT * FROM queryfuncs_dtext_view; +SELECT JSON_VALUE(jsonb 'true', '$' RETURNING queryfuncs_dtext); +SELECT JSON_VALUE(jsonb 'true', '$' RETURNING queryfuncs_dtext ERROR ON ERROR); +-- a NULL result must still be checked against the domain's constraints +ALTER DOMAIN queryfuncs_dtext ADD CHECK (VALUE IS NOT NULL); +SELECT * FROM queryfuncs_dtext_view; +SELECT JSON_VALUE(jsonb 'null', '$' RETURNING queryfuncs_dtext ERROR ON ERROR); +SELECT JSON_VALUE(NULL::jsonb, '$' RETURNING queryfuncs_dtext ERROR ON ERROR); +SELECT JSON_VALUE(NULL::jsonb, '$' RETURNING queryfuncs_dtext DEFAULT 'dflt' ON ERROR); +DROP VIEW queryfuncs_dtext_view; +DROP DOMAIN queryfuncs_dtext, queryfuncs_dtext_chk, queryfuncs_dchar3, + queryfuncs_dchar3_chk, queryfuncs_djsonb, queryfuncs_djsonb_chk, + queryfuncs_djson, queryfuncs_djson_chk; -- 2.47.3