From 46aa631c90aaf8b3062212a2ea7cd879b6d4f9cf Mon Sep 17 00:00:00 2001 From: Srinath Reddy Sadipiralla Date: Thu, 10 Sep 2026 23:19:28 +0530 Subject: [PATCH v5 2/2] SQL/JSON: support "= PATH " source in JSON_TRANSFORM INSERT and REPLACE previously accepted only a value expression as their source. Per SQL Standard, the source may instead be "PATH ", in which case the value to insert or replace is produced at run time by evaluating that jsonpath against the input document, the same way JSON_QUERY without a wrapper does. This also activates the ON EMPTY and ON ERROR behavior clauses, which earlier revisions parsed but rejected because they are meaningful only for a PATH-valued source. Following the standard's General Rules: - a source path that yields no items triggers ON EMPTY, defaulting to NULL ON EMPTY; - a source path that yields more than one item, or whose evaluation raises a structural error, triggers ON ERROR, defaulting to ERROR ON ERROR. This path uses soft-error handling so that the IGNORE and NULL behaviors return a value instead of throwing. The target path and the PATH source are both coerced to jsonpath during parse analysis. The source value is derived during execution in ExecEvalJsonTransform. PASSING variables now have a use: they are supplied to the source path evaluation, so a jsonpath variable referenced in a PATH source resolves to the passed value. The target path may only contain member and wildcard accessors and so cannot reference a variable. Add regression tests in sqljson_transform.sql, the first coverage for JSON_TRANSFORM, exercising the four actions, the wildcard accessor, lax and strict target paths, the PATH source with and without PASSING variables, the ON EMPTY / ON ERROR / ON NULL routing, target-path validation, deparsing, and use in a functional index. --- src/backend/executor/execExpr.c | 37 +- src/backend/executor/execExprInterp.c | 87 +- src/backend/nodes/nodeFuncs.c | 3 + src/backend/optimizer/util/clauses.c | 9 + src/backend/parser/gram.y | 38 + src/backend/parser/parse_expr.c | 72 +- src/backend/utils/adt/ruleutils.c | 29 +- src/include/nodes/execnodes.h | 8 +- src/include/nodes/primnodes.h | 18 +- .../regress/expected/sqljson_transform.out | 741 ++++++++++++++++++ src/test/regress/parallel_schedule | 2 +- src/test/regress/sql/sqljson_transform.sql | 271 +++++++ 12 files changed, 1280 insertions(+), 35 deletions(-) create mode 100644 src/test/regress/expected/sqljson_transform.out create mode 100644 src/test/regress/sql/sqljson_transform.sql diff --git a/src/backend/executor/execExpr.c b/src/backend/executor/execExpr.c index 91195f3e610..0e96aea5bb2 100644 --- a/src/backend/executor/execExpr.c +++ b/src/backend/executor/execExpr.c @@ -5079,10 +5079,11 @@ ExecInitJsonExpr(JsonExpr *jsexpr, ExprState *state, * steps[K] EEOP_JUMP_IF_NULL (if doc is NULL, jump to M) * steps[..] evaluate action->pathspec -> jtstate->pathspec * steps[L] EEOP_JUMP_IF_NULL (if path is NULL, jump to M) + * steps[..] evaluate action->source_pathspec (PATH form only) + * steps[S] EEOP_JUMP_IF_NULL (if NULL, jump to M) * steps[..] evaluate action->value_expr (if any) -> jtstate->action_value * steps[..] evaluate PASSING args -> jtstate->args - * (nothing references them yet, since the target path cannot - * use variables; evaluated for parity with JSON_QUERY) + * (used only by the PATH form) * steps[P] EEOP_JSON_TRANSFORM (handler: do the mutation) * steps[P+1] EEOP_JUMP (success: jump past M) * steps[M] EEOP_CONST(NULL) (return-null landing pad) @@ -5134,9 +5135,26 @@ ExecInitJsonTransformExpr(JsonExpr *jsexpr, ExprState *state, ExprEvalPushStep(state, scratch); /* - * Evaluate the action's value_expr, if any. REMOVE has no value. + * Evaluate the action's source. For the "= PATH " form we + * compile the source jsonpath; ExecEvalJsonTransform runs it against the + * input document to derive the value. Otherwise we compile the value + * expression (RENAME's new key name, or INSERT/REPLACE's value). REMOVE + * has neither. */ - if (action->value_expr != NULL) + if (action->value_is_path) + { + ExecInitExprRec((Expr *) action->source_pathspec, state, + &jtstate->source_pathspec.value, + &jtstate->source_pathspec.isnull); + + /* JUMP to return-NULL landing pad if the source path is NULL */ + jumps_return_null = lappend_int(jumps_return_null, state->steps_len); + scratch->opcode = EEOP_JUMP_IF_NULL; + scratch->resnull = &jtstate->source_pathspec.isnull; + scratch->d.jump.jumpdone = -1; /* patched below */ + ExprEvalPushStep(state, scratch); + } + else if (action->value_expr != NULL) { ExecInitExprRec((Expr *) action->value_expr, state, &jtstate->action_value.value, @@ -5144,11 +5162,12 @@ ExecInitJsonTransformExpr(JsonExpr *jsexpr, ExprState *state, } /* - * Steps to compute PASSING args. These don't feed the mutation functions - * directly, but the jsonpath engine may reference them if in future we - * switch to native jsonpath-aware mutation. For now we evaluate but - * don't use them; kept for forward compatibility and for parity with how - * JSON_QUERY handles PASSING. + * Steps to compute PASSING args into jtstate->args. + * ExecEvalJsonTransform passes these to JsonPathQuery() when evaluating a + * "= PATH " source, so a variable referenced there resolves to + * the supplied value. The target path cannot reference variables (it may + * only contain member and wildcard accessors), so the args do not affect + * it. */ jtstate->args = NIL; forboth(argexprlc, jsexpr->passing_values, diff --git a/src/backend/executor/execExprInterp.c b/src/backend/executor/execExprInterp.c index 8184c88e96d..e5da4d0f04e 100644 --- a/src/backend/executor/execExprInterp.c +++ b/src/backend/executor/execExprInterp.c @@ -5419,7 +5419,11 @@ jtSetPath(JsonbIterator **it, JsonbInState *st, * jtstate->pathspec : the compiled target jsonpath Datum (non-null) * jtstate->action_value : the INSERT/REPLACE value or RENAME's new key * name (isnull=true for REMOVE, or if the user - * passed NULL) + * passed NULL; unused for a PATH source) + * jtstate->source_pathspec: the compiled source jsonpath Datum, for the + * "= PATH " form (non-null) + * jtstate->args : the PASSING variables, used only by the PATH + * source * * We convert the jsonpath to a list of accessor steps (member names and '.*' * wildcards), then make a single streaming pass over the document, rebuilding @@ -5429,8 +5433,8 @@ jtSetPath(JsonbIterator **it, JsonbInState *st, * * The per-action behaviors (action->on_existing / on_missing / on_null) are * resolved during parse analysis from the user's clauses plus the standard's - * implicit defaults; here we just honor them. ON EMPTY / ON ERROR are not - * yet supported (rejected at parse time). + * implicit defaults; here we just honor them. ON EMPTY and ON ERROR are + * consulted only for a PATH source. */ void ExecEvalJsonTransform(ExprState *state, ExprEvalStep *op, @@ -5468,7 +5472,82 @@ ExecEvalJsonTransform(ExprState *state, ExprEvalStep *op, /* Build the value the action needs, honoring ON NULL for INSERT/REPLACE. */ if (action->op == TRANSFORM_INSERT || action->op == TRANSFORM_REPLACE) { - if (jtstate->action_value.isnull) + if (action->value_is_path) + { + /* + * "= PATH " source: derive the value by running the + * source jsonpath against the input document with the PASSING + * variables. Exactly one item is required: zero items triggers + * ON EMPTY, while more than one item, like an evaluation error, + * triggers ON ERROR. ON NULL does not apply to a PATH source. + * + * We ask JsonPathQuery() to wrap the items in an array and count + * them ourselves, rather than letting it reject a multi-item + * result, so that the error names JSON_TRANSFORM instead of + * JSON_QUERY. + */ + JsonPath *jp_src = DatumGetJsonPathP(jtstate->source_pathspec.value); + bool throw_error = (action->on_error == JSON_TRANSFORM_BEHAVIOR_ERROR); + bool src_empty = false; + bool src_error = false; + Datum srcval; + + srcval = JsonPathQuery(jtstate->formatted_expr.value, jp_src, + JSW_UNCONDITIONAL, &src_empty, + throw_error ? NULL : &src_error, + jtstate->args, NULL); + + if (!src_error && !src_empty) + { + Jsonb *items = DatumGetJsonbP(srcval); + + if (JsonContainerSize(&items->root) > 1) + { + if (throw_error) + ereport(ERROR, + errcode(ERRCODE_MORE_THAN_ONE_SQL_JSON_ITEM), + errmsg("JSON_TRANSFORM source path must return a single SQL/JSON item")); + src_error = true; + } + else + newval = getIthJsonbValueFromContainer(&items->root, 0); + } + + if (src_error) + { + /* soft error (incl. >1 item); on_error is IGNORE or NULL */ + if (action->on_error == JSON_TRANSFORM_BEHAVIOR_IGNORE) + { + *op->resvalue = JsonbPGetDatum(in); + *op->resnull = false; + return; + } + /* NULL ON ERROR */ + newvalbuf.type = jbvNull; + newval = &newvalbuf; + } + else if (src_empty) + { + switch (action->on_empty) + { + case JSON_TRANSFORM_BEHAVIOR_ERROR: + ereport(ERROR, + errcode(ERRCODE_NO_SQL_JSON_ITEM), + errmsg("no SQL/JSON item found for the JSON_TRANSFORM source path")); + break; + case JSON_TRANSFORM_BEHAVIOR_IGNORE: + *op->resvalue = JsonbPGetDatum(in); + *op->resnull = false; + return; + default: + /* NULL ON EMPTY */ + newvalbuf.type = jbvNull; + newval = &newvalbuf; + break; + } + } + } + else if (jtstate->action_value.isnull) { switch (action->on_null) { diff --git a/src/backend/nodes/nodeFuncs.c b/src/backend/nodes/nodeFuncs.c index 2df263b8bfa..ec4ca3c21eb 100644 --- a/src/backend/nodes/nodeFuncs.c +++ b/src/backend/nodes/nodeFuncs.c @@ -2400,6 +2400,8 @@ expression_tree_walker_impl(Node *node, return true; if (WALK(jexpr->action->value_expr)) return true; + if (WALK(jexpr->action->source_pathspec)) + return true; } } break; @@ -3462,6 +3464,7 @@ expression_tree_mutator_impl(Node *node, FLATCOPY(newact, jexpr->action, JsonTransformAction); MUTATE(newact->pathspec, jexpr->action->pathspec, Node *); MUTATE(newact->value_expr, jexpr->action->value_expr, Node *); + MUTATE(newact->source_pathspec, jexpr->action->source_pathspec, Node *); newnode->action = newact; } return (Node *) newnode; diff --git a/src/backend/optimizer/util/clauses.c b/src/backend/optimizer/util/clauses.c index edc98615b65..b16393e39af 100644 --- a/src/backend/optimizer/util/clauses.c +++ b/src/backend/optimizer/util/clauses.c @@ -477,6 +477,15 @@ contain_mutable_functions_walker(Node *node, void *context) jexpr->path_spec, jexpr)) return true; + /* + * A JSON_TRANSFORM INSERT/REPLACE "= PATH " source is + * evaluated at run time against the input document, so it must be + * checked too. + */ + if (jexpr->action && jexpr->action->source_pathspec && + json_path_is_mutable(jexpr->action->source_pathspec, jexpr)) + return true; + /* Fall through to check subnodes */ } diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y index 781e0d7b7be..3e3a5343c6f 100644 --- a/src/backend/parser/gram.y +++ b/src/backend/parser/gram.y @@ -907,6 +907,16 @@ static Node *makeRecursiveViewSelect(char *relname, List *aliases, Node *query); %nonassoc UNBOUNDED NESTED /* ideally would have same precedence as IDENT */ %nonassoc IDENT PARTITION RANGE ROWS GROUPS PRECEDING FOLLOWING CUBE ROLLUP SET KEYS OBJECT_P SCALAR VALUE_P WITH WITHOUT PATH +/* + * The string-literal token SCONST is given a precedence just above PATH so + * that, in the JSON_TRANSFORM INSERT/REPLACE source "= PATH Sconst", the + * parser shifts the string as the jsonpath source rather than reducing PATH + * as an unreserved keyword introducing a "path 'literal'" typed constant. + * This only affects that one construct: without it the sole shift/reduce + * conflicts involving SCONST are those two, so the assignment cannot mask any + * other ambiguity. + */ +%nonassoc SCONST /* * IGNORE is given a precedence so the shift/reduce conflict between window * null-treatment (IGNORE NULLS) and a JSON_TRANSFORM behavior clause @@ -17549,6 +17559,20 @@ json_transform_action: $$ = (Node *) n; } | + /* INSERT path_expr = PATH jsonpath_source */ + INSERT a_expr '=' PATH Sconst json_transform_behavior_list_opt + { + JsonTransformAction *n = makeNode(JsonTransformAction); + n->op = TRANSFORM_INSERT; + n->pathspec = $2; + n->value_is_path = true; + n->source_pathspec = makeStringConst($5, @5); + n->behaviors = $6; + n->location = @1; + + $$ = (Node *) n; + } + | RENAME a_expr '=' Sconst json_transform_behavior_list_opt { JsonTransformAction *n = makeNode(JsonTransformAction); @@ -17573,6 +17597,20 @@ json_transform_action: $$ = (Node *) n; } | + /* REPLACE path_expr = PATH jsonpath_source */ + REPLACE a_expr '=' PATH Sconst json_transform_behavior_list_opt + { + JsonTransformAction *n = makeNode(JsonTransformAction); + n->op = TRANSFORM_REPLACE; + n->pathspec = $2; + n->value_is_path = true; + n->source_pathspec = makeStringConst($5, @5); + n->behaviors = $6; + n->location = @1; + + $$ = (Node *) n; + } + | REMOVE a_expr json_transform_behavior_list_opt { JsonTransformAction *n = makeNode(JsonTransformAction); diff --git a/src/backend/parser/parse_expr.c b/src/backend/parser/parse_expr.c index 59478ae788e..452176f14e3 100644 --- a/src/backend/parser/parse_expr.c +++ b/src/backend/parser/parse_expr.c @@ -4398,16 +4398,24 @@ resolveJsonTransformBehaviors(ParseState *pstate, { ListCell *lc; - /* Standard implicit defaults. */ + /* + * Standard implicit defaults. ON EMPTY / ON ERROR apply only to + * INSERT/REPLACE and are consulted only for a PATH-valued source; their + * defaults are NULL ON EMPTY and ERROR ON ERROR. + */ switch (action->op) { case TRANSFORM_INSERT: action->on_existing = JSON_TRANSFORM_BEHAVIOR_ERROR; action->on_null = JSON_TRANSFORM_BEHAVIOR_NULL; + action->on_empty = JSON_TRANSFORM_BEHAVIOR_NULL; + action->on_error = JSON_TRANSFORM_BEHAVIOR_ERROR; break; case TRANSFORM_REPLACE: action->on_missing = JSON_TRANSFORM_BEHAVIOR_IGNORE; action->on_null = JSON_TRANSFORM_BEHAVIOR_NULL; + action->on_empty = JSON_TRANSFORM_BEHAVIOR_NULL; + action->on_error = JSON_TRANSFORM_BEHAVIOR_ERROR; break; case TRANSFORM_REMOVE: case TRANSFORM_RENAME: @@ -4471,10 +4479,27 @@ resolveJsonTransformBehaviors(ParseState *pstate, case JSON_TRANSFORM_TARGET_EMPTY: case JSON_TRANSFORM_TARGET_ERROR: - ereport(ERROR, - errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("ON EMPTY and ON ERROR clauses are not yet supported in JSON_TRANSFORM"), - parser_errposition(pstate, clause->location)); + if (action->op != TRANSFORM_INSERT && + action->op != TRANSFORM_REPLACE) + ereport(ERROR, + errcode(ERRCODE_SYNTAX_ERROR), + errmsg("%s is only valid for JSON_TRANSFORM INSERT and REPLACE", + clause->target == JSON_TRANSFORM_TARGET_EMPTY ? + "ON EMPTY" : "ON ERROR"), + parser_errposition(pstate, clause->location)); + if (behavior != JSON_TRANSFORM_BEHAVIOR_ERROR && + behavior != JSON_TRANSFORM_BEHAVIOR_IGNORE && + behavior != JSON_TRANSFORM_BEHAVIOR_NULL) + ereport(ERROR, + errcode(ERRCODE_SYNTAX_ERROR), + errmsg("%s behavior must be ERROR, IGNORE, or NULL", + clause->target == JSON_TRANSFORM_TARGET_EMPTY ? + "ON EMPTY" : "ON ERROR"), + parser_errposition(pstate, clause->location)); + if (clause->target == JSON_TRANSFORM_TARGET_EMPTY) + action->on_empty = behavior; + else + action->on_error = behavior; break; } } @@ -4722,11 +4747,38 @@ transformJsonFuncExpr(ParseState *pstate, JsonFuncExpr *func) { case TRANSFORM_INSERT: case TRANSFORM_REPLACE: - analyzed_jst_action->value_expr = transformJsonValueExpr(pstate, func_name, - (JsonValueExpr *) jst_action->value_expr, - default_format, - JSONBOID, - false); + if (jst_action->value_is_path) + { + /* + * "= PATH " source: the value to insert/replace + * is produced at run time by evaluating this jsonpath + * against the input document. Coerce it to jsonpath just + * like the target path. + */ + Node *src = transformExprRecurse(pstate, jst_action->source_pathspec); + Oid srctype = exprType(src); + int srcloc = exprLocation(src); + Node *coerced_src = coerce_to_target_type(pstate, src, srctype, + JSONPATHOID, -1, + COERCION_EXPLICIT, + COERCE_IMPLICIT_CAST, + srcloc); + + if (coerced_src == NULL) + ereport(ERROR, + (errcode(ERRCODE_DATATYPE_MISMATCH), + errmsg("JSON path expression must be of type %s, not of type %s", + "jsonpath", format_type_be(srctype)), + parser_errposition(pstate, srcloc))); + analyzed_jst_action->value_is_path = true; + analyzed_jst_action->source_pathspec = coerced_src; + } + else + analyzed_jst_action->value_expr = transformJsonValueExpr(pstate, func_name, + (JsonValueExpr *) jst_action->value_expr, + default_format, + JSONBOID, + false); break; case TRANSFORM_RENAME: diff --git a/src/backend/utils/adt/ruleutils.c b/src/backend/utils/adt/ruleutils.c index f4fa9ae78a5..4c775a84080 100644 --- a/src/backend/utils/adt/ruleutils.c +++ b/src/backend/utils/adt/ruleutils.c @@ -10697,17 +10697,24 @@ get_rule_expr(Node *node, deparse_context *context, } else if (jexpr->action->op != TRANSFORM_REMOVE) { - /* - * Parenthesize a non-constant value: a function call - * followed by "IGNORE ON ..." would otherwise be read - * back as the start of IGNORE NULLS. - */ appendStringInfoString(buf, " = "); - if (IsA(jexpr->action->value_expr, Const)) + if (jexpr->action->value_is_path) + { + appendStringInfoString(buf, "PATH "); + get_json_path_spec(jexpr->action->source_pathspec, + context, showimplicit); + } + else if (IsA(jexpr->action->value_expr, Const)) get_rule_expr(jexpr->action->value_expr, context, showimplicit); else { + /* + * Parenthesize a non-constant value: a function + * call followed by "IGNORE ON ..." would + * otherwise be read back as the start of IGNORE + * NULLS. + */ appendStringInfoChar(buf, '('); get_rule_expr(jexpr->action->value_expr, context, showimplicit); @@ -10724,6 +10731,16 @@ get_rule_expr(Node *node, deparse_context *context, get_json_transform_behavior(buf, jexpr->action->on_null, JSON_TRANSFORM_BEHAVIOR_NULL, "NULL"); + /* ON EMPTY / ON ERROR apply only to a PATH-valued source */ + if (jexpr->action->value_is_path) + { + get_json_transform_behavior(buf, jexpr->action->on_empty, + JSON_TRANSFORM_BEHAVIOR_NULL, + "EMPTY"); + get_json_transform_behavior(buf, jexpr->action->on_error, + JSON_TRANSFORM_BEHAVIOR_ERROR, + "ERROR"); + } } else get_json_path_spec(jexpr->path_spec, context, showimplicit); diff --git a/src/include/nodes/execnodes.h b/src/include/nodes/execnodes.h index 59bb8f2c8b0..dbaf6349009 100644 --- a/src/include/nodes/execnodes.h +++ b/src/include/nodes/execnodes.h @@ -1080,11 +1080,13 @@ typedef struct JsonTransformExprState /* Runtime slots: filled by prior steps */ NullableDatum formatted_expr; /* input jsonb document */ - NullableDatum pathspec; /* compiled jsonpath Datum */ + NullableDatum pathspec; /* compiled target jsonpath Datum */ NullableDatum action_value; /* value for the transform op (NULL for - * REMOVE) */ + * REMOVE, or when the source is a PATH) */ + NullableDatum source_pathspec; /* compiled source jsonpath Datum, for the + * INSERT/REPLACE "= PATH " form */ - /* PASSING args (only used if jsonpath needs them) */ + /* PASSING args, used only by a PATH source */ List *args; /* List of JsonPathVariable */ } JsonTransformExprState; diff --git a/src/include/nodes/primnodes.h b/src/include/nodes/primnodes.h index 07cb2a2d023..a9941c20a9a 100644 --- a/src/include/nodes/primnodes.h +++ b/src/include/nodes/primnodes.h @@ -1747,14 +1747,28 @@ typedef struct JsonTransformAction { NodeTag type; JsonTransformOp op; - Node *pathspec; /* The JSON Path: '$.a' */ - Node *value_expr; + Node *pathspec; /* The target JSON Path: '$.a' */ + + /* + * The source of an INSERT/REPLACE value. Per SQL/JSON, the source is + * either a value expression (value_is_path = false; value_expr holds it) + * or "PATH " (value_is_path = true; source_pathspec holds the + * jsonpath, evaluated against the input document at run time). RENAME + * carries its new key name in value_expr; REMOVE has neither. + */ + bool value_is_path; /* is the source a "PATH "? */ + Node *value_expr; /* value source, or RENAME target name */ + Node *source_pathspec; /* jsonpath source (PATH form), else NULL */ + /* raw ON-clauses from the grammar (transient; resolved in analysis) */ List *behaviors; /* resolved behaviors (filled by parse analysis from defaults + clauses) */ JsonTransformBehavior on_existing; JsonTransformBehavior on_missing; JsonTransformBehavior on_null; + /* ON EMPTY / ON ERROR, consulted only for a PATH-valued source */ + JsonTransformBehavior on_empty; + JsonTransformBehavior on_error; ParseLoc location; /* token location, or -1 if unknown */ } JsonTransformAction; diff --git a/src/test/regress/expected/sqljson_transform.out b/src/test/regress/expected/sqljson_transform.out new file mode 100644 index 00000000000..04de5281f80 --- /dev/null +++ b/src/test/regress/expected/sqljson_transform.out @@ -0,0 +1,741 @@ +-- JSON_TRANSFORM +-- Basic actions on a jsonb document +SELECT JSON_TRANSFORM('{"a": 1, "b": 2}'::jsonb, REMOVE '$.a'); + json_transform +---------------- + {"b": 2} +(1 row) + +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, INSERT '$.b' = '2'); + json_transform +------------------ + {"a": 1, "b": 2} +(1 row) + +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.a' = '9'); + json_transform +---------------- + {"a": 9} +(1 row) + +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, RENAME '$.a' = 'z'); + json_transform +---------------- + {"z": 1} +(1 row) + +-- INSERT of an existing key raises an error by default (ERROR ON EXISTING); +-- IGNORE ON EXISTING keeps the existing member unchanged +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, INSERT '$.a' = '2'); +ERROR: target in JSON_TRANSFORM already exists +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, INSERT '$.a' = '2' IGNORE ON EXISTING); + json_transform +---------------- + {"a": 1} +(1 row) + +-- INSERT does not create missing parent objects; nothing is inserted +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, INSERT '$.x.y' = '2'); + json_transform +---------------- + {"a": 1} +(1 row) + +SELECT JSON_TRANSFORM('{"a": {}}'::jsonb, INSERT '$.a.y' = '2'); + json_transform +----------------- + {"a": {"y": 2}} +(1 row) + +-- REPLACE/RENAME/REMOVE of a missing key: default IGNORE ON MISSING +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.b' = '2'); + json_transform +---------------- + {"a": 1} +(1 row) + +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.b' = '2' ERROR ON MISSING); +ERROR: target in JSON_TRANSFORM does not exist +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REMOVE '$.b'); + json_transform +---------------- + {"a": 1} +(1 row) + +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REMOVE '$.b' ERROR ON MISSING); +ERROR: target in JSON_TRANSFORM does not exist +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, RENAME '$.b' = 'c'); + json_transform +---------------- + {"a": 1} +(1 row) + +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, RENAME '$.b' = 'c' ERROR ON MISSING); +ERROR: target in JSON_TRANSFORM does not exist +-- RENAME onto a key that already exists in the same object is an error; +-- renaming a key to its own name is not, and keys of other objects do not +-- count +SELECT JSON_TRANSFORM('{"a": 1, "b": 2}'::jsonb, RENAME '$.a' = 'b'); +ERROR: cannot rename JSON_TRANSFORM target to "b": key already exists +SELECT JSON_TRANSFORM('{"a": 1, "b": 2}'::jsonb, RENAME '$.a' = 'a'); + json_transform +------------------ + {"a": 1, "b": 2} +(1 row) + +SELECT JSON_TRANSFORM('{"o": {"a": 1}, "b": 2}'::jsonb, RENAME '$.o.a' = 'b'); + json_transform +------------------------- + {"b": 2, "o": {"b": 1}} +(1 row) + +-- Wildcard member accessor '.*' applies the action to every member +SELECT JSON_TRANSFORM('{"a": 1, "b": 2}'::jsonb, REPLACE '$.*' = '0'); + json_transform +------------------ + {"a": 0, "b": 0} +(1 row) + +SELECT JSON_TRANSFORM('{"a": 1, "b": 2}'::jsonb, REMOVE '$.*'); + json_transform +---------------- + {} +(1 row) + +-- ... also in the middle of a path, where non-objects are skipped (lax) +SELECT JSON_TRANSFORM('{"p": {"x": 1, "y": 2}, "q": {"x": 3}, "r": 5}'::jsonb, + REPLACE '$.*.x' = '0'); + json_transform +------------------------------------------------ + {"p": {"x": 0, "y": 2}, "q": {"x": 0}, "r": 5} +(1 row) + +-- ... and a wildcard that matches nothing is a missing target +SELECT JSON_TRANSFORM('{}'::jsonb, REPLACE '$.*' = '0'); + json_transform +---------------- + {} +(1 row) + +SELECT JSON_TRANSFORM('{}'::jsonb, REPLACE '$.*' = '0' ERROR ON MISSING); +ERROR: target in JSON_TRANSFORM does not exist +SELECT JSON_TRANSFORM('{}'::jsonb, REMOVE '$.*' ERROR ON MISSING); +ERROR: target in JSON_TRANSFORM does not exist +-- Nested member accessors +SELECT JSON_TRANSFORM('{"a": {"b": {"c": 1}}}'::jsonb, REPLACE '$.a.b.c' = '2'); + json_transform +------------------------ + {"a": {"b": {"c": 2}}} +(1 row) + +-- lax mode (the default) unwraps arrays; strict mode errors on them +SELECT JSON_TRANSFORM('{"arr": [{"a": 1}, {"a": 2}]}'::jsonb, REPLACE 'lax $.arr.a' = '9'); + json_transform +------------------------------- + {"arr": [{"a": 9}, {"a": 9}]} +(1 row) + +SELECT JSON_TRANSFORM('{"arr": [{"a": 1}]}'::jsonb, REPLACE '$.arr.a' = '9'); + json_transform +--------------------- + {"arr": [{"a": 9}]} +(1 row) + +SELECT JSON_TRANSFORM('{"arr": [{"a": 1}]}'::jsonb, REPLACE 'strict $.arr.a' = '9'); +ERROR: jsonpath member accessor can only be applied to an object +-- lax unwraps one array level only, and skips scalars, like jsonb_path_query() +SELECT JSON_TRANSFORM('{"arr": [[{"a": 1}], 7, {"a": 2}]}'::jsonb, REPLACE '$.arr.a' = '9'); + json_transform +------------------------------------ + {"arr": [[{"a": 1}], 7, {"a": 9}]} +(1 row) + +SELECT jsonb_path_query('{"arr": [[{"a": 1}], 7, {"a": 2}]}', 'lax $.arr.a'); + jsonb_path_query +------------------ + 2 +(1 row) + +-- strict: a member accessor applied to a scalar or an array is an error +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE 'strict $.a.b' = '9'); +ERROR: jsonpath member accessor can only be applied to an object +SELECT JSON_TRANSFORM('{"a": [1]}'::jsonb, REPLACE 'strict $.a.*' = '9'); +ERROR: jsonpath wildcard member accessor can only be applied to an object +-- top-level array and top-level scalar documents +SELECT JSON_TRANSFORM('[{"a": 1}, {"b": 2}]'::jsonb, REMOVE '$.a'); + json_transform +---------------- + [{}, {"b": 2}] +(1 row) + +SELECT JSON_TRANSFORM('5'::jsonb, REMOVE '$.a'); + json_transform +---------------- + 5 +(1 row) + +SELECT JSON_TRANSFORM('5'::jsonb, REMOVE '$.a' ERROR ON MISSING); +ERROR: target in JSON_TRANSFORM does not exist +-- "= PATH " source: the value is pulled from the input document +SELECT JSON_TRANSFORM('{"a": 1, "b": 42}'::jsonb, REPLACE '$.a' = PATH '$.b'); + json_transform +-------------------- + {"a": 42, "b": 42} +(1 row) + +SELECT JSON_TRANSFORM('{"a": 1, "b": {"c": [1, 2, 3]}}'::jsonb, INSERT '$.d' = PATH '$.b.c'); + json_transform +------------------------------------------------- + {"a": 1, "b": {"c": [1, 2, 3]}, "d": [1, 2, 3]} +(1 row) + +-- PASSING variables are visible to a PATH source +SELECT JSON_TRANSFORM('{"a": 1, "b": 42}'::jsonb, REPLACE '$.a' = PATH '$x' PASSING 99 AS x); + json_transform +-------------------- + {"a": 99, "b": 42} +(1 row) + +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.a' = PATH '$x' PASSING '"hi"'::jsonb AS x); + json_transform +---------------- + {"a": "hi"} +(1 row) + +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.a' = PATH '$x' PASSING 'hello' AS x); + json_transform +---------------- + {"a": "hello"} +(1 row) + +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, INSERT '$.b' = PATH '$x' PASSING 7 AS x); + json_transform +------------------ + {"a": 1, "b": 7} +(1 row) + +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.a' = PATH '$x + 1' PASSING 41 AS x); + json_transform +---------------- + {"a": 42} +(1 row) + +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.a' = PATH '$y' PASSING 1 AS x, 2 AS y); + json_transform +---------------- + {"a": 2} +(1 row) + +-- PASSING is accepted, but has no effect, without a PATH source +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.a' = '5' PASSING 99 AS x); + json_transform +---------------- + {"a": 5} +(1 row) + +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REMOVE '$.a' PASSING 99 AS x); + json_transform +---------------- + {} +(1 row) + +-- Unbound variable in a PATH source is an error +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.a' = PATH '$y'); +ERROR: could not find jsonpath variable "y" +-- PATH source cardinality routing (SQL:2023 6.44 GR): 0 items -> ON EMPTY, +-- >1 items or a structural error -> ON ERROR. +-- Default is NULL ON EMPTY, ERROR ON ERROR. +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.a' = PATH '$.nope'); + json_transform +---------------- + {"a": null} +(1 row) + +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.a' = PATH '$.nope' ERROR ON EMPTY); +ERROR: no SQL/JSON item found for the JSON_TRANSFORM source path +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.a' = PATH '$.nope' IGNORE ON EMPTY); + json_transform +---------------- + {"a": 1} +(1 row) + +SELECT JSON_TRANSFORM('{"a": 1, "arr": [10, 20]}'::jsonb, REPLACE '$.a' = PATH '$.arr[*]'); +ERROR: JSON_TRANSFORM source path must return a single SQL/JSON item +SELECT JSON_TRANSFORM('{"a": 1, "arr": [10, 20]}'::jsonb, REPLACE '$.a' = PATH '$.arr[*]' NULL ON ERROR); + json_transform +------------------------------ + {"a": null, "arr": [10, 20]} +(1 row) + +SELECT JSON_TRANSFORM('{"a": 1, "arr": [10, 20]}'::jsonb, REPLACE '$.a' = PATH '$.arr[*]' IGNORE ON ERROR); + json_transform +--------------------------- + {"a": 1, "arr": [10, 20]} +(1 row) + +-- a single item that is itself an array is fine +SELECT JSON_TRANSFORM('{"a": 1, "arr": [10, 20]}'::jsonb, REPLACE '$.a' = PATH '$.arr'); + json_transform +---------------------------------- + {"a": [10, 20], "arr": [10, 20]} +(1 row) + +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.a' = PATH 'strict $.nope'); +ERROR: JSON object does not contain key "nope" +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.a' = PATH 'strict $.nope' NULL ON ERROR); + json_transform +---------------- + {"a": null} +(1 row) + +-- ON EMPTY vs ON ERROR are independent knobs (cross test) +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.a' = PATH '$.nope' IGNORE ON EMPTY ERROR ON ERROR); + json_transform +---------------- + {"a": 1} +(1 row) + +SELECT JSON_TRANSFORM('{"a": 1, "arr": [10, 20]}'::jsonb, REPLACE '$.a' = PATH '$.arr[*]' ERROR ON EMPTY IGNORE ON ERROR); + json_transform +--------------------------- + {"a": 1, "arr": [10, 20]} +(1 row) + +-- ON NULL for a literal (non-PATH) source +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.a' = NULL); + json_transform +---------------- + {"a": null} +(1 row) + +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.a' = NULL NULL ON NULL); + json_transform +---------------- + {"a": null} +(1 row) + +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.a' = NULL ERROR ON NULL); +ERROR: null in replacement value of JSON_TRANSFORM not allowed +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.a' = NULL IGNORE ON NULL); + json_transform +---------------- + {"a": 1} +(1 row) + +SELECT JSON_TRANSFORM('{"a": 1, "b": 2}'::jsonb, REPLACE '$.a' = NULL REMOVE ON NULL); + json_transform +---------------- + {"b": 2} +(1 row) + +-- Behavior clauses that do not apply to the action are rejected +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.a' = '2' IGNORE ON EXISTING); +ERROR: ON EXISTING is only valid for JSON_TRANSFORM INSERT +LINE 1: ..._TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.a' = '2' IGNORE ON ... + ^ +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, INSERT '$.b' = '2' IGNORE ON MISSING); +ERROR: ON MISSING is not valid for JSON_TRANSFORM INSERT +LINE 1: ...N_TRANSFORM('{"a": 1}'::jsonb, INSERT '$.b' = '2' IGNORE ON ... + ^ +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, INSERT '$.a' = '2' NULL ON EXISTING); +ERROR: ON EXISTING behavior must be ERROR or IGNORE +LINE 1: ...N_TRANSFORM('{"a": 1}'::jsonb, INSERT '$.a' = '2' NULL ON EX... + ^ +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, INSERT '$.b' = NULL REMOVE ON NULL); +ERROR: REMOVE ON NULL is not allowed for JSON_TRANSFORM INSERT +LINE 1: ..._TRANSFORM('{"a": 1}'::jsonb, INSERT '$.b' = NULL REMOVE ON ... + ^ +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.b' = '2' NULL ON MISSING); +ERROR: ON MISSING behavior must be ERROR or IGNORE +LINE 1: ..._TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.b' = '2' NULL ON MI... + ^ +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REMOVE '$.a' NULL ON NULL); +ERROR: ON NULL is only valid for JSON_TRANSFORM INSERT and REPLACE +LINE 1: ...CT JSON_TRANSFORM('{"a": 1}'::jsonb, REMOVE '$.a' NULL ON NU... + ^ +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REMOVE '$.a' ERROR ON EMPTY); +ERROR: ON EMPTY is only valid for JSON_TRANSFORM INSERT and REPLACE +LINE 1: ...CT JSON_TRANSFORM('{"a": 1}'::jsonb, REMOVE '$.a' ERROR ON E... + ^ +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.a' = PATH '$.b' REMOVE ON EMPTY); +ERROR: ON EMPTY behavior must be ERROR, IGNORE, or NULL +LINE 1: ...ORM('{"a": 1}'::jsonb, REPLACE '$.a' = PATH '$.b' REMOVE ON ... + ^ +-- ON EMPTY / ON ERROR are accepted with a non-PATH source, but only the +-- PATH source rules ever consult them +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.a' = '2' IGNORE ON ERROR); + json_transform +---------------- + {"a": 2} +(1 row) + +-- The standard's SQLSTATEs (SQL:2023 6.44) +\set VERBOSITY sqlstate +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, INSERT '$.a' = '2'); +ERROR: 22050 +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.a' = NULL ERROR ON NULL); +ERROR: 22051 +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REMOVE '$.b' ERROR ON MISSING); +ERROR: 22052 +SELECT JSON_TRANSFORM('{"a": 1, "b": 2}'::jsonb, RENAME '$.a' = 'b'); +ERROR: 22037 +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.a' = PATH '$.nope' ERROR ON EMPTY); +ERROR: 22035 +SELECT JSON_TRANSFORM('{"a": 1, "arr": [10, 20]}'::jsonb, REPLACE '$.a' = PATH '$.arr[*]'); +ERROR: 22034 +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.a' = PATH 'strict $.nope'); +ERROR: 2203A +\set VERBOSITY default +-- Target-path validation: must start with $, only member/wildcard accessors +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REMOVE 'lax @.a'); +ERROR: @ is not allowed in root expressions +LINE 1: SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REMOVE 'lax @.a'); + ^ +SELECT JSON_TRANSFORM('{"a": [1, 2]}'::jsonb, REMOVE '$.a[0]'); +ERROR: JSON_TRANSFORM target path may only contain member accessors (.key) and wildcard member accessors (.*) +LINE 1: ...ECT JSON_TRANSFORM('{"a": [1, 2]}'::jsonb, REMOVE '$.a[0]'); + ^ +DETAIL: Array subscripts, filters, methods, and recursive descent are not allowed. +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REMOVE '$.a ? (@ == 1)'); +ERROR: JSON_TRANSFORM target path may only contain member accessors (.key) and wildcard member accessors (.*) +LINE 1: SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REMOVE '$.a ? (@ ==... + ^ +DETAIL: Array subscripts, filters, methods, and recursive descent are not allowed. +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REMOVE '$.a.type()'); +ERROR: JSON_TRANSFORM target path may only contain member accessors (.key) and wildcard member accessors (.*) +LINE 1: SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REMOVE '$.a.type()'... + ^ +DETAIL: Array subscripts, filters, methods, and recursive descent are not allowed. +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REMOVE '$'); +ERROR: JSON_TRANSFORM target path must name at least one member +LINE 1: SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REMOVE '$'); + ^ +-- A variable cannot be referenced in the target path, not even as its start +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REMOVE '$.a ? (@ == $x)' PASSING 1 AS x); +ERROR: JSON_TRANSFORM target path may only contain member accessors (.key) and wildcard member accessors (.*) +LINE 1: SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REMOVE '$.a ? (@ ==... + ^ +DETAIL: Array subscripts, filters, methods, and recursive descent are not allowed. +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REMOVE '$x.a' PASSING '{"a": 1}'::jsonb AS x); +ERROR: JSON_TRANSFORM target path must start with the context variable $ +LINE 1: SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REMOVE '$x.a' PASSI... + ^ +-- The target path must be a jsonpath +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REMOVE 42); +ERROR: JSON path expression must be of type jsonpath, not of type integer +LINE 1: SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REMOVE 42); + ^ +-- Deep paths (more steps than the initial step array holds) +SELECT JSON_TRANSFORM('{"a":{"b":{"c":{"d":{"e":{"f":{"g":{"h":{"i":{"j":1}}}}}}}}}}'::jsonb, + REPLACE '$.a.b.c.d.e.f.g.h.i.j' = '2'); + json_transform +------------------------------------------------------------------------- + {"a": {"b": {"c": {"d": {"e": {"f": {"g": {"h": {"i": {"j": 2}}}}}}}}}} +(1 row) + +-- The last accessor of INSERT/RENAME may not be a wildcard +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, INSERT '$.*' = '1'); +ERROR: the last accessor of a JSON_TRANSFORM INSERT target path may not be a wildcard +LINE 1: SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, INSERT '$.*' = '1')... + ^ +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, RENAME '$.*' = 'z'); +ERROR: the last accessor of a JSON_TRANSFORM RENAME target path may not be a wildcard +LINE 1: SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, RENAME '$.*' = 'z')... + ^ +-- NULL input document returns NULL +SELECT JSON_TRANSFORM(NULL::jsonb, REMOVE '$.a'); + json_transform +---------------- + +(1 row) + +-- Unquoted (text) input is accepted and treated as JSON +SELECT JSON_TRANSFORM('{"a": 1}', REPLACE '$.a' = '2'); + json_transform +---------------- + {"a": 2} +(1 row) + +-- Non-constant arguments: column references and sub-selects as the value +-- (a sub-select used to crash), and a column as the target path. These are +-- not folded at plan time, so they also run the executor (and JIT) path. +CREATE TABLE jt_tab (id int, j jsonb, v jsonb, p jsonpath); +INSERT INTO jt_tab VALUES + (1, '{"a": 1, "b": 2}', '"x"', '$.a'), + (2, '{"a": {"c": 3}}', NULL, '$.a.c'), + (3, NULL, '1', '$.b'); +SELECT id, JSON_TRANSFORM(j, REPLACE '$.a' = v) FROM jt_tab ORDER BY id; + id | json_transform +----+-------------------- + 1 | {"a": "x", "b": 2} + 2 | {"a": null} + 3 | +(3 rows) + +SELECT id, JSON_TRANSFORM(j, REPLACE '$.a' = (SELECT v)) FROM jt_tab ORDER BY id; + id | json_transform +----+-------------------- + 1 | {"a": "x", "b": 2} + 2 | {"a": null} + 3 | +(3 rows) + +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.a' = (SELECT '[1, 2]'::jsonb)); + json_transform +---------------- + {"a": [1, 2]} +(1 row) + +SELECT id, JSON_TRANSFORM(j, REPLACE p = '0') FROM jt_tab ORDER BY id; + id | json_transform +----+------------------ + 1 | {"a": 0, "b": 2} + 2 | {"a": {"c": 0}} + 3 | +(3 rows) + +SELECT id, JSON_TRANSFORM(j, REPLACE '$.a' = PATH '$x' PASSING id AS x) FROM jt_tab ORDER BY id; + id | json_transform +----+------------------ + 1 | {"a": 1, "b": 2} + 2 | {"a": 2} + 3 | +(3 rows) + +SELECT id, JSON_TRANSFORM(j, INSERT '$.b' = v IGNORE ON EXISTING) FROM jt_tab ORDER BY id; + id | json_transform +----+---------------------------- + 1 | {"a": 1, "b": 2} + 2 | {"a": {"c": 3}, "b": null} + 3 | +(3 rows) + +-- A function call followed by IGNORE ON ... is read as the start of IGNORE +-- NULLS (one token of lookahead cannot tell them apart), so it must be +-- parenthesized +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, INSERT '$.b' = to_jsonb(1) IGNORE ON EXISTING); +ERROR: syntax error at or near "ON" +LINE 1: ...a": 1}'::jsonb, INSERT '$.b' = to_jsonb(1) IGNORE ON EXISTIN... + ^ +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, INSERT '$.b' = (to_jsonb(1)) IGNORE ON EXISTING); + json_transform +------------------ + {"a": 1, "b": 1} +(1 row) + +-- Deparse: EXPLAIN VERBOSE and stored views must round-trip. Clauses equal +-- to their default are not printed. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REMOVE '$.a'); + QUERY PLAN +------------------------------------------------------------- + Result + Output: JSON_TRANSFORM('{"a": 1}'::jsonb, REMOVE '$."a"') +(2 rows) + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT JSON_TRANSFORM(j, REPLACE '$.a' = v ERROR ON MISSING) FROM jt_tab; + QUERY PLAN +--------------------------------------------------------------------- + Seq Scan on public.jt_tab + Output: JSON_TRANSFORM(j, REPLACE '$."a"' = (v) ERROR ON MISSING) +(2 rows) + +-- jt_view is left in place so that pg_upgrade's dump/restore test exercises it +CREATE VIEW jt_view AS +SELECT id, + JSON_TRANSFORM(j, REPLACE '$.a' = PATH '$x' ERROR ON ERROR PASSING 5 AS x) AS r1, + JSON_TRANSFORM(j, REPLACE '$.a' = PATH '$.b' IGNORE ON EMPTY NULL ON ERROR) AS r2, + JSON_TRANSFORM(j, INSERT '$.n' = (to_jsonb(id)) IGNORE ON EXISTING) AS r3, + JSON_TRANSFORM(j, REMOVE p ERROR ON MISSING) AS r4, + JSON_TRANSFORM(j, RENAME '$.a' = 'z') AS r5, + JSON_TRANSFORM(j, REPLACE '$.a' = v REMOVE ON NULL) AS r6, + JSON_TRANSFORM(j, REPLACE '$.b' = '"k"') AS r7 +FROM jt_tab; +SELECT pg_get_viewdef('jt_view', true); + pg_get_viewdef +-------------------------------------------------------------------------------------------- + SELECT id, + + JSON_TRANSFORM(j, REPLACE '$."a"' = PATH '$"x"' PASSING 5 AS x) AS r1, + + JSON_TRANSFORM(j, REPLACE '$."a"' = PATH '$."b"' IGNORE ON EMPTY NULL ON ERROR) AS r2,+ + JSON_TRANSFORM(j, INSERT '$."n"' = (to_jsonb(id)) IGNORE ON EXISTING) AS r3, + + JSON_TRANSFORM(j, REMOVE p ERROR ON MISSING) AS r4, + + JSON_TRANSFORM(j, RENAME '$."a"' = 'z') AS r5, + + JSON_TRANSFORM(j, REPLACE '$."a"' = (v) REMOVE ON NULL) AS r6, + + JSON_TRANSFORM(j, REPLACE '$."b"' = ('"k"'::text)) AS r7 + + FROM jt_tab; +(1 row) + +-- the deparsed text must be accepted by the parser again +DO $$ +BEGIN + EXECUTE 'CREATE VIEW jt_view2 AS ' || pg_get_viewdef('jt_view'); +END +$$; +SELECT pg_get_viewdef('jt_view') = pg_get_viewdef('jt_view2') AS same; + same +------ + t +(1 row) + +DROP VIEW jt_view2; +SELECT * FROM jt_view ORDER BY id; + id | r1 | r2 | r3 | r4 | r5 | r6 | r7 +----+------------------+------------------+--------------------------+-----------+------------------+--------------------+-------------------- + 1 | {"a": 5, "b": 2} | {"a": 2, "b": 2} | {"a": 1, "b": 2, "n": 1} | {"b": 2} | {"b": 2, "z": 1} | {"a": "x", "b": 2} | {"a": 1, "b": "k"} + 2 | {"a": 5} | {"a": {"c": 3}} | {"a": {"c": 3}, "n": 2} | {"a": {}} | {"z": {"c": 3}} | {} | {"a": {"c": 3}} + 3 | | | | | | | +(3 rows) + +-- JSON_TRANSFORM is immutable, so it may be used in a functional index; +-- jt_idx is left in place for the dump/restore test as well +CREATE INDEX jt_idx ON jt_tab ((JSON_TRANSFORM(j, REMOVE '$.a'))); +CREATE INDEX jt_idx2 ON jt_tab ((JSON_TRANSFORM(j, REPLACE '$.a' = PATH '$.b'))); +INSERT INTO jt_tab VALUES (4, '{"a": 1, "b": 2}', NULL, '$.b'); +DROP INDEX jt_idx2; +-- ... but not if any part of it is not: the target path, the value, or a +-- mutable PATH source +CREATE INDEX ON jt_tab ((JSON_TRANSFORM(j, REMOVE (CASE WHEN random() > 2 THEN '$.x' ELSE '$.a' END)::jsonpath))); +ERROR: functions in index expression must be marked IMMUTABLE +LINE 1: CREATE INDEX ON jt_tab ((JSON_TRANSFORM(j, REMOVE (CASE WHEN... + ^ +CREATE INDEX ON jt_tab ((JSON_TRANSFORM(j, REPLACE '$.a' = to_jsonb(random())))); +ERROR: functions in index expression must be marked IMMUTABLE +LINE 1: CREATE INDEX ON jt_tab ((JSON_TRANSFORM(j, REPLACE '$.a' = t... + ^ +CREATE INDEX ON jt_tab ((JSON_TRANSFORM(j, REPLACE '$.a' = PATH '$.b.datetime("HH:MI TZH") < $.b.datetime("HH:MI")'))); +ERROR: functions in index expression must be marked IMMUTABLE +LINE 1: CREATE INDEX ON jt_tab ((JSON_TRANSFORM(j, REPLACE '$.a' = P... + ^ +-- jt_idx3, with a non-default clause, is also left in place +CREATE INDEX jt_idx3 ON jt_tab ((JSON_TRANSFORM(j, INSERT '$.n' = '1' IGNORE ON EXISTING))); +SELECT pg_get_indexdef('jt_idx3'::regclass); + pg_get_indexdef +------------------------------------------------------------------------------------------------------------------------ + CREATE INDEX jt_idx3 ON public.jt_tab USING btree (JSON_TRANSFORM(j, INSERT '$."n"' = ('1'::text) IGNORE ON EXISTING)) +(1 row) + +-- An invalid constant target path is rejected when an index, view, or +-- generated column is defined, even on an empty table where nothing gets +-- evaluated; otherwise every later INSERT would fail +CREATE TABLE jt_empty (j jsonb, p jsonpath); +CREATE INDEX ON jt_empty ((JSON_TRANSFORM(j, REMOVE '$x.a' PASSING 1 AS x))); +ERROR: JSON_TRANSFORM target path must start with the context variable $ +LINE 1: ...EATE INDEX ON jt_empty ((JSON_TRANSFORM(j, REMOVE '$x.a' PAS... + ^ +CREATE INDEX ON jt_empty ((JSON_TRANSFORM(j, REMOVE '$[0]'))); +ERROR: JSON_TRANSFORM target path may only contain member accessors (.key) and wildcard member accessors (.*) +LINE 1: ...EATE INDEX ON jt_empty ((JSON_TRANSFORM(j, REMOVE '$[0]'))); + ^ +DETAIL: Array subscripts, filters, methods, and recursive descent are not allowed. +CREATE INDEX ON jt_empty ((JSON_TRANSFORM(j, REMOVE '$.a ? (@ > 1)'))); +ERROR: JSON_TRANSFORM target path may only contain member accessors (.key) and wildcard member accessors (.*) +LINE 1: ...EATE INDEX ON jt_empty ((JSON_TRANSFORM(j, REMOVE '$.a ? (@ ... + ^ +DETAIL: Array subscripts, filters, methods, and recursive descent are not allowed. +CREATE INDEX ON jt_empty ((JSON_TRANSFORM(j, REMOVE '$.**'))); +ERROR: JSON_TRANSFORM target path may only contain member accessors (.key) and wildcard member accessors (.*) +LINE 1: ...EATE INDEX ON jt_empty ((JSON_TRANSFORM(j, REMOVE '$.**'))); + ^ +DETAIL: Array subscripts, filters, methods, and recursive descent are not allowed. +CREATE INDEX ON jt_empty ((JSON_TRANSFORM(j, REMOVE '$'))); +ERROR: JSON_TRANSFORM target path must name at least one member +LINE 1: CREATE INDEX ON jt_empty ((JSON_TRANSFORM(j, REMOVE '$'))); + ^ +CREATE INDEX ON jt_empty ((JSON_TRANSFORM(j, INSERT '$.*' = '1'))); +ERROR: the last accessor of a JSON_TRANSFORM INSERT target path may not be a wildcard +LINE 1: ...EATE INDEX ON jt_empty ((JSON_TRANSFORM(j, INSERT '$.*' = '1... + ^ +CREATE INDEX ON jt_empty ((JSON_TRANSFORM(j, RENAME '$.*' = 'z'))); +ERROR: the last accessor of a JSON_TRANSFORM RENAME target path may not be a wildcard +LINE 1: ...EATE INDEX ON jt_empty ((JSON_TRANSFORM(j, RENAME '$.*' = 'z... + ^ +CREATE VIEW jt_bad_view AS SELECT JSON_TRANSFORM(j, REMOVE '$[0]') FROM jt_empty; +ERROR: JSON_TRANSFORM target path may only contain member accessors (.key) and wildcard member accessors (.*) +LINE 1: ...EW jt_bad_view AS SELECT JSON_TRANSFORM(j, REMOVE '$[0]') FR... + ^ +DETAIL: Array subscripts, filters, methods, and recursive descent are not allowed. +ALTER TABLE jt_empty ADD COLUMN g jsonb + GENERATED ALWAYS AS (JSON_TRANSFORM(j, REMOVE '$[0]')) STORED; +ERROR: JSON_TRANSFORM target path may only contain member accessors (.key) and wildcard member accessors (.*) +DETAIL: Array subscripts, filters, methods, and recursive descent are not allowed. +-- ... also when the path only becomes a constant during planning +CREATE INDEX ON jt_empty ((JSON_TRANSFORM(j, REMOVE '$[0]'::text))); +ERROR: JSON_TRANSFORM target path may only contain member accessors (.key) and wildcard member accessors (.*) +DETAIL: Array subscripts, filters, methods, and recursive descent are not allowed. +ALTER TABLE jt_empty ADD COLUMN g jsonb + GENERATED ALWAYS AS (JSON_TRANSFORM(j, REMOVE '$[0]'::text)) STORED; +ERROR: JSON_TRANSFORM target path may only contain member accessors (.key) and wildcard member accessors (.*) +DETAIL: Array subscripts, filters, methods, and recursive descent are not allowed. +-- ... and when a NULL input means the executor would never look at it +SELECT JSON_TRANSFORM(NULL::jsonb, REMOVE '$[0]'); +ERROR: JSON_TRANSFORM target path may only contain member accessors (.key) and wildcard member accessors (.*) +LINE 1: SELECT JSON_TRANSFORM(NULL::jsonb, REMOVE '$[0]'); + ^ +DETAIL: Array subscripts, filters, methods, and recursive descent are not allowed. +-- a valid path folded during planning is fine +CREATE INDEX ON jt_empty ((JSON_TRANSFORM(j, REMOVE '$.a'::text))); +INSERT INTO jt_empty VALUES ('{"a": 1, "b": 2}'); +-- a non-constant target path makes the expression mutable, and can only be +-- checked at run time +CREATE INDEX ON jt_empty ((JSON_TRANSFORM(j, REMOVE p))); +ERROR: functions in index expression must be marked IMMUTABLE +LINE 1: CREATE INDEX ON jt_empty ((JSON_TRANSFORM(j, REMOVE p))); + ^ +SELECT JSON_TRANSFORM('{"a": 1}', REMOVE p) FROM (VALUES ('$[0]'::jsonpath)) v(p); +ERROR: JSON_TRANSFORM target path may only contain member accessors (.key) and wildcard member accessors (.*) +DETAIL: Array subscripts, filters, methods, and recursive descent are not allowed. +-- mutable through a PASSING argument: a volatile value, or a timestamptz +-- compared with a datetime of unknown type (time zone dependent, as for +-- JSON_QUERY); an immutable PASSING argument is fine +CREATE INDEX ON jt_empty ((JSON_TRANSFORM(j, INSERT '$.r' = PATH '$.a + $x' PASSING random() AS x))); +ERROR: functions in index expression must be marked IMMUTABLE +LINE 1: CREATE INDEX ON jt_empty ((JSON_TRANSFORM(j, INSERT '$.r' = ... + ^ +CREATE INDEX ON jt_empty ((JSON_TRANSFORM(j, INSERT '$.r' = PATH '$.d.datetime() < $x' + PASSING '2020-01-01 00:00'::timestamptz AS x))); +ERROR: functions in index expression must be marked IMMUTABLE +LINE 1: CREATE INDEX ON jt_empty ((JSON_TRANSFORM(j, INSERT '$.r' = ... + ^ +CREATE INDEX ON jt_empty ((JSON_TRANSFORM(j, INSERT '$.r' = PATH '$.a + $x' PASSING 1 AS x))); +-- a data-dependent error is still raised while building the index +CREATE INDEX ON jt_empty ((JSON_TRANSFORM(j, INSERT '$.b' = '0'))); +ERROR: target in JSON_TRANSFORM already exists +CREATE INDEX ON jt_empty ((JSON_TRANSFORM(j, INSERT '$.b' = '0' IGNORE ON EXISTING))); +-- the planner matches the index however the query orders its clauses or +-- spells out a default, but not with a different behavior +CREATE INDEX jt_empty_ins ON jt_empty ((JSON_TRANSFORM(j, INSERT '$.n' = '1' IGNORE ON EXISTING))); +SET enable_seqscan = off; +EXPLAIN (COSTS OFF) +SELECT j FROM jt_empty +WHERE JSON_TRANSFORM(j, INSERT '$.n' = '1' NULL ON NULL IGNORE ON EXISTING) = '{"a": 1, "b": 2, "n": 1}'; + QUERY PLAN +----------------------------------------------------------------------------------------------------------------------- + Index Scan using jt_empty_ins on jt_empty + Index Cond: (JSON_TRANSFORM(j, INSERT '$."n"' = '1'::jsonb IGNORE ON EXISTING) = '{"a": 1, "b": 2, "n": 1}'::jsonb) +(2 rows) + +SELECT j FROM jt_empty +WHERE JSON_TRANSFORM(j, INSERT '$.n' = '1' NULL ON NULL IGNORE ON EXISTING) = '{"a": 1, "b": 2, "n": 1}'; + j +------------------ + {"a": 1, "b": 2} +(1 row) + +EXPLAIN (COSTS OFF) +SELECT j FROM jt_empty +WHERE JSON_TRANSFORM(j, INSERT '$.n' = '1') = '{"a": 1, "b": 2, "n": 1}'; + QUERY PLAN +------------------------------------------------------------------------------------------------ + Seq Scan on jt_empty + Disabled: true + Filter: (JSON_TRANSFORM(j, INSERT '$."n"' = '1'::jsonb) = '{"a": 1, "b": 2, "n": 1}'::jsonb) +(3 rows) + +RESET enable_seqscan; +DROP TABLE jt_empty; +-- Unlike the target path, the PATH source must be a string literal +SELECT JSON_TRANSFORM(j, REPLACE '$.a' = PATH p) FROM jt_tab; +ERROR: syntax error at or near "p" +LINE 1: SELECT JSON_TRANSFORM(j, REPLACE '$.a' = PATH p) FROM jt_tab... + ^ diff --git a/src/test/regress/parallel_schedule b/src/test/regress/parallel_schedule index bb13a7b6b8f..39d6dd7c01a 100644 --- a/src/test/regress/parallel_schedule +++ b/src/test/regress/parallel_schedule @@ -107,7 +107,7 @@ test: select_views portals_p2 portals_inflight foreign_key dependency guc bitmap # ---------- # Another group of parallel tests (JSON related) # ---------- -test: json jsonb json_encoding jsonpath jsonpath_encoding jsonb_jsonpath sqljson sqljson_queryfuncs sqljson_jsontable +test: json jsonb json_encoding jsonpath jsonpath_encoding jsonb_jsonpath sqljson sqljson_queryfuncs sqljson_jsontable sqljson_transform # ---------- # Another group of parallel tests diff --git a/src/test/regress/sql/sqljson_transform.sql b/src/test/regress/sql/sqljson_transform.sql new file mode 100644 index 00000000000..c4b13a06abe --- /dev/null +++ b/src/test/regress/sql/sqljson_transform.sql @@ -0,0 +1,271 @@ +-- JSON_TRANSFORM + +-- Basic actions on a jsonb document +SELECT JSON_TRANSFORM('{"a": 1, "b": 2}'::jsonb, REMOVE '$.a'); +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, INSERT '$.b' = '2'); +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.a' = '9'); +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, RENAME '$.a' = 'z'); + +-- INSERT of an existing key raises an error by default (ERROR ON EXISTING); +-- IGNORE ON EXISTING keeps the existing member unchanged +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, INSERT '$.a' = '2'); +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, INSERT '$.a' = '2' IGNORE ON EXISTING); + +-- INSERT does not create missing parent objects; nothing is inserted +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, INSERT '$.x.y' = '2'); +SELECT JSON_TRANSFORM('{"a": {}}'::jsonb, INSERT '$.a.y' = '2'); + +-- REPLACE/RENAME/REMOVE of a missing key: default IGNORE ON MISSING +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.b' = '2'); +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.b' = '2' ERROR ON MISSING); +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REMOVE '$.b'); +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REMOVE '$.b' ERROR ON MISSING); +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, RENAME '$.b' = 'c'); +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, RENAME '$.b' = 'c' ERROR ON MISSING); + +-- RENAME onto a key that already exists in the same object is an error; +-- renaming a key to its own name is not, and keys of other objects do not +-- count +SELECT JSON_TRANSFORM('{"a": 1, "b": 2}'::jsonb, RENAME '$.a' = 'b'); +SELECT JSON_TRANSFORM('{"a": 1, "b": 2}'::jsonb, RENAME '$.a' = 'a'); +SELECT JSON_TRANSFORM('{"o": {"a": 1}, "b": 2}'::jsonb, RENAME '$.o.a' = 'b'); + +-- Wildcard member accessor '.*' applies the action to every member +SELECT JSON_TRANSFORM('{"a": 1, "b": 2}'::jsonb, REPLACE '$.*' = '0'); +SELECT JSON_TRANSFORM('{"a": 1, "b": 2}'::jsonb, REMOVE '$.*'); +-- ... also in the middle of a path, where non-objects are skipped (lax) +SELECT JSON_TRANSFORM('{"p": {"x": 1, "y": 2}, "q": {"x": 3}, "r": 5}'::jsonb, + REPLACE '$.*.x' = '0'); +-- ... and a wildcard that matches nothing is a missing target +SELECT JSON_TRANSFORM('{}'::jsonb, REPLACE '$.*' = '0'); +SELECT JSON_TRANSFORM('{}'::jsonb, REPLACE '$.*' = '0' ERROR ON MISSING); +SELECT JSON_TRANSFORM('{}'::jsonb, REMOVE '$.*' ERROR ON MISSING); + +-- Nested member accessors +SELECT JSON_TRANSFORM('{"a": {"b": {"c": 1}}}'::jsonb, REPLACE '$.a.b.c' = '2'); + +-- lax mode (the default) unwraps arrays; strict mode errors on them +SELECT JSON_TRANSFORM('{"arr": [{"a": 1}, {"a": 2}]}'::jsonb, REPLACE 'lax $.arr.a' = '9'); +SELECT JSON_TRANSFORM('{"arr": [{"a": 1}]}'::jsonb, REPLACE '$.arr.a' = '9'); +SELECT JSON_TRANSFORM('{"arr": [{"a": 1}]}'::jsonb, REPLACE 'strict $.arr.a' = '9'); +-- lax unwraps one array level only, and skips scalars, like jsonb_path_query() +SELECT JSON_TRANSFORM('{"arr": [[{"a": 1}], 7, {"a": 2}]}'::jsonb, REPLACE '$.arr.a' = '9'); +SELECT jsonb_path_query('{"arr": [[{"a": 1}], 7, {"a": 2}]}', 'lax $.arr.a'); +-- strict: a member accessor applied to a scalar or an array is an error +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE 'strict $.a.b' = '9'); +SELECT JSON_TRANSFORM('{"a": [1]}'::jsonb, REPLACE 'strict $.a.*' = '9'); +-- top-level array and top-level scalar documents +SELECT JSON_TRANSFORM('[{"a": 1}, {"b": 2}]'::jsonb, REMOVE '$.a'); +SELECT JSON_TRANSFORM('5'::jsonb, REMOVE '$.a'); +SELECT JSON_TRANSFORM('5'::jsonb, REMOVE '$.a' ERROR ON MISSING); + +-- "= PATH " source: the value is pulled from the input document +SELECT JSON_TRANSFORM('{"a": 1, "b": 42}'::jsonb, REPLACE '$.a' = PATH '$.b'); +SELECT JSON_TRANSFORM('{"a": 1, "b": {"c": [1, 2, 3]}}'::jsonb, INSERT '$.d' = PATH '$.b.c'); + +-- PASSING variables are visible to a PATH source +SELECT JSON_TRANSFORM('{"a": 1, "b": 42}'::jsonb, REPLACE '$.a' = PATH '$x' PASSING 99 AS x); +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.a' = PATH '$x' PASSING '"hi"'::jsonb AS x); +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.a' = PATH '$x' PASSING 'hello' AS x); +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, INSERT '$.b' = PATH '$x' PASSING 7 AS x); +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.a' = PATH '$x + 1' PASSING 41 AS x); +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.a' = PATH '$y' PASSING 1 AS x, 2 AS y); +-- PASSING is accepted, but has no effect, without a PATH source +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.a' = '5' PASSING 99 AS x); +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REMOVE '$.a' PASSING 99 AS x); + +-- Unbound variable in a PATH source is an error +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.a' = PATH '$y'); + +-- PATH source cardinality routing (SQL:2023 6.44 GR): 0 items -> ON EMPTY, +-- >1 items or a structural error -> ON ERROR. +-- Default is NULL ON EMPTY, ERROR ON ERROR. +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.a' = PATH '$.nope'); +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.a' = PATH '$.nope' ERROR ON EMPTY); +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.a' = PATH '$.nope' IGNORE ON EMPTY); +SELECT JSON_TRANSFORM('{"a": 1, "arr": [10, 20]}'::jsonb, REPLACE '$.a' = PATH '$.arr[*]'); +SELECT JSON_TRANSFORM('{"a": 1, "arr": [10, 20]}'::jsonb, REPLACE '$.a' = PATH '$.arr[*]' NULL ON ERROR); +SELECT JSON_TRANSFORM('{"a": 1, "arr": [10, 20]}'::jsonb, REPLACE '$.a' = PATH '$.arr[*]' IGNORE ON ERROR); +-- a single item that is itself an array is fine +SELECT JSON_TRANSFORM('{"a": 1, "arr": [10, 20]}'::jsonb, REPLACE '$.a' = PATH '$.arr'); +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.a' = PATH 'strict $.nope'); +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.a' = PATH 'strict $.nope' NULL ON ERROR); + +-- ON EMPTY vs ON ERROR are independent knobs (cross test) +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.a' = PATH '$.nope' IGNORE ON EMPTY ERROR ON ERROR); +SELECT JSON_TRANSFORM('{"a": 1, "arr": [10, 20]}'::jsonb, REPLACE '$.a' = PATH '$.arr[*]' ERROR ON EMPTY IGNORE ON ERROR); + +-- ON NULL for a literal (non-PATH) source +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.a' = NULL); +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.a' = NULL NULL ON NULL); +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.a' = NULL ERROR ON NULL); +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.a' = NULL IGNORE ON NULL); +SELECT JSON_TRANSFORM('{"a": 1, "b": 2}'::jsonb, REPLACE '$.a' = NULL REMOVE ON NULL); + +-- Behavior clauses that do not apply to the action are rejected +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.a' = '2' IGNORE ON EXISTING); +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, INSERT '$.b' = '2' IGNORE ON MISSING); +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, INSERT '$.a' = '2' NULL ON EXISTING); +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, INSERT '$.b' = NULL REMOVE ON NULL); +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.b' = '2' NULL ON MISSING); +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REMOVE '$.a' NULL ON NULL); +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REMOVE '$.a' ERROR ON EMPTY); +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.a' = PATH '$.b' REMOVE ON EMPTY); +-- ON EMPTY / ON ERROR are accepted with a non-PATH source, but only the +-- PATH source rules ever consult them +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.a' = '2' IGNORE ON ERROR); + +-- The standard's SQLSTATEs (SQL:2023 6.44) +\set VERBOSITY sqlstate +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, INSERT '$.a' = '2'); +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.a' = NULL ERROR ON NULL); +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REMOVE '$.b' ERROR ON MISSING); +SELECT JSON_TRANSFORM('{"a": 1, "b": 2}'::jsonb, RENAME '$.a' = 'b'); +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.a' = PATH '$.nope' ERROR ON EMPTY); +SELECT JSON_TRANSFORM('{"a": 1, "arr": [10, 20]}'::jsonb, REPLACE '$.a' = PATH '$.arr[*]'); +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.a' = PATH 'strict $.nope'); +\set VERBOSITY default + +-- Target-path validation: must start with $, only member/wildcard accessors +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REMOVE 'lax @.a'); +SELECT JSON_TRANSFORM('{"a": [1, 2]}'::jsonb, REMOVE '$.a[0]'); +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REMOVE '$.a ? (@ == 1)'); +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REMOVE '$.a.type()'); +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REMOVE '$'); +-- A variable cannot be referenced in the target path, not even as its start +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REMOVE '$.a ? (@ == $x)' PASSING 1 AS x); +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REMOVE '$x.a' PASSING '{"a": 1}'::jsonb AS x); +-- The target path must be a jsonpath +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REMOVE 42); +-- Deep paths (more steps than the initial step array holds) +SELECT JSON_TRANSFORM('{"a":{"b":{"c":{"d":{"e":{"f":{"g":{"h":{"i":{"j":1}}}}}}}}}}'::jsonb, + REPLACE '$.a.b.c.d.e.f.g.h.i.j' = '2'); +-- The last accessor of INSERT/RENAME may not be a wildcard +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, INSERT '$.*' = '1'); +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, RENAME '$.*' = 'z'); + +-- NULL input document returns NULL +SELECT JSON_TRANSFORM(NULL::jsonb, REMOVE '$.a'); + +-- Unquoted (text) input is accepted and treated as JSON +SELECT JSON_TRANSFORM('{"a": 1}', REPLACE '$.a' = '2'); + +-- Non-constant arguments: column references and sub-selects as the value +-- (a sub-select used to crash), and a column as the target path. These are +-- not folded at plan time, so they also run the executor (and JIT) path. +CREATE TABLE jt_tab (id int, j jsonb, v jsonb, p jsonpath); +INSERT INTO jt_tab VALUES + (1, '{"a": 1, "b": 2}', '"x"', '$.a'), + (2, '{"a": {"c": 3}}', NULL, '$.a.c'), + (3, NULL, '1', '$.b'); +SELECT id, JSON_TRANSFORM(j, REPLACE '$.a' = v) FROM jt_tab ORDER BY id; +SELECT id, JSON_TRANSFORM(j, REPLACE '$.a' = (SELECT v)) FROM jt_tab ORDER BY id; +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REPLACE '$.a' = (SELECT '[1, 2]'::jsonb)); +SELECT id, JSON_TRANSFORM(j, REPLACE p = '0') FROM jt_tab ORDER BY id; +SELECT id, JSON_TRANSFORM(j, REPLACE '$.a' = PATH '$x' PASSING id AS x) FROM jt_tab ORDER BY id; +SELECT id, JSON_TRANSFORM(j, INSERT '$.b' = v IGNORE ON EXISTING) FROM jt_tab ORDER BY id; + +-- A function call followed by IGNORE ON ... is read as the start of IGNORE +-- NULLS (one token of lookahead cannot tell them apart), so it must be +-- parenthesized +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, INSERT '$.b' = to_jsonb(1) IGNORE ON EXISTING); +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, INSERT '$.b' = (to_jsonb(1)) IGNORE ON EXISTING); + +-- Deparse: EXPLAIN VERBOSE and stored views must round-trip. Clauses equal +-- to their default are not printed. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT JSON_TRANSFORM('{"a": 1}'::jsonb, REMOVE '$.a'); +EXPLAIN (VERBOSE, COSTS OFF) +SELECT JSON_TRANSFORM(j, REPLACE '$.a' = v ERROR ON MISSING) FROM jt_tab; +-- jt_view is left in place so that pg_upgrade's dump/restore test exercises it +CREATE VIEW jt_view AS +SELECT id, + JSON_TRANSFORM(j, REPLACE '$.a' = PATH '$x' ERROR ON ERROR PASSING 5 AS x) AS r1, + JSON_TRANSFORM(j, REPLACE '$.a' = PATH '$.b' IGNORE ON EMPTY NULL ON ERROR) AS r2, + JSON_TRANSFORM(j, INSERT '$.n' = (to_jsonb(id)) IGNORE ON EXISTING) AS r3, + JSON_TRANSFORM(j, REMOVE p ERROR ON MISSING) AS r4, + JSON_TRANSFORM(j, RENAME '$.a' = 'z') AS r5, + JSON_TRANSFORM(j, REPLACE '$.a' = v REMOVE ON NULL) AS r6, + JSON_TRANSFORM(j, REPLACE '$.b' = '"k"') AS r7 +FROM jt_tab; +SELECT pg_get_viewdef('jt_view', true); +-- the deparsed text must be accepted by the parser again +DO $$ +BEGIN + EXECUTE 'CREATE VIEW jt_view2 AS ' || pg_get_viewdef('jt_view'); +END +$$; +SELECT pg_get_viewdef('jt_view') = pg_get_viewdef('jt_view2') AS same; +DROP VIEW jt_view2; +SELECT * FROM jt_view ORDER BY id; + +-- JSON_TRANSFORM is immutable, so it may be used in a functional index; +-- jt_idx is left in place for the dump/restore test as well +CREATE INDEX jt_idx ON jt_tab ((JSON_TRANSFORM(j, REMOVE '$.a'))); +CREATE INDEX jt_idx2 ON jt_tab ((JSON_TRANSFORM(j, REPLACE '$.a' = PATH '$.b'))); +INSERT INTO jt_tab VALUES (4, '{"a": 1, "b": 2}', NULL, '$.b'); +DROP INDEX jt_idx2; +-- ... but not if any part of it is not: the target path, the value, or a +-- mutable PATH source +CREATE INDEX ON jt_tab ((JSON_TRANSFORM(j, REMOVE (CASE WHEN random() > 2 THEN '$.x' ELSE '$.a' END)::jsonpath))); +CREATE INDEX ON jt_tab ((JSON_TRANSFORM(j, REPLACE '$.a' = to_jsonb(random())))); +CREATE INDEX ON jt_tab ((JSON_TRANSFORM(j, REPLACE '$.a' = PATH '$.b.datetime("HH:MI TZH") < $.b.datetime("HH:MI")'))); + +-- jt_idx3, with a non-default clause, is also left in place +CREATE INDEX jt_idx3 ON jt_tab ((JSON_TRANSFORM(j, INSERT '$.n' = '1' IGNORE ON EXISTING))); +SELECT pg_get_indexdef('jt_idx3'::regclass); + +-- An invalid constant target path is rejected when an index, view, or +-- generated column is defined, even on an empty table where nothing gets +-- evaluated; otherwise every later INSERT would fail +CREATE TABLE jt_empty (j jsonb, p jsonpath); +CREATE INDEX ON jt_empty ((JSON_TRANSFORM(j, REMOVE '$x.a' PASSING 1 AS x))); +CREATE INDEX ON jt_empty ((JSON_TRANSFORM(j, REMOVE '$[0]'))); +CREATE INDEX ON jt_empty ((JSON_TRANSFORM(j, REMOVE '$.a ? (@ > 1)'))); +CREATE INDEX ON jt_empty ((JSON_TRANSFORM(j, REMOVE '$.**'))); +CREATE INDEX ON jt_empty ((JSON_TRANSFORM(j, REMOVE '$'))); +CREATE INDEX ON jt_empty ((JSON_TRANSFORM(j, INSERT '$.*' = '1'))); +CREATE INDEX ON jt_empty ((JSON_TRANSFORM(j, RENAME '$.*' = 'z'))); +CREATE VIEW jt_bad_view AS SELECT JSON_TRANSFORM(j, REMOVE '$[0]') FROM jt_empty; +ALTER TABLE jt_empty ADD COLUMN g jsonb + GENERATED ALWAYS AS (JSON_TRANSFORM(j, REMOVE '$[0]')) STORED; +-- ... also when the path only becomes a constant during planning +CREATE INDEX ON jt_empty ((JSON_TRANSFORM(j, REMOVE '$[0]'::text))); +ALTER TABLE jt_empty ADD COLUMN g jsonb + GENERATED ALWAYS AS (JSON_TRANSFORM(j, REMOVE '$[0]'::text)) STORED; +-- ... and when a NULL input means the executor would never look at it +SELECT JSON_TRANSFORM(NULL::jsonb, REMOVE '$[0]'); +-- a valid path folded during planning is fine +CREATE INDEX ON jt_empty ((JSON_TRANSFORM(j, REMOVE '$.a'::text))); +INSERT INTO jt_empty VALUES ('{"a": 1, "b": 2}'); +-- a non-constant target path makes the expression mutable, and can only be +-- checked at run time +CREATE INDEX ON jt_empty ((JSON_TRANSFORM(j, REMOVE p))); +SELECT JSON_TRANSFORM('{"a": 1}', REMOVE p) FROM (VALUES ('$[0]'::jsonpath)) v(p); +-- mutable through a PASSING argument: a volatile value, or a timestamptz +-- compared with a datetime of unknown type (time zone dependent, as for +-- JSON_QUERY); an immutable PASSING argument is fine +CREATE INDEX ON jt_empty ((JSON_TRANSFORM(j, INSERT '$.r' = PATH '$.a + $x' PASSING random() AS x))); +CREATE INDEX ON jt_empty ((JSON_TRANSFORM(j, INSERT '$.r' = PATH '$.d.datetime() < $x' + PASSING '2020-01-01 00:00'::timestamptz AS x))); +CREATE INDEX ON jt_empty ((JSON_TRANSFORM(j, INSERT '$.r' = PATH '$.a + $x' PASSING 1 AS x))); +-- a data-dependent error is still raised while building the index +CREATE INDEX ON jt_empty ((JSON_TRANSFORM(j, INSERT '$.b' = '0'))); +CREATE INDEX ON jt_empty ((JSON_TRANSFORM(j, INSERT '$.b' = '0' IGNORE ON EXISTING))); +-- the planner matches the index however the query orders its clauses or +-- spells out a default, but not with a different behavior +CREATE INDEX jt_empty_ins ON jt_empty ((JSON_TRANSFORM(j, INSERT '$.n' = '1' IGNORE ON EXISTING))); +SET enable_seqscan = off; +EXPLAIN (COSTS OFF) +SELECT j FROM jt_empty +WHERE JSON_TRANSFORM(j, INSERT '$.n' = '1' NULL ON NULL IGNORE ON EXISTING) = '{"a": 1, "b": 2, "n": 1}'; +SELECT j FROM jt_empty +WHERE JSON_TRANSFORM(j, INSERT '$.n' = '1' NULL ON NULL IGNORE ON EXISTING) = '{"a": 1, "b": 2, "n": 1}'; +EXPLAIN (COSTS OFF) +SELECT j FROM jt_empty +WHERE JSON_TRANSFORM(j, INSERT '$.n' = '1') = '{"a": 1, "b": 2, "n": 1}'; +RESET enable_seqscan; +DROP TABLE jt_empty; + +-- Unlike the target path, the PATH source must be a string literal +SELECT JSON_TRANSFORM(j, REPLACE '$.a' = PATH p) FROM jt_tab; -- 2.43.0