From de2449cb8deae445ecdd8f9ba190bcb2a1c1e3d1 Mon Sep 17 00:00:00 2001 From: Srinath Reddy Sadipiralla Date: Fri, 4 Dec 2026 17:31:57 +0530 Subject: [PATCH v5 1/2] SQL/JSON: Add JSON_TRANSFORM JSON_TRANSFORM(context_item, action [PASSING ...]) is the SQL/JSON function defined in subclause 6.44 of the SQL standard. It yields a copy of the input JSON value with one modification applied. The action is one of: INSERT = add a member that must not already exist REPLACE = change the value of an existing member REMOVE delete a member RENAME = give a member a new key name The target path must start with $ and may contain only member accessors (.key) and wildcard member accessors (.*). REMOVE and REPLACE may end in a wildcard, acting on every member at that level; INSERT and RENAME must end in a named member. In lax mode, the default, an accessor applied to an array is applied to each of its elements; in strict mode that is an error. This matches jsonb_path_query() for the same paths. Each action may carry the behavior clauses defined by the standard. INSERT accepts ON EXISTING and ON NULL, REPLACE accepts ON MISSING and ON NULL, and REMOVE and RENAME accept ON MISSING. An omitted clause takes the standard's default: ERROR ON EXISTING and NULL ON NULL for INSERT, IGNORE ON MISSING and NULL ON NULL for REPLACE, and IGNORE ON MISSING for REMOVE and RENAME. The clauses are parsed into a list of JsonTransformBehaviorClause nodes, then validated and resolved during parse analysis, so an error can point at the offending clause. ON EMPTY and ON ERROR are parsed but rejected here; they apply only to a PATH source, which a following commit adds. JSON_TRANSFORM reuses the JsonExpr node with a new JSON_TRANSFORM_OP and a JsonTransformAction that holds the operation, target path, value and resolved behaviors. A new EEOP_JSON_TRANSFORM step evaluates it in a single streaming pass over the input jsonb, using the JsonbIterator and pushJsonbValue API to apply the action where the path matches and copy everything else through unchanged. The cost is one pass over the document however many members a wildcard matches, and the shared jsonb_set, jsonb_insert and jsonb_delete_path code is left alone. Also add expression walker and mutator support, a mutability check in contain_mutable_functions_walker() so that JSON_TRANSFORM can be used in an index expression, and deparse support in ruleutils.c. A literal target path is checked against the standard's restrictions during parse analysis, and a target path that only becomes a constant during planning (such as '$[0]'::text) is checked in eval_const_expressions(). An invalid path is thus rejected when an index, view, or generated column is defined, rather than accepted on an empty table and then failing every later insertion. The executor still checks a non-constant target path, such as a column. New keywords: JSON_TRANSFORM (column name keyword), and EXISTING, MISSING and REMOVE (unreserved). IGNORE is now used both by window function null treatment (IGNORE NULLS) and by the IGNORE ON ... behavior clause, which gives a shift/reduce conflict. IGNORE_P is given a precedence so that the parser shifts, binding IGNORE to NULLS exactly as before. Discussion: https://postgr.es/m/CAFC+b6pQxA0-YV8B-8KFub_bix_wdhA+oHrv7S1rYb2tQjjPzg@mail.gmail.com --- src/backend/executor/execExpr.c | 161 ++++++++++ src/backend/executor/execExprInterp.c | 412 ++++++++++++++++++++++++++ src/backend/jit/llvm/llvmjit_expr.c | 6 + src/backend/jit/llvm/llvmjit_types.c | 1 + src/backend/nodes/nodeFuncs.c | 22 ++ src/backend/optimizer/util/clauses.c | 63 +++- src/backend/parser/gram.y | 140 ++++++++- src/backend/parser/parse_expr.c | 224 +++++++++++++- src/backend/parser/parse_target.c | 3 + src/backend/utils/adt/jsonpath.c | 89 ++++++ src/backend/utils/adt/ruleutils.c | 135 ++++++++- src/backend/utils/errcodes.txt | 3 + src/include/executor/execExpr.h | 9 + src/include/nodes/execnodes.h | 14 + src/include/nodes/parsenodes.h | 1 + src/include/nodes/primnodes.h | 64 ++++ src/include/parser/kwlist.h | 4 + src/include/utils/jsonpath.h | 19 ++ src/tools/pgindent/typedefs.list | 7 + 19 files changed, 1339 insertions(+), 38 deletions(-) diff --git a/src/backend/executor/execExpr.c b/src/backend/executor/execExpr.c index 91c429b894a..91195f3e610 100644 --- a/src/backend/executor/execExpr.c +++ b/src/backend/executor/execExpr.c @@ -99,6 +99,9 @@ static void ExecBuildAggTransCall(ExprState *state, AggState *aggstate, static void ExecInitJsonExpr(JsonExpr *jsexpr, ExprState *state, Datum *resv, bool *resnull, ExprEvalStep *scratch); +static void ExecInitJsonTransformExpr(JsonExpr *jsexpr, ExprState *state, + Datum *resv, bool *resnull, + ExprEvalStep *scratch); static void ExecInitJsonCoercion(ExprState *state, JsonReturning *returning, ErrorSaveContext *escontext, bool omit_quotes, bool exists_coerce, @@ -2499,6 +2502,8 @@ ExecInitExprRec(Expr *node, ExprState *state, if (jsexpr->op == JSON_TABLE_OP) ExecInitExprRec((Expr *) jsexpr->formatted_expr, state, resv, resnull); + else if (jsexpr->op == JSON_TRANSFORM_OP) + ExecInitJsonTransformExpr(jsexpr, state, resv, resnull, &scratch); else ExecInitJsonExpr(jsexpr, state, resv, resnull, &scratch); break; @@ -5058,6 +5063,162 @@ ExecInitJsonExpr(JsonExpr *jsexpr, ExprState *state, jsestate->jump_end = state->steps_len; } +/* + * Compile a JSON_TRANSFORM expression into a sequence of expression-eval + * steps. + * + * JSON_TRANSFORM is fundamentally different from JSON_QUERY/VALUE/EXISTS: + * those ops query a document, we mutate one. So we don't reuse + * ExecInitJsonExpr; we emit our own step sequence tailored to the mutation + * pipeline. + * + * The standard allows exactly one (SQL:2023 + * 6.44), so a single action is attached to the JsonExpr. The step layout is: + * + * steps[..] evaluate formatted_expr (input doc) -> jtstate->formatted_expr + * 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->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) + * 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) + */ +static void +ExecInitJsonTransformExpr(JsonExpr *jsexpr, ExprState *state, + Datum *resv, bool *resnull, + ExprEvalStep *scratch) +{ + JsonTransformExprState *jtstate = palloc0(sizeof(JsonTransformExprState)); + JsonTransformAction *action = jsexpr->action; + List *jumps_return_null = NIL; + ListCell *argexprlc; + ListCell *argnamelc; + ListCell *lc; + + Assert(action != NULL); + + jtstate->jsexpr = jsexpr; + + /* + * Evaluate formatted_expr storing the result into + * jtstate->formatted_expr. + */ + ExecInitExprRec((Expr *) jsexpr->formatted_expr, state, + &jtstate->formatted_expr.value, + &jtstate->formatted_expr.isnull); + + /* JUMP to return-NULL landing pad if formatted_expr is NULL */ + jumps_return_null = lappend_int(jumps_return_null, state->steps_len); + scratch->opcode = EEOP_JUMP_IF_NULL; + scratch->resnull = &jtstate->formatted_expr.isnull; + scratch->d.jump.jumpdone = -1; /* patched below */ + ExprEvalPushStep(state, scratch); + + /* + * Evaluate the action's pathspec (a compiled jsonpath Const) into + * jtstate->pathspec. + */ + ExecInitExprRec((Expr *) action->pathspec, state, + &jtstate->pathspec.value, + &jtstate->pathspec.isnull); + + /* JUMP to return-NULL landing pad if pathspec is NULL */ + jumps_return_null = lappend_int(jumps_return_null, state->steps_len); + scratch->opcode = EEOP_JUMP_IF_NULL; + scratch->resnull = &jtstate->pathspec.isnull; + scratch->d.jump.jumpdone = -1; /* patched below */ + ExprEvalPushStep(state, scratch); + + /* + * Evaluate the action's value_expr, if any. REMOVE has no value. + */ + if (action->value_expr != NULL) + { + ExecInitExprRec((Expr *) action->value_expr, state, + &jtstate->action_value.value, + &jtstate->action_value.isnull); + } + + /* + * 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. + */ + jtstate->args = NIL; + forboth(argexprlc, jsexpr->passing_values, + argnamelc, jsexpr->passing_names) + { + Expr *argexpr = (Expr *) lfirst(argexprlc); + String *argname = lfirst_node(String, argnamelc); + JsonPathVariable *var = palloc(sizeof(*var)); + + var->name = argname->sval; + var->namelen = strlen(var->name); + var->typid = exprType((Node *) argexpr); + var->typmod = exprTypmod((Node *) argexpr); + + ExecInitExprRec((Expr *) argexpr, state, &var->value, &var->isnull); + + jtstate->args = lappend(jtstate->args, var); + } + + /* + * The main step: EEOP_JSON_TRANSFORM. Its handler branches on + * action->op, converts the jsonpath to a text[] path, and calls the + * appropriate jsonb mutation function, writing the result to resv. + */ + scratch->opcode = EEOP_JSON_TRANSFORM; + scratch->resvalue = resv; + scratch->resnull = resnull; + scratch->d.json_transform.jtstate = jtstate; + ExprEvalPushStep(state, scratch); + + /* + * Unconditional JUMP over the NULL landing pad below. Without this, a + * successful main step would fall through into EEOP_CONST(NULL) and have + * its result overwritten with NULL. + */ + { + int jump_past_null = state->steps_len; + + scratch->opcode = EEOP_JUMP; + scratch->d.jump.jumpdone = -1; /* patched below */ + ExprEvalPushStep(state, scratch); + + /* + * Patch the JUMP_IF_NULL placeholders to land on the NULL pad we are + * about to emit. + */ + foreach(lc, jumps_return_null) + { + ExprEvalStep *as = &state->steps[lfirst_int(lc)]; + + as->d.jump.jumpdone = state->steps_len; + } + + /* Return-NULL landing pad */ + scratch->opcode = EEOP_CONST; + scratch->resvalue = resv; + scratch->resnull = resnull; + scratch->d.constval.value = (Datum) 0; + scratch->d.constval.isnull = true; + ExprEvalPushStep(state, scratch); + + /* + * Patch the unconditional JUMP to land just past the NULL pad. + * Success path (via JUMP) and null path (via fallthrough) converge + * here. + */ + state->steps[jump_past_null].d.jump.jumpdone = state->steps_len; + } +} + /* * Initialize a EEOP_JSONEXPR_COERCION step to coerce the value given in resv * to the given RETURNING type. diff --git a/src/backend/executor/execExprInterp.c b/src/backend/executor/execExprInterp.c index 8f3363b4219..8184c88e96d 100644 --- a/src/backend/executor/execExprInterp.c +++ b/src/backend/executor/execExprInterp.c @@ -177,6 +177,18 @@ static Datum ExecJustHashOuterVarVirt(ExprState *state, ExprContext *econtext, b static Datum ExecJustHashInnerVarVirt(ExprState *state, ExprContext *econtext, bool *isnull); static Datum ExecJustHashOuterVarStrict(ExprState *state, ExprContext *econtext, bool *isnull); +static void jtSetPath(JsonbIterator **it, JsonbInState *st, + JsonTransformStep *steps, int nsteps, int level, + JsonTransformOp op, JsonbValue *newval, + JsonTransformBehavior on_existing, bool strict, + bool unwrap, bool *matched); +static void jtSetPathObject(JsonbIterator **it, JsonbInState *st, + JsonTransformStep *steps, int nsteps, int level, + JsonTransformOp op, JsonbValue *newval, + JsonTransformBehavior on_existing, bool strict, + bool *matched, uint32 npairs); +static void jtCopyValue(JsonbIterator **it, JsonbInState *st); + /* execution helper functions */ static pg_always_inline void ExecEvalArrayCompareInternal(FunctionCallInfo fcinfo, ArrayType *arr, @@ -579,6 +591,7 @@ ExecInterpExpr(ExprState *state, ExprContext *econtext, bool *isnull) &&CASE_EEOP_JSON_CONSTRUCTOR, &&CASE_EEOP_IS_JSON, &&CASE_EEOP_JSONEXPR_PATH, + &&CASE_EEOP_JSON_TRANSFORM, &&CASE_EEOP_JSONEXPR_COERCION, &&CASE_EEOP_JSONEXPR_COERCION_FINISH, &&CASE_EEOP_AGGREF, @@ -1942,6 +1955,13 @@ ExecInterpExpr(ExprState *state, ExprContext *econtext, bool *isnull) EEO_JUMP(ExecEvalJsonExprPath(state, op, econtext)); } + EEO_CASE(EEOP_JSON_TRANSFORM) + { + /* too complex for an inline implementation */ + ExecEvalJsonTransform(state, op, econtext); + EEO_NEXT(); + } + EEO_CASE(EEOP_JSONEXPR_COERCION) { /* too complex for an inline implementation */ @@ -5128,6 +5148,398 @@ ExecEvalJsonExprPath(ExprState *state, ExprEvalStep *op, return jump_eval_coercion >= 0 ? jump_eval_coercion : jsestate->jump_end; } +/* + * Copy the next value from *it into *st verbatim (scalar or whole container). + * Precondition: the value's token has NOT yet been read from *it. + * + * This is the standard "stream through unchanged" idiom used by setPath(): + * descend with skipNested=false and re-emit every token until the container + * we opened is balanced again. + */ +static void +jtCopyValue(JsonbIterator **it, JsonbInState *st) +{ + JsonbValue v; + JsonbIteratorToken r = JsonbIteratorNext(it, &v, false); + + pushJsonbValue(st, r, r < WJB_BEGIN_ARRAY ? &v : NULL); + + if (r == WJB_BEGIN_ARRAY || r == WJB_BEGIN_OBJECT) + { + int walking_level = 1; + + while (walking_level != 0) + { + r = JsonbIteratorNext(it, &v, false); + if (r == WJB_BEGIN_ARRAY || r == WJB_BEGIN_OBJECT) + walking_level++; + else if (r == WJB_END_ARRAY || r == WJB_END_OBJECT) + walking_level--; + pushJsonbValue(st, r, r < WJB_BEGIN_ARRAY ? &v : NULL); + } + } +} + +/* + * Walk one object's members, rebuilding it into *st and applying the action + * to members matched by steps[level]. + * + * A named-key step matches at most one member; a wildcard step matches every + * member (and so must not "stop" after the first match). + */ +static void +jtSetPathObject(JsonbIterator **it, JsonbInState *st, + JsonTransformStep *steps, int nsteps, int level, + JsonTransformOp op, JsonbValue *newval, + JsonTransformBehavior on_existing, bool strict, + bool *matched, uint32 npairs) +{ + JsonTransformStep *step = &steps[level]; + bool is_last = (level == nsteps - 1); + bool found = false; + uint32 i; + + for (i = 0; i < npairs; i++) + { + JsonbValue k, + v; + JsonbIteratorToken r PG_USED_FOR_ASSERTS_ONLY; + bool is_match; + + r = JsonbIteratorNext(it, &k, true); + Assert(r == WJB_KEY); + + is_match = step->wildcard || + (k.val.string.len == step->keylen && + memcmp(k.val.string.val, step->key, step->keylen) == 0); + + if (is_match && !step->wildcard) + found = true; + + if (is_match && is_last) + { + switch (op) + { + case TRANSFORM_REMOVE: + /* swallow the value; push nothing -> member removed */ + (void) JsonbIteratorNext(it, &v, true); + *matched = true; + break; + + case TRANSFORM_REPLACE: + /* drop old value, push key + replacement */ + (void) JsonbIteratorNext(it, &v, true); + pushJsonbValue(st, WJB_KEY, &k); + pushJsonbValue(st, WJB_VALUE, newval); + *matched = true; + break; + + case TRANSFORM_INSERT: + + /* + * Target key already present. ERROR (default) raises; + * IGNORE keeps the existing member unchanged. + */ + if (on_existing == JSON_TRANSFORM_BEHAVIOR_ERROR) + ereport(ERROR, + errcode(ERRCODE_TARGET_IN_JSON_TRANSFORM_ALREADY_EXISTS), + errmsg("target in JSON_TRANSFORM already exists")); + (void) JsonbIteratorNext(it, &v, true); + pushJsonbValue(st, WJB_KEY, &k); + pushJsonbValue(st, WJB_VALUE, &v); + break; + + case TRANSFORM_RENAME: + + /* + * Rename the key: read the existing value and re-emit it + * under the new name carried in newval (a jbvString). + * + * Renaming onto a name that another member of this object + * already has would produce duplicate keys, which the + * standard says is an error. *it is this object's own + * iterator here, so look the new name up in its container + * before emitting anything. Renaming a key to itself is + * a harmless no-op. + */ + if ((newval->val.string.len != k.val.string.len || + memcmp(newval->val.string.val, k.val.string.val, + k.val.string.len) != 0) && + findJsonbValueFromContainer((*it)->container, + JB_FOBJECT, newval) != NULL) + ereport(ERROR, + errcode(ERRCODE_NON_UNIQUE_KEYS_IN_A_JSON_OBJECT), + errmsg("cannot rename JSON_TRANSFORM target to \"%s\": key already exists", + pnstrdup(newval->val.string.val, + newval->val.string.len))); + (void) JsonbIteratorNext(it, &v, true); + pushJsonbValue(st, WJB_KEY, newval); + pushJsonbValue(st, WJB_VALUE, &v); + *matched = true; + break; + + default: + elog(ERROR, "unexpected JsonTransformOp %d", (int) op); + } + } + else if (is_match && !is_last) + { + /* descend into this member's value to continue matching */ + pushJsonbValue(st, WJB_KEY, &k); + jtSetPath(it, st, steps, nsteps, level + 1, op, newval, + on_existing, strict, !strict, matched); + } + else + { + /* not a target: copy the member through unchanged */ + pushJsonbValue(st, WJB_KEY, &k); + jtCopyValue(it, st); + } + } + + /* + * INSERT of a new key: if the named (non-wildcard) last-level key wasn't + * found among the existing members, append it now. (A wildcard as the + * last INSERT accessor is rejected at path-validation time, so we never + * reach here with step->wildcard.) + */ + if (op == TRANSFORM_INSERT && is_last && !step->wildcard && !found) + { + JsonbValue newkey; + + newkey.type = jbvString; + newkey.val.string.val = step->key; + newkey.val.string.len = step->keylen; + pushJsonbValue(st, WJB_KEY, &newkey); + pushJsonbValue(st, WJB_VALUE, newval); + } +} + +/* + * Dispatcher: read the container/value currently at the front of *it and + * rebuild it into *st, recursing through objects along the path. + * + * 'strict' is the path's global mode; 'unwrap' says whether an array at this + * position should be lax-unwrapped -- true at a primary position in lax mode, + * false when recursing into an already-unwrapped array (keeping unwrapping one + * level deep). A '.key'/'.*' accessor needs an object: applied to an array we + * unwrap it (lax) or raise a structural error (strict); applied to a scalar we + * skip it (lax) or raise a structural error (strict). This matches the + * SQL/JSON path engine used by jsonb_path_query(). + */ +static void +jtSetPath(JsonbIterator **it, JsonbInState *st, + JsonTransformStep *steps, int nsteps, int level, + JsonTransformOp op, JsonbValue *newval, + JsonTransformBehavior on_existing, bool strict, bool unwrap, + bool *matched) +{ + JsonbValue v; + JsonbIteratorToken r; + + check_stack_depth(); + + r = JsonbIteratorNext(it, &v, false); + + if (r == WJB_BEGIN_OBJECT) + { + pushJsonbValue(st, WJB_BEGIN_OBJECT, NULL); + jtSetPathObject(it, st, steps, nsteps, level, op, newval, + on_existing, strict, matched, v.val.object.nPairs); + r = JsonbIteratorNext(it, &v, true); + Assert(r == WJB_END_OBJECT); + pushJsonbValue(st, WJB_END_OBJECT, NULL); + } + else if (r == WJB_BEGIN_ARRAY && unwrap) + { + /* + * Lax mode: a '.key'/'.*' accessor applied to an array auto-unwraps + * it. Rebuild the array, re-applying the *current* step to each + * element. Per the path language this unwrapping is one level deep, + * so we recurse with unwrap=false: a nested array element is then + * handled as a plain value (copied through), not unwrapped again. + * This mirrors jsonb_path_query()'s lax behavior. + */ + uint32 nelems = v.val.array.nElems; + uint32 i; + + pushJsonbValue(st, WJB_BEGIN_ARRAY, NULL); + for (i = 0; i < nelems; i++) + jtSetPath(it, st, steps, nsteps, level, op, newval, + on_existing, strict, false, matched); + r = JsonbIteratorNext(it, &v, true); + Assert(r == WJB_END_ARRAY); + pushJsonbValue(st, WJB_END_ARRAY, NULL); + } + else if (strict) + { + /* + * A '.key'/'.*' accessor requires an object, but here the value is an + * array we are not unwrapping, or a scalar. In strict mode this is a + * structural error, matching the SQL/JSON path engine. + */ + if (steps[level].wildcard) + ereport(ERROR, + errcode(ERRCODE_SQL_JSON_OBJECT_NOT_FOUND), + errmsg("jsonpath wildcard member accessor can only be applied to an object")); + else + ereport(ERROR, + errcode(ERRCODE_SQL_JSON_MEMBER_NOT_FOUND), + errmsg("jsonpath member accessor can only be applied to an object")); + } + else if (r == WJB_BEGIN_ARRAY) + { + /* lax, but not unwrapping (nested array): nothing matches, copy it */ + int walking_level = 1; + + pushJsonbValue(st, WJB_BEGIN_ARRAY, NULL); + while (walking_level != 0) + { + r = JsonbIteratorNext(it, &v, false); + if (r == WJB_BEGIN_ARRAY || r == WJB_BEGIN_OBJECT) + walking_level++; + else if (r == WJB_END_ARRAY || r == WJB_END_OBJECT) + walking_level--; + pushJsonbValue(st, r, r < WJB_BEGIN_ARRAY ? &v : NULL); + } + } + else + { + /* lax scalar: nothing matches, leave as-is */ + pushJsonbValue(st, r, &v); + } +} + +/* + * Runtime handler for EEOP_JSON_TRANSFORM. + * + * By the time we get here, prior steps have populated: + * jtstate->formatted_expr : the input jsonb (non-null; the + * EEOP_JUMP_IF_NULL before us handles null) + * 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) + * + * We convert the jsonpath to a list of accessor steps (member names and '.*' + * wildcards), then make a single streaming pass over the document, rebuilding + * it with the action applied wherever the path matches. Doing our own pass + * (rather than delegating to jsonb_set/insert/delete_path on a text[] path) + * is what lets us honor '.*', which can match many members at once. + * + * 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). + */ +void +ExecEvalJsonTransform(ExprState *state, ExprEvalStep *op, + ExprContext *econtext) +{ + JsonTransformExprState *jtstate = op->d.json_transform.jtstate; + JsonExpr *jsexpr = jtstate->jsexpr; + JsonTransformAction *action = jsexpr->action; + Jsonb *in; + JsonPath *jp; + JsonTransformStep *steps; + int nsteps; + JsonbValue newvalbuf; + JsonbValue *newval = NULL; + JsonbIterator *it; + JsonbInState st = {0}; + JsonTransformOp effop = action->op; + bool matched = false; + bool strict; + + /* + * The JUMP_IF_NULL guards in the step array already skip us if + * formatted_expr or pathspec is NULL. + */ + Assert(!jtstate->formatted_expr.isnull); + Assert(!jtstate->pathspec.isnull); + + in = DatumGetJsonbP(jtstate->formatted_expr.value); + jp = DatumGetJsonPathP(jtstate->pathspec.value); + strict = (jp->header & JSONPATH_LAX) == 0; + + /* Validate path and break it into accessor steps. */ + steps = JsonPathToTransformSteps(jp, action->op, &nsteps); + + /* 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) + { + switch (action->on_null) + { + case JSON_TRANSFORM_BEHAVIOR_ERROR: + ereport(ERROR, + errcode(ERRCODE_NULL_IN_REPLACEMENT_VALUE_OF_JSON_TRANSFORM_NOT_ALLOWED), + errmsg("null in replacement value of JSON_TRANSFORM not allowed")); + break; + case JSON_TRANSFORM_BEHAVIOR_IGNORE: + /* do not perform the action; return input unchanged */ + *op->resvalue = JsonbPGetDatum(in); + *op->resnull = false; + return; + case JSON_TRANSFORM_BEHAVIOR_REMOVE: + /* delete the target instead of setting it (REPLACE only) */ + effop = TRANSFORM_REMOVE; + break; + default: + /* NULL ON NULL: store a JSON null */ + newvalbuf.type = jbvNull; + newval = &newvalbuf; + break; + } + } + else + { + JsonbToJsonbValue(DatumGetJsonbP(jtstate->action_value.value), + &newvalbuf); + newval = &newvalbuf; + } + } + else if (action->op == TRANSFORM_RENAME) + { + /* new key name: a text value, carried to the walker as a jbvString */ + text *newname = DatumGetTextPP(jtstate->action_value.value); + + newvalbuf.type = jbvString; + newvalbuf.val.string.val = VARDATA_ANY(newname); + newvalbuf.val.string.len = VARSIZE_ANY_EXHDR(newname); + newval = &newvalbuf; + } + + /* + * A top-level scalar has no members for a '.key'/'.*' path to target, so + * nothing matches: honor ON MISSING, else return the input unchanged. + */ + if (JB_ROOT_IS_SCALAR(in)) + { + if (action->on_missing == JSON_TRANSFORM_BEHAVIOR_ERROR) + ereport(ERROR, + errcode(ERRCODE_TARGET_IN_JSON_TRANSFORM_DOES_NOT_EXIST), + errmsg("target in JSON_TRANSFORM does not exist")); + *op->resvalue = JsonbPGetDatum(in); + *op->resnull = false; + return; + } + + it = JsonbIteratorInit(&in->root); + jtSetPath(&it, &st, steps, nsteps, 0, effop, newval, + action->on_existing, strict, !strict, &matched); + + /* ON MISSING ERROR: the path matched no existing target. */ + if (!matched && action->on_missing == JSON_TRANSFORM_BEHAVIOR_ERROR) + ereport(ERROR, + errcode(ERRCODE_TARGET_IN_JSON_TRANSFORM_DOES_NOT_EXIST), + errmsg("target in JSON_TRANSFORM does not exist")); + + *op->resvalue = JsonbPGetDatum(JsonbValueToJsonb(st.result)); + *op->resnull = false; +} + /* * Convert the given JsonbValue to its C string representation * diff --git a/src/backend/jit/llvm/llvmjit_expr.c b/src/backend/jit/llvm/llvmjit_expr.c index 2f3742c56f3..4cff3106bed 100644 --- a/src/backend/jit/llvm/llvmjit_expr.c +++ b/src/backend/jit/llvm/llvmjit_expr.c @@ -2360,6 +2360,12 @@ llvm_compile_expr(ExprState *state) break; } + case EEOP_JSON_TRANSFORM: + build_EvalXFunc(b, mod, "ExecEvalJsonTransform", + v_state, op, v_econtext); + LLVMBuildBr(b, opblocks[opno + 1]); + break; + case EEOP_JSONEXPR_COERCION: build_EvalXFunc(b, mod, "ExecEvalJsonCoercion", v_state, op, v_econtext); diff --git a/src/backend/jit/llvm/llvmjit_types.c b/src/backend/jit/llvm/llvmjit_types.c index 5751e3f5720..8b0ff4c8c93 100644 --- a/src/backend/jit/llvm/llvmjit_types.c +++ b/src/backend/jit/llvm/llvmjit_types.c @@ -186,6 +186,7 @@ void *referenced_functions[] = ExecEvalJsonCoercion, ExecEvalJsonCoercionFinish, ExecEvalJsonExprPath, + ExecEvalJsonTransform, MakeExpandedObjectReadOnlyInternal, slot_getmissingattrs, slot_getsomeattrs_int, diff --git a/src/backend/nodes/nodeFuncs.c b/src/backend/nodes/nodeFuncs.c index ab2e6c6a8f5..2df263b8bfa 100644 --- a/src/backend/nodes/nodeFuncs.c +++ b/src/backend/nodes/nodeFuncs.c @@ -2394,6 +2394,13 @@ expression_tree_walker_impl(Node *node, return true; if (WALK(jexpr->on_error)) return true; + if (jexpr->action) + { + if (WALK(jexpr->action->pathspec)) + return true; + if (WALK(jexpr->action->value_expr)) + return true; + } } break; case T_JsonBehavior: @@ -3442,6 +3449,21 @@ expression_tree_mutator_impl(Node *node, /* assume mutator does not care about passing_names */ MUTATE(newnode->on_empty, jexpr->on_empty, JsonBehavior *); MUTATE(newnode->on_error, jexpr->on_error, JsonBehavior *); + if (jexpr->action) + { + /* + * Copy the JsonTransformAction node ourselves and mutate + * its sub-expressions, rather than handing the action + * node itself to the mutator callback, so that the + * original node is never modified. + */ + JsonTransformAction *newact; + + FLATCOPY(newact, jexpr->action, JsonTransformAction); + MUTATE(newact->pathspec, jexpr->action->pathspec, Node *); + MUTATE(newact->value_expr, jexpr->action->value_expr, Node *); + newnode->action = newact; + } return (Node *) newnode; } break; diff --git a/src/backend/optimizer/util/clauses.c b/src/backend/optimizer/util/clauses.c index 4d9ff9ec27a..edc98615b65 100644 --- a/src/backend/optimizer/util/clauses.c +++ b/src/backend/optimizer/util/clauses.c @@ -412,6 +412,25 @@ contain_mutable_functions_checker(Oid func_id, void *context) return (func_volatile(func_id) != PROVOLATILE_IMMUTABLE); } +/* + * Is a JsonExpr's jsonpath (its path_spec, or a JSON_TRANSFORM target path or + * PATH source) mutable? A non-constant path must be treated as mutable. + */ +static bool +json_path_is_mutable(Node *path_spec, JsonExpr *jexpr) +{ + Const *cnst; + + if (!IsA(path_spec, Const)) + return true; + + cnst = castNode(Const, path_spec); + Assert(cnst->consttype == JSONPATHOID); + return !cnst->constisnull && + jspIsMutable(DatumGetJsonPathP(cnst->constvalue), + jexpr->passing_names, jexpr->passing_values); +} + static bool contain_mutable_functions_walker(Node *node, void *context) { @@ -452,17 +471,10 @@ contain_mutable_functions_walker(Node *node, void *context) if (IsA(node, JsonExpr)) { JsonExpr *jexpr = (JsonExpr *) node; - Const *cnst; - - /* If non-constant path_spec, must treat as mutable */ - if (!IsA(jexpr->path_spec, Const)) - return true; - cnst = (Const *) jexpr->path_spec; - Assert(cnst->consttype == JSONPATHOID); - if (!cnst->constisnull && - jspIsMutable(DatumGetJsonPathP(cnst->constvalue), - jexpr->passing_names, jexpr->passing_values)) + /* JSON_TRANSFORM carries its target path in action->pathspec */ + if (json_path_is_mutable(jexpr->action ? jexpr->action->pathspec : + jexpr->path_spec, jexpr)) return true; /* Fall through to check subnodes */ @@ -4555,6 +4567,37 @@ eval_const_expressions_mutator(Node *node, return ece_evaluate_expr((Node *) newcre); return (Node *) newcre; } + case T_JsonExpr: + { + JsonExpr *jexpr; + Const *pathconst; + + /* const-simplify the subexpressions first */ + jexpr = (JsonExpr *) ece_generic_processing(node); + + /* + * A JSON_TRANSFORM target path that was not a constant during + * parse analysis (say, '$[0]'::text) may have just been + * folded into one. Check it against the standard's + * restrictions now, as parse analysis does for a literal + * path. Otherwise CREATE INDEX, which plans an index + * expression only to test its mutability, would accept a path + * that can never be evaluated, and every later insertion + * would fail. + */ + if (jexpr->action && IsA(jexpr->action->pathspec, Const)) + { + pathconst = castNode(Const, jexpr->action->pathspec); + if (!pathconst->constisnull) + { + int nsteps; + + pfree(JsonPathToTransformSteps(DatumGetJsonPathP(pathconst->constvalue), + jexpr->action->op, &nsteps)); + } + } + return (Node *) jexpr; + } default: break; } diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y index 0563453fe24..781e0d7b7be 100644 --- a/src/backend/parser/gram.y +++ b/src/backend/parser/gram.y @@ -673,6 +673,7 @@ static Node *makeRecursiveViewSelect(char *relname, List *aliases, Node *query); json_table_plan_union json_table_plan_cross json_table_plan_primary + json_transform_action %type json_name_and_value_list json_value_expr_list json_array_aggregate_order_by_clause_opt @@ -680,9 +681,14 @@ static Node *makeRecursiveViewSelect(char *relname, List *aliases, Node *query); json_behavior_clause_opt json_passing_clause_opt json_table_column_definition_list + json_transform_behavior_list_opt + json_transform_behavior_list %type json_table_path_name_opt +%type json_transform_behavior %type json_behavior_type json_predicate_type_constraint + json_transform_behavior_value + json_transform_behavior_target json_quotes_clause_opt json_table_default_plan_choices json_table_default_plan_inner_outer @@ -739,7 +745,7 @@ static Node *makeRecursiveViewSelect(char *relname, List *aliases, Node *query); DOUBLE_P DROP EACH ELSE EMPTY_P ENABLE_P ENCODING ENCRYPTED END_P ENFORCED ENUM_P ERROR_P - ESCAPE EVENT EXCEPT EXCLUDE EXCLUDING EXCLUSIVE EXECUTE EXISTS EXPLAIN + ESCAPE EVENT EXCEPT EXCLUDE EXCLUDING EXCLUSIVE EXECUTE EXISTING EXISTS EXPLAIN EXPRESSION EXTENSION EXTERNAL EXTRACT FALSE_P FAMILY FETCH FILTER FINALIZE FIRST_P FLOAT_P FOLLOWING FOR @@ -755,7 +761,7 @@ static Node *makeRecursiveViewSelect(char *relname, List *aliases, Node *query); INTERSECT INTERVAL INTO INVOKER IS ISNULL ISOLATION JOIN JSON JSON_ARRAY JSON_ARRAYAGG JSON_EXISTS JSON_OBJECT JSON_OBJECTAGG - JSON_QUERY JSON_SCALAR JSON_SERIALIZE JSON_TABLE JSON_VALUE + JSON_QUERY JSON_SCALAR JSON_SERIALIZE JSON_TABLE JSON_TRANSFORM JSON_VALUE KEEP KEY KEYS @@ -764,7 +770,7 @@ static Node *makeRecursiveViewSelect(char *relname, List *aliases, Node *query); LOCALTIME LOCALTIMESTAMP LOCATION LOCK_P LOCKED LOGGED LSN_P MAPPING MATCH MATCHED MATERIALIZED MAXVALUE MERGE MERGE_ACTION METHOD - MINUTE_P MINVALUE MODE MONTH_P MOVE + MINUTE_P MINVALUE MISSING MODE MONTH_P MOVE NAME_P NAMES NATIONAL NATURAL NCHAR NESTED NEW NEXT NFC NFD NFKC NFKD NO NONE NORMALIZE NORMALIZED @@ -783,7 +789,7 @@ static Node *makeRecursiveViewSelect(char *relname, List *aliases, Node *query); QUOTE QUOTES RANGE READ REAL REASSIGN RECURSIVE REF_P REFERENCES REFERENCING - REFRESH REINDEX RELATIVE_P RELEASE RENAME REPACK REPEATABLE REPLACE REPLICA + REFRESH REINDEX RELATIVE_P RELEASE REMOVE RENAME REPACK REPEATABLE REPLACE REPLICA RESET RESPECT_P RESTART RESTRICT RETURN RETURNING RETURNS REVOKE RIGHT ROLE ROLLBACK ROLLUP ROUTINE ROUTINES ROW ROWS RULE @@ -901,6 +907,14 @@ 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 +/* + * IGNORE is given a precedence so the shift/reduce conflict between window + * null-treatment (IGNORE NULLS) and a JSON_TRANSFORM behavior clause + * (IGNORE ON ...) resolves in favor of shifting (binding IGNORE to NULLS). + * The empty null_treatment rule below is marked %prec UNBOUNDED (lower) so + * the shift wins by precedence rather than as an unresolved conflict. + */ +%nonassoc IGNORE_P %left Op OPERATOR /* multi-character ops and user-defined operators */ %left '+' '-' %left '*' '/' '%' @@ -16629,6 +16643,19 @@ func_expr_common_subexpr: n->location = @1; $$ = (Node *) n; } + | JSON_TRANSFORM '(' + json_value_expr ',' json_transform_action + json_passing_clause_opt + ')' + { + JsonFuncExpr *n = makeNode(JsonFuncExpr); + n->op = JSON_TRANSFORM_OP; + n->context_item = (JsonValueExpr *) $3; + n->action = (JsonTransformAction *) $5; + n->passing = $6; + n->location = @1; + $$ = (Node *) n; + } ; @@ -16757,7 +16784,7 @@ filter_clause: null_treatment: IGNORE_P NULLS_P { $$ = PARSER_IGNORE_NULLS; } | RESPECT_P NULLS_P { $$ = PARSER_RESPECT_NULLS; } - | /*EMPTY*/ { $$ = NO_NULLTREATMENT; } + | /*EMPTY*/ %prec UNBOUNDED { $$ = NO_NULLTREATMENT; } ; window_clause: @@ -17508,6 +17535,101 @@ json_returning_clause_opt: | /* EMPTY */ { $$ = NULL; } ; +json_transform_action: + /* INSERT path_expr = value_expr */ + INSERT a_expr '=' json_value_expr json_transform_behavior_list_opt + { + JsonTransformAction *n = makeNode(JsonTransformAction); + n->op = TRANSFORM_INSERT; + n->pathspec = $2; + n->value_expr = $4; + n->behaviors = $5; + n->location = @1; + + $$ = (Node *) n; + } + | + RENAME a_expr '=' Sconst json_transform_behavior_list_opt + { + JsonTransformAction *n = makeNode(JsonTransformAction); + n->op = TRANSFORM_RENAME; + n->pathspec = $2; + n->value_expr = makeStringConst($4, @4); + n->behaviors = $5; + n->location = @1; + + $$ = (Node *) n; + } + | + REPLACE a_expr '=' json_value_expr json_transform_behavior_list_opt + { + JsonTransformAction *n = makeNode(JsonTransformAction); + n->op = TRANSFORM_REPLACE; + n->pathspec = $2; + n->value_expr = $4; + n->behaviors = $5; + n->location = @1; + + $$ = (Node *) n; + } + | + REMOVE a_expr json_transform_behavior_list_opt + { + JsonTransformAction *n = makeNode(JsonTransformAction); + n->op = TRANSFORM_REMOVE; + n->pathspec = $2; + n->value_expr = NULL; + n->behaviors = $3; + n->location = @1; + + $$ = (Node *) n; + }; + +/* + * Optional per-action behavior clauses: a sequence of " ON ". + * Each clause becomes a JsonTransformBehaviorClause node; which clauses are + * allowed for which action, and their defaults, are checked in parse analysis + * (resolveJsonTransformBehaviors), not here. + */ +json_transform_behavior_list_opt: + json_transform_behavior_list { $$ = $1; } + | /* EMPTY */ { $$ = NIL; } + ; + +json_transform_behavior_list: + json_transform_behavior + { $$ = list_make1($1); } + | json_transform_behavior_list json_transform_behavior + { $$ = lappend($1, $2); } + ; + +json_transform_behavior: + json_transform_behavior_value ON json_transform_behavior_target + { + JsonTransformBehaviorClause *c = makeNode(JsonTransformBehaviorClause); + + c->behavior = $1; + c->target = $3; + c->location = @1; + $$ = (Node *) c; + } + ; + +json_transform_behavior_value: + ERROR_P { $$ = JSON_TRANSFORM_BEHAVIOR_ERROR; } + | IGNORE_P { $$ = JSON_TRANSFORM_BEHAVIOR_IGNORE; } + | NULL_P { $$ = JSON_TRANSFORM_BEHAVIOR_NULL; } + | REMOVE { $$ = JSON_TRANSFORM_BEHAVIOR_REMOVE; } + ; + +json_transform_behavior_target: + EXISTING { $$ = JSON_TRANSFORM_TARGET_EXISTING; } + | MISSING { $$ = JSON_TRANSFORM_TARGET_MISSING; } + | NULL_P { $$ = JSON_TRANSFORM_TARGET_NULL; } + | EMPTY_P { $$ = JSON_TRANSFORM_TARGET_EMPTY; } + | ERROR_P { $$ = JSON_TRANSFORM_TARGET_ERROR; } + ; + /* * We must assign the only-JSON production a precedence less than IDENT in * order to favor shifting over reduction when JSON is followed by VALUE_P, @@ -18162,6 +18284,7 @@ unreserved_keyword: | EXCLUDING | EXCLUSIVE | EXECUTE + | EXISTING | EXPLAIN | EXPRESSION | EXTENSION @@ -18232,6 +18355,7 @@ unreserved_keyword: | METHOD | MINUTE_P | MINVALUE + | MISSING | MODE | MONTH_P | MOVE @@ -18301,6 +18425,7 @@ unreserved_keyword: | REINDEX | RELATIVE_P | RELEASE + | REMOVE | RENAME | REPACK | REPEATABLE @@ -18446,6 +18571,7 @@ col_name_keyword: | JSON_SCALAR | JSON_SERIALIZE | JSON_TABLE + | JSON_TRANSFORM | JSON_VALUE | LEAST | MERGE_ACTION @@ -18747,6 +18873,7 @@ bare_label_keyword: | EXCLUDING | EXCLUSIVE | EXECUTE + | EXISTING | EXISTS | EXPLAIN | EXPRESSION @@ -18817,6 +18944,7 @@ bare_label_keyword: | JSON_SCALAR | JSON_SERIALIZE | JSON_TABLE + | JSON_TRANSFORM | JSON_VALUE | KEEP | KEY @@ -18851,6 +18979,7 @@ bare_label_keyword: | MERGE_ACTION | METHOD | MINVALUE + | MISSING | MODE | MOVE | NAME_P @@ -18937,6 +19066,7 @@ bare_label_keyword: | REINDEX | RELATIVE_P | RELEASE + | REMOVE | RENAME | REPACK | REPEATABLE diff --git a/src/backend/parser/parse_expr.c b/src/backend/parser/parse_expr.c index a01d6385024..59478ae788e 100644 --- a/src/backend/parser/parse_expr.c +++ b/src/backend/parser/parse_expr.c @@ -36,6 +36,7 @@ #include "utils/builtins.h" #include "utils/date.h" #include "utils/fmgroids.h" +#include "utils/jsonpath.h" #include "utils/lsyscache.h" #include "utils/timestamp.h" #include "utils/typcache.h" @@ -4384,6 +4385,101 @@ transformJsonSerializeExpr(ParseState *pstate, JsonSerializeExpr *expr) NULL, returning, false, false, expr->location); } +/* + * Resolve the raw ON-clause list collected by the grammar into the + * on_existing / on_missing / on_null fields of an analyzed + * JSON_TRANSFORM action, applying the standard's implicit defaults for + * clauses the user omitted and validating the ones they specified. + */ +static void +resolveJsonTransformBehaviors(ParseState *pstate, + JsonTransformAction *raw, + JsonTransformAction *action) +{ + ListCell *lc; + + /* Standard implicit defaults. */ + switch (action->op) + { + case TRANSFORM_INSERT: + action->on_existing = JSON_TRANSFORM_BEHAVIOR_ERROR; + action->on_null = JSON_TRANSFORM_BEHAVIOR_NULL; + break; + case TRANSFORM_REPLACE: + action->on_missing = JSON_TRANSFORM_BEHAVIOR_IGNORE; + action->on_null = JSON_TRANSFORM_BEHAVIOR_NULL; + break; + case TRANSFORM_REMOVE: + case TRANSFORM_RENAME: + action->on_missing = JSON_TRANSFORM_BEHAVIOR_IGNORE; + break; + } + + foreach(lc, raw->behaviors) + { + JsonTransformBehaviorClause *clause = lfirst_node(JsonTransformBehaviorClause, lc); + JsonTransformBehavior behavior = clause->behavior; + + switch (clause->target) + { + case JSON_TRANSFORM_TARGET_EXISTING: + if (action->op != TRANSFORM_INSERT) + ereport(ERROR, + errcode(ERRCODE_SYNTAX_ERROR), + errmsg("ON EXISTING is only valid for JSON_TRANSFORM INSERT"), + parser_errposition(pstate, clause->location)); + if (behavior != JSON_TRANSFORM_BEHAVIOR_ERROR && + behavior != JSON_TRANSFORM_BEHAVIOR_IGNORE) + ereport(ERROR, + errcode(ERRCODE_SYNTAX_ERROR), + errmsg("ON EXISTING behavior must be ERROR or IGNORE"), + parser_errposition(pstate, clause->location)); + action->on_existing = behavior; + break; + + case JSON_TRANSFORM_TARGET_MISSING: + if (action->op == TRANSFORM_INSERT) + ereport(ERROR, + errcode(ERRCODE_SYNTAX_ERROR), + errmsg("ON MISSING is not valid for JSON_TRANSFORM INSERT"), + parser_errposition(pstate, clause->location)); + if (behavior != JSON_TRANSFORM_BEHAVIOR_ERROR && + behavior != JSON_TRANSFORM_BEHAVIOR_IGNORE) + ereport(ERROR, + errcode(ERRCODE_SYNTAX_ERROR), + errmsg("ON MISSING behavior must be ERROR or IGNORE"), + parser_errposition(pstate, clause->location)); + action->on_missing = behavior; + break; + + case JSON_TRANSFORM_TARGET_NULL: + if (action->op != TRANSFORM_INSERT && + action->op != TRANSFORM_REPLACE) + ereport(ERROR, + errcode(ERRCODE_SYNTAX_ERROR), + errmsg("ON NULL is only valid for JSON_TRANSFORM INSERT and REPLACE"), + parser_errposition(pstate, clause->location)); + /* REMOVE-on-null is disallowed for INSERT */ + if (behavior == JSON_TRANSFORM_BEHAVIOR_REMOVE && + action->op == TRANSFORM_INSERT) + ereport(ERROR, + errcode(ERRCODE_SYNTAX_ERROR), + errmsg("REMOVE ON NULL is not allowed for JSON_TRANSFORM INSERT"), + parser_errposition(pstate, clause->location)); + action->on_null = behavior; + break; + + 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)); + break; + } + } +} + /* * Transform JSON_VALUE, JSON_QUERY, JSON_EXISTS, JSON_TABLE functions into * a JsonExpr node. @@ -4398,6 +4494,7 @@ transformJsonFuncExpr(ParseState *pstate, JsonFuncExpr *func) Node *coerced_path_spec; const char *func_name = NULL; JsonFormatType default_format; + JsonTransformAction *jst_action = func->action; switch (func->op) { @@ -4417,6 +4514,10 @@ transformJsonFuncExpr(ParseState *pstate, JsonFuncExpr *func) func_name = "JSON_TABLE"; default_format = JS_FORMAT_JSONB; break; + case JSON_TRANSFORM_OP: + func_name = "JSON_TRANSFORM"; + default_format = JS_FORMAT_JSONB; + break; default: elog(ERROR, "invalid JsonFuncExpr op %d", (int) func->op); default_format = JS_FORMAT_DEFAULT; /* keep compiler quiet */ @@ -4610,22 +4711,103 @@ transformJsonFuncExpr(ParseState *pstate, JsonFuncExpr *func) false); jsexpr->format = func->context_item->format; - path_spec = transformExprRecurse(pstate, func->pathspec); - pathspec_type = exprType(path_spec); - pathspec_loc = exprLocation(path_spec); - coerced_path_spec = coerce_to_target_type(pstate, path_spec, - pathspec_type, - JSONPATHOID, -1, - COERCION_EXPLICIT, - COERCE_IMPLICIT_CAST, - pathspec_loc); - if (coerced_path_spec == NULL) - ereport(ERROR, - (errcode(ERRCODE_DATATYPE_MISMATCH), - errmsg("JSON path expression must be of type %s, not of type %s", - "jsonpath", format_type_be(pathspec_type)), - parser_errposition(pstate, pathspec_loc))); - jsexpr->path_spec = coerced_path_spec; + if (jst_action) + { + JsonTransformAction *analyzed_jst_action = makeNode(JsonTransformAction); + + analyzed_jst_action->op = jst_action->op; + analyzed_jst_action->location = jst_action->location; + + switch (jst_action->op) + { + case TRANSFORM_INSERT: + case TRANSFORM_REPLACE: + analyzed_jst_action->value_expr = transformJsonValueExpr(pstate, func_name, + (JsonValueExpr *) jst_action->value_expr, + default_format, + JSONBOID, + false); + break; + case TRANSFORM_RENAME: + + /* + * The new key name is a (SQL:2023 + * 6.44); the grammar accepts nothing else, so this coercion + * of an unknown-type literal to text cannot fail. + */ + analyzed_jst_action->value_expr = + coerce_to_specific_type(pstate, + transformExprRecurse(pstate, jst_action->value_expr), + TEXTOID, "JSON_TRANSFORM"); + break; + case TRANSFORM_REMOVE: + /* REMOVE has no value_expr */ + analyzed_jst_action->value_expr = NULL; + break; + } + + path_spec = transformExprRecurse(pstate, jst_action->pathspec); + pathspec_type = exprType(path_spec); + pathspec_loc = exprLocation(path_spec); + coerced_path_spec = coerce_to_target_type(pstate, path_spec, + pathspec_type, + JSONPATHOID, -1, + COERCION_EXPLICIT, + COERCE_IMPLICIT_CAST, + pathspec_loc); + if (coerced_path_spec == NULL) + ereport(ERROR, + (errcode(ERRCODE_DATATYPE_MISMATCH), + errmsg("JSON path expression must be of type %s, not of type %s", + "jsonpath", format_type_be(pathspec_type)), + parser_errposition(pstate, pathspec_loc))); + analyzed_jst_action->pathspec = coerced_path_spec; + + /* + * Check a constant target path against the standard's restrictions + * now, so that an invalid one is rejected when the statement is + * analyzed. Leaving it to the executor would let CREATE INDEX, + * CREATE VIEW, or a generated column accept, on an empty table, a + * path that can never be evaluated. A non-constant path (say, a + * column) can only be checked by the executor. + */ + if (IsA(coerced_path_spec, Const) && + !castNode(Const, coerced_path_spec)->constisnull) + { + Const *pathconst = castNode(Const, coerced_path_spec); + ParseCallbackState pcbstate; + int nsteps; + + setup_parser_errposition_callback(&pcbstate, pstate, pathspec_loc); + pfree(JsonPathToTransformSteps(DatumGetJsonPathP(pathconst->constvalue), + jst_action->op, &nsteps)); + cancel_parser_errposition_callback(&pcbstate); + } + + /* Resolve ON EXISTING / ON MISSING / ON NULL clauses + defaults. */ + resolveJsonTransformBehaviors(pstate, jst_action, analyzed_jst_action); + + jsexpr->action = analyzed_jst_action; + } + else + { + path_spec = transformExprRecurse(pstate, func->pathspec); + pathspec_type = exprType(path_spec); + pathspec_loc = exprLocation(path_spec); + coerced_path_spec = coerce_to_target_type(pstate, path_spec, + pathspec_type, + JSONPATHOID, -1, + COERCION_EXPLICIT, + COERCE_IMPLICIT_CAST, + pathspec_loc); + if (coerced_path_spec == NULL) + ereport(ERROR, + (errcode(ERRCODE_DATATYPE_MISMATCH), + errmsg("JSON path expression must be of type %s, not of type %s", + "jsonpath", format_type_be(pathspec_type)), + parser_errposition(pstate, pathspec_loc))); + jsexpr->path_spec = coerced_path_spec; + } /* Transform and coerce the PASSING arguments to jsonb. */ transformJsonPassingArgs(pstate, func_name, @@ -4767,6 +4949,16 @@ transformJsonFuncExpr(ParseState *pstate, JsonFuncExpr *func) jsexpr->returning); break; + case JSON_TRANSFORM_OP: + /* Return type is always jsonb */ + if (!OidIsValid(jsexpr->returning->typid)) + { + jsexpr->returning->typid = JSONBOID; + jsexpr->returning->typmod = -1; + } + jsexpr->collation = get_typcollation(jsexpr->returning->typid); + /* No top-level ON EMPTY / ON ERROR for JSON_TRANSFORM */ + break; default: elog(ERROR, "invalid JsonFuncExpr op %d", (int) func->op); break; diff --git a/src/backend/parser/parse_target.c b/src/backend/parser/parse_target.c index 728936b502e..e52e2735749 100644 --- a/src/backend/parser/parse_target.c +++ b/src/backend/parser/parse_target.c @@ -2013,6 +2013,9 @@ FigureColnameInternal(Node *node, char **name) case JSON_VALUE_OP: *name = "json_value"; return 2; + case JSON_TRANSFORM_OP: + *name = "json_transform"; + return 2; /* JSON_TABLE_OP can't happen here. */ default: elog(ERROR, "unrecognized JsonExpr op: %d", diff --git a/src/backend/utils/adt/jsonpath.c b/src/backend/utils/adt/jsonpath.c index 7bfc18c9888..26676039ae1 100644 --- a/src/backend/utils/adt/jsonpath.c +++ b/src/backend/utils/adt/jsonpath.c @@ -1636,3 +1636,92 @@ jspIsMutableWalker(JsonPathItem *jpi, struct JsonPathMutableContext *cxt) return status; } + +/* + * Convert a JSON_TRANSFORM jsonpath into an array of JsonTransformStep. + * + * Per standard, the path must begin with the context variable '$' and + * may only contain member accessors (.key, jpiKey) and wildcard member + * accessors (.*, jpiAnyKey). Array subscripts, filters, methods, recursive + * descent, and named variables are all rejected. Additionally, for INSERT + * and RENAME the *last* accessor must be a named member, not a wildcard. + * + * Parse analysis calls this on a constant target path, so that an invalid + * path is rejected when the statement (or a view, index, or generated + * column) is defined, not when a row is first processed. The executor + * calls it again on every evaluation, since a target path may also be a + * non-constant expression. + * + * The returned key pointers point into the (detoasted) jsonpath value, which + * outlives this evaluation, so we don't copy the strings. + */ +JsonTransformStep * +JsonPathToTransformSteps(JsonPath *jp, JsonTransformOp op, int *nsteps) +{ + JsonPathItem v; + JsonTransformStep *steps; + int nalloc = 8; + int n = 0; + + steps = palloc(nalloc * sizeof(JsonTransformStep)); + + jspInit(&v, jp); + + /* Per standard, the path must begin with '$'. */ + if (v.type != jpiRoot) + ereport(ERROR, + errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("JSON_TRANSFORM target path must start with the context variable $")); + + while (jspHasNext(&v)) + { + JsonPathItem next; + + jspGetNext(&v, &next); + v = next; + + if (n >= nalloc) + { + nalloc *= 2; + steps = repalloc(steps, nalloc * sizeof(JsonTransformStep)); + } + + if (v.type == jpiKey) + { + int32 len; + + steps[n].wildcard = false; + steps[n].key = jspGetString(&v, &len); + steps[n].keylen = len; + } + else if (v.type == jpiAnyKey) + { + steps[n].wildcard = true; + steps[n].key = NULL; + steps[n].keylen = 0; + } + else + ereport(ERROR, + errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("JSON_TRANSFORM target path may only contain member accessors (.key) and wildcard member accessors (.*)"), + errdetail("Array subscripts, filters, methods, and recursive descent are not allowed.")); + + n++; + } + + if (n == 0) + ereport(ERROR, + errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("JSON_TRANSFORM target path must name at least one member")); + + /* INSERT/RENAME: the last accessor must name a member, not a wildcard. */ + if ((op == TRANSFORM_INSERT || op == TRANSFORM_RENAME) && + steps[n - 1].wildcard) + ereport(ERROR, + errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("the last accessor of a JSON_TRANSFORM %s target path may not be a wildcard", + op == TRANSFORM_INSERT ? "INSERT" : "RENAME")); + + *nsteps = n; + return steps; +} diff --git a/src/backend/utils/adt/ruleutils.c b/src/backend/utils/adt/ruleutils.c index b2d5327cc20..f4fa9ae78a5 100644 --- a/src/backend/utils/adt/ruleutils.c +++ b/src/backend/utils/adt/ruleutils.c @@ -540,6 +540,10 @@ static char *generate_qualified_type_name(Oid typid); static text *string_to_text(char *str); static char *flatten_reloptions(Oid relid); void get_reloptions(StringInfo buf, Datum reloptions); +static void get_json_transform_behavior(StringInfo buf, + JsonTransformBehavior behavior, + JsonTransformBehavior default_behavior, + const char *label); static void get_json_path_spec(Node *path_spec, deparse_context *context, bool showimplicit); static void get_json_table_columns(TableFunc *tf, JsonTablePathScan *scan, @@ -10644,6 +10648,9 @@ get_rule_expr(Node *node, deparse_context *context, case JSON_VALUE_OP: appendStringInfoString(buf, "JSON_VALUE("); break; + case JSON_TRANSFORM_OP: + appendStringInfoString(buf, "JSON_TRANSFORM("); + break; default: elog(ERROR, "unrecognized JsonExpr op: %d", (int) jexpr->op); @@ -10653,7 +10660,73 @@ get_rule_expr(Node *node, deparse_context *context, appendStringInfoString(buf, ", "); - get_json_path_spec(jexpr->path_spec, context, showimplicit); + if (jexpr->action) + { + switch (jexpr->action->op) + { + case TRANSFORM_INSERT: + appendStringInfoString(buf, "INSERT "); + break; + case TRANSFORM_REMOVE: + appendStringInfoString(buf, "REMOVE "); + break; + case TRANSFORM_RENAME: + appendStringInfoString(buf, "RENAME "); + break; + case TRANSFORM_REPLACE: + appendStringInfoString(buf, "REPLACE "); + break; + default: + elog(ERROR, "unrecognized JsonTransform op: %d", + (int) jexpr->action->op); + } + + get_json_path_spec(jexpr->action->pathspec, context, showimplicit); + if (jexpr->action->op == TRANSFORM_RENAME) + { + /* + * The grammar takes only a bare string literal here, + * so print the text Const without the ::text + * decoration. + */ + Const *newname = castNode(Const, jexpr->action->value_expr); + + appendStringInfoString(buf, " = "); + simple_quote_literal(buf, + TextDatumGetCString(newname->constvalue)); + } + 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)) + get_rule_expr(jexpr->action->value_expr, context, + showimplicit); + else + { + appendStringInfoChar(buf, '('); + get_rule_expr(jexpr->action->value_expr, context, + showimplicit); + appendStringInfoChar(buf, ')'); + } + } + + get_json_transform_behavior(buf, jexpr->action->on_existing, + JSON_TRANSFORM_BEHAVIOR_ERROR, + "EXISTING"); + get_json_transform_behavior(buf, jexpr->action->on_missing, + JSON_TRANSFORM_BEHAVIOR_IGNORE, + "MISSING"); + get_json_transform_behavior(buf, jexpr->action->on_null, + JSON_TRANSFORM_BEHAVIOR_NULL, + "NULL"); + } + else + get_json_path_spec(jexpr->path_spec, context, showimplicit); if (jexpr->passing_values) { @@ -10676,15 +10749,18 @@ get_rule_expr(Node *node, deparse_context *context, } } - if (jexpr->op != JSON_EXISTS_OP || - jexpr->returning->typid != BOOLOID) + /* JSON_TRANSFORM has no RETURNING or ON EMPTY/ERROR clauses */ + if (jexpr->op != JSON_TRANSFORM_OP && + (jexpr->op != JSON_EXISTS_OP || + jexpr->returning->typid != BOOLOID)) get_json_returning(jexpr->returning, context->buf, jexpr->op == JSON_QUERY_OP); - get_json_expr_options(jexpr, context, - jexpr->op != JSON_EXISTS_OP ? - JSON_BEHAVIOR_NULL : - JSON_BEHAVIOR_FALSE); + if (jexpr->op != JSON_TRANSFORM_OP) + get_json_expr_options(jexpr, context, + jexpr->op != JSON_EXISTS_OP ? + JSON_BEHAVIOR_NULL : + JSON_BEHAVIOR_FALSE); appendStringInfoChar(buf, ')'); } @@ -11772,6 +11848,51 @@ get_json_path_spec(Node *path_spec, deparse_context *context, bool showimplicit) get_rule_expr(path_spec, context, showimplicit); } +/* + * get_json_transform_behavior - deparse one JSON_TRANSFORM ON clause + * + * Emits " ON