Age Owner Branch data TLA Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * parse_jsontable.c
4 : : * parsing of JSON_TABLE
5 : : *
6 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
7 : : * Portions Copyright (c) 1994, Regents of the University of California
8 : : *
9 : : *
10 : : * IDENTIFICATION
11 : : * src/backend/parser/parse_jsontable.c
12 : : *
13 : : *-------------------------------------------------------------------------
14 : : */
15 : :
16 : : #include "postgres.h"
17 : :
18 : : #include "catalog/pg_type.h"
19 : : #include "nodes/makefuncs.h"
20 : : #include "nodes/nodeFuncs.h"
21 : : #include "optimizer/optimizer.h"
22 : : #include "parser/parse_clause.h"
23 : : #include "parser/parse_collate.h"
24 : : #include "parser/parse_expr.h"
25 : : #include "parser/parse_relation.h"
26 : : #include "parser/parse_type.h"
27 : : #include "utils/fmgrprotos.h"
28 : : #include "utils/json.h"
29 : : #include "utils/lsyscache.h"
30 : :
31 : : /* Context for transformJsonTableColumns() */
32 : : typedef struct JsonTableParseContext
33 : : {
34 : : ParseState *pstate;
35 : : JsonTable *jt;
36 : : TableFunc *tf;
37 : : List *pathNames; /* list of all path and columns names */
38 : : int pathNameId; /* path name id counter */
39 : : } JsonTableParseContext;
40 : :
41 : : static JsonTablePlan *transformJsonTableColumns(JsonTableParseContext *cxt,
42 : : JsonTablePlanSpec *planspec,
43 : : List *columns,
44 : : List *passingArgs,
45 : : JsonTablePathSpec *pathspec);
46 : : static JsonTablePlan *transformJsonTableNestedColumns(JsonTableParseContext *cxt,
47 : : JsonTablePlanSpec *plan,
48 : : List *passingArgs,
49 : : List *columns);
50 : : static JsonFuncExpr *transformJsonTableColumn(JsonTableColumn *jtc,
51 : : Node *contextItemExpr,
52 : : List *passingArgs,
53 : : bool errorOnError);
54 : : static bool isCompositeType(Oid typid);
55 : : static JsonTablePlan *makeJsonTablePathScan(JsonTableParseContext *cxt,
56 : : JsonTablePathSpec *pathspec,
57 : : JsonTablePlanSpec *planspec,
58 : : bool errorOnError,
59 : : int colMin, int colMax,
60 : : JsonTablePlan *childplan);
61 : : static void CheckDuplicateColumnOrPathNames(JsonTableParseContext *cxt,
62 : : List *columns);
63 : : static bool LookupPathOrColumnName(JsonTableParseContext *cxt, char *name);
64 : : static char *generateJsonTablePathName(JsonTableParseContext *cxt);
65 : : static void validateJsonTableChildPlan(JsonTableParseContext *cxt,
66 : : JsonTablePlanSpec *plan,
67 : : List *columns);
68 : : static JsonTablePlan *makeJsonTableSiblingJoin(bool cross,
69 : : JsonTablePlan *lplan,
70 : : JsonTablePlan *rplan);
71 : : static void
72 : : appendJsonTableColumns(JsonTableParseContext *cxt, List *columns,
73 : : List *passingArgs, bool errorOnError);
74 : :
75 : : /*
76 : : * transformJsonTable -
77 : : * Transform a raw JsonTable into TableFunc
78 : : *
79 : : * Mainly, this transforms the JSON_TABLE() document-generating expression
80 : : * (jt->context_item) and the column-generating expressions (jt->columns) to
81 : : * populate TableFunc.docexpr and TableFunc.colvalexprs, respectively. Also,
82 : : * the PASSING values (jt->passing) are transformed and added into
83 : : * TableFunc.passingvalexprs.
84 : : */
85 : : ParseNamespaceItem *
899 amitlan@postgresql.o 86 :CBC 490 : transformJsonTable(ParseState *pstate, JsonTable *jt)
87 : : {
88 : : TableFunc *tf;
89 : : JsonFuncExpr *jfe;
90 : : JsonExpr *je;
73 akorotkov@postgresql 91 :GNC 490 : JsonTablePlanSpec *plan = jt->planspec;
899 amitlan@postgresql.o 92 :CBC 490 : JsonTablePathSpec *rootPathSpec = jt->pathspec;
93 : : bool is_lateral;
94 : 490 : JsonTableParseContext cxt = {pstate};
95 : :
96 [ + - - + ]: 490 : Assert(IsA(rootPathSpec->string, A_Const) &&
97 : : castNode(A_Const, rootPathSpec->string)->val.node.type == T_String);
98 : :
99 [ + + ]: 490 : if (jt->on_error &&
100 [ + + ]: 64 : jt->on_error->btype != JSON_BEHAVIOR_ERROR &&
101 [ + - ]: 24 : jt->on_error->btype != JSON_BEHAVIOR_EMPTY &&
102 [ + + ]: 24 : jt->on_error->btype != JSON_BEHAVIOR_EMPTY_ARRAY)
103 [ + - ]: 12 : ereport(ERROR,
104 : : errcode(ERRCODE_SYNTAX_ERROR),
105 : : errmsg("invalid %s behavior", "ON ERROR"),
106 : : errdetail("Only EMPTY [ ARRAY ] or ERROR is allowed in the top-level ON ERROR clause."),
107 : : parser_errposition(pstate, jt->on_error->location));
108 : :
109 : 478 : cxt.pathNameId = 0;
110 : :
111 : : /*
112 : : * Collect the user-supplied path and column names, checking that they are
113 : : * distinct. If the row pattern path has an explicit name, it shares this
114 : : * namespace, so seed the list with it.
115 : : */
67 akorotkov@postgresql 116 [ + + ]:GNC 478 : if (rootPathSpec->name != NULL)
117 : 142 : cxt.pathNames = list_make1(rootPathSpec->name);
118 : 478 : CheckDuplicateColumnOrPathNames(&cxt, jt->columns);
119 : :
120 : : /*
121 : : * Generate a name for the row pattern path if it was not given one. Path
122 : : * names are optional for every path, including when a PLAN clause is
123 : : * present; a specific PLAN() can only reference named paths, so an
124 : : * unnamed path that the plan must mention is caught later as a path name
125 : : * mismatch or a path not covered by the plan. We generate the name only
126 : : * after collecting the user-supplied names above, so that it cannot
127 : : * collide with any of them.
128 : : */
899 amitlan@postgresql.o 129 [ + + ]:CBC 458 : if (rootPathSpec->name == NULL)
130 : 324 : rootPathSpec->name = generateJsonTablePathName(&cxt);
131 : :
132 : : /*
133 : : * We make lateral_only names of this level visible, whether or not the
134 : : * RangeTableFunc is explicitly marked LATERAL. This is needed for SQL
135 : : * spec compliance and seems useful on convenience grounds for all
136 : : * functions in FROM.
137 : : *
138 : : * (LATERAL can't nest within a single pstate level, so we don't need
139 : : * save/restore logic here.)
140 : : */
141 [ - + ]: 458 : Assert(!pstate->p_lateral_active);
142 : 458 : pstate->p_lateral_active = true;
143 : :
144 : 458 : tf = makeNode(TableFunc);
145 : 458 : tf->functype = TFT_JSON_TABLE;
146 : :
147 : : /*
148 : : * Transform JsonFuncExpr representing the top JSON_TABLE context_item and
149 : : * pathspec into a dummy JSON_TABLE_OP JsonExpr.
150 : : */
151 : 458 : jfe = makeNode(JsonFuncExpr);
152 : 458 : jfe->op = JSON_TABLE_OP;
153 : 458 : jfe->context_item = jt->context_item;
154 : 458 : jfe->pathspec = (Node *) rootPathSpec->string;
155 : 458 : jfe->passing = jt->passing;
156 : 458 : jfe->on_empty = NULL;
157 : 458 : jfe->on_error = jt->on_error;
158 : 458 : jfe->location = jt->location;
159 : 458 : tf->docexpr = transformExpr(pstate, (Node *) jfe, EXPR_KIND_FROM_FUNCTION);
160 : :
161 : : /*
162 : : * Create a JsonTablePlan that will generate row pattern that becomes
163 : : * source data for JSON path expressions in jt->columns. This also adds
164 : : * the columns' transformed JsonExpr nodes into tf->colvalexprs.
165 : : */
166 : 458 : cxt.jt = jt;
167 : 458 : cxt.tf = tf;
73 akorotkov@postgresql 168 :GNC 458 : tf->plan = (Node *) transformJsonTableColumns(&cxt, plan, jt->columns,
169 : : jt->passing,
170 : : rootPathSpec);
171 : :
172 : : /*
173 : : * Copy the transformed PASSING arguments into the TableFunc node, because
174 : : * they are evaluated separately from the JsonExpr that we just put in
175 : : * TableFunc.docexpr. JsonExpr.passing_values is still kept around for
176 : : * get_json_table().
177 : : */
899 amitlan@postgresql.o 178 :CBC 390 : je = (JsonExpr *) tf->docexpr;
179 : 390 : tf->passingvalexprs = copyObject(je->passing_values);
180 : :
181 : 390 : tf->ordinalitycol = -1; /* undefine ordinality column number */
182 : 390 : tf->location = jt->location;
183 : :
184 : 390 : pstate->p_lateral_active = false;
185 : :
186 : : /*
187 : : * Mark the RTE as LATERAL if the user said LATERAL explicitly, or if
188 : : * there are any lateral cross-references in it.
189 : : */
190 [ + - + + ]: 390 : is_lateral = jt->lateral || contain_vars_of_level((Node *) tf, 0);
191 : :
192 : 390 : return addRangeTableEntryForTableFunc(pstate,
193 : : tf, jt->alias, is_lateral, true);
194 : : }
195 : :
196 : : /*
197 : : * Check if a column / path name is duplicated in the given shared list of
198 : : * names.
199 : : */
200 : : static void
201 : 1008 : CheckDuplicateColumnOrPathNames(JsonTableParseContext *cxt,
202 : : List *columns)
203 : : {
204 : : ListCell *lc1;
205 : :
206 [ + - + + : 2680 : foreach(lc1, columns)
+ + ]
207 : : {
208 : 1696 : JsonTableColumn *jtc = castNode(JsonTableColumn, lfirst(lc1));
209 : :
895 210 [ + + ]: 1696 : if (jtc->coltype == JTC_NESTED)
211 : : {
212 [ + + ]: 542 : if (jtc->pathspec->name)
213 : : {
214 [ + + ]: 434 : if (LookupPathOrColumnName(cxt, jtc->pathspec->name))
215 [ + - ]: 12 : ereport(ERROR,
216 : : errcode(ERRCODE_DUPLICATE_ALIAS),
217 : : errmsg("duplicate JSON_TABLE column or path name: %s",
218 : : jtc->pathspec->name),
219 : : parser_errposition(cxt->pstate,
220 : : jtc->pathspec->name_location));
221 : 422 : cxt->pathNames = lappend(cxt->pathNames, jtc->pathspec->name);
222 : : }
223 : :
224 : 530 : CheckDuplicateColumnOrPathNames(cxt, jtc->columns);
225 : : }
226 : : else
227 : : {
228 [ + + ]: 1154 : if (LookupPathOrColumnName(cxt, jtc->name))
229 [ + - ]: 8 : ereport(ERROR,
230 : : errcode(ERRCODE_DUPLICATE_ALIAS),
231 : : errmsg("duplicate JSON_TABLE column or path name: %s",
232 : : jtc->name),
233 : : parser_errposition(cxt->pstate, jtc->location));
234 : 1146 : cxt->pathNames = lappend(cxt->pathNames, jtc->name);
235 : : }
236 : : }
899 237 : 984 : }
238 : :
239 : : /*
240 : : * Lookup a column/path name in the given name list, returning true if already
241 : : * there.
242 : : */
243 : : static bool
244 : 2024 : LookupPathOrColumnName(JsonTableParseContext *cxt, char *name)
245 : : {
246 : : ListCell *lc;
247 : :
248 [ + + + + : 10183 : foreach(lc, cxt->pathNames)
+ + ]
249 : : {
250 [ + + ]: 8187 : if (strcmp(name, (const char *) lfirst(lc)) == 0)
251 : 28 : return true;
252 : : }
253 : :
254 : 1996 : return false;
255 : : }
256 : :
257 : : /* Generate a new unique JSON_TABLE path name. */
258 : : static char *
259 : 428 : generateJsonTablePathName(JsonTableParseContext *cxt)
260 : : {
261 : : char namebuf[32];
262 : : char *name;
263 : :
264 : : /*
265 : : * Bump the counter until we produce a name that is not already used as a
266 : : * path or column name. Otherwise a generated name could coincide with a
267 : : * user-supplied one, which would confuse PLAN clause matching and could
268 : : * silently drop a column.
269 : : */
270 : : do
271 : : {
67 akorotkov@postgresql 272 :GNC 436 : snprintf(namebuf, sizeof(namebuf), "json_table_path_%d",
273 : 436 : cxt->pathNameId++);
274 [ + + ]: 436 : } while (LookupPathOrColumnName(cxt, namebuf));
275 : :
276 : 428 : name = pstrdup(namebuf);
899 amitlan@postgresql.o 277 :CBC 428 : cxt->pathNames = lappend(cxt->pathNames, name);
278 : :
279 : 428 : return name;
280 : : }
281 : :
282 : : /*
283 : : * Create a JsonTablePlan that will supply the source row for 'columns'
284 : : * using 'pathspec' and append the columns' transformed JsonExpr nodes and
285 : : * their type/collation information to cxt->tf.
286 : : */
287 : : static JsonTablePlan *
73 akorotkov@postgresql 288 :GNC 792 : transformJsonTableColumns(JsonTableParseContext *cxt,
289 : : JsonTablePlanSpec *planspec,
290 : : List *columns,
291 : : List *passingArgs,
292 : : JsonTablePathSpec *pathspec)
293 : : {
899 amitlan@postgresql.o 294 :CBC 792 : JsonTable *jt = cxt->jt;
295 : 792 : TableFunc *tf = cxt->tf;
296 : : JsonTablePathScan *scan;
297 : : JsonTablePlanSpec *childPlanSpec;
73 akorotkov@postgresql 298 [ + + ]:GNC 1064 : bool defaultPlan = planspec == NULL ||
299 [ + + ]: 272 : planspec->plan_type == JSTP_DEFAULT;
899 amitlan@postgresql.o 300 [ + + ]:CBC 844 : bool errorOnError = jt->on_error &&
301 [ + + ]: 52 : jt->on_error->btype == JSON_BEHAVIOR_ERROR;
302 : : int colMin,
303 : : colMax;
73 akorotkov@postgresql 304 :GNC 792 : JsonTablePlan *childplan = NULL;
305 : :
306 : : /* Start of column range */
895 amitlan@postgresql.o 307 :CBC 792 : colMin = list_length(tf->colvalexprs);
308 : :
73 akorotkov@postgresql 309 [ + + ]:GNC 792 : if (defaultPlan)
310 : 580 : childPlanSpec = planspec;
311 : : else
312 : : {
313 : : /* validate parent and child plans */
314 : : JsonTablePlanSpec *parentPlanSpec;
315 : :
316 [ + + ]: 212 : if (planspec->plan_type == JSTP_JOINED)
317 : : {
318 [ + + ]: 108 : if (planspec->join_type != JSTP_JOIN_INNER &&
319 [ + + ]: 76 : planspec->join_type != JSTP_JOIN_OUTER)
320 [ + - ]: 8 : ereport(ERROR,
321 : : (errcode(ERRCODE_SYNTAX_ERROR),
322 : : errmsg("invalid JSON_TABLE plan clause"),
323 : : errdetail("Expected INNER or OUTER."),
324 : : parser_errposition(cxt->pstate, planspec->location)));
325 : :
326 : 100 : parentPlanSpec = planspec->plan1;
327 : 100 : childPlanSpec = planspec->plan2;
328 : :
329 [ - + ]: 100 : Assert(parentPlanSpec->plan_type != JSTP_JOINED);
330 [ - + ]: 100 : Assert(parentPlanSpec->pathname);
331 : : }
332 : : else
333 : : {
334 : 104 : parentPlanSpec = planspec;
335 : 104 : childPlanSpec = NULL;
336 : : }
337 : :
338 [ + + ]: 204 : if (strcmp(parentPlanSpec->pathname, pathspec->name) != 0)
339 [ + - ]: 4 : ereport(ERROR,
340 : : (errcode(ERRCODE_SYNTAX_ERROR),
341 : : errmsg("invalid JSON_TABLE plan"),
342 : : errdetail("PATH name mismatch: expected %s but %s is given.",
343 : : pathspec->name, parentPlanSpec->pathname),
344 : : parser_errposition(cxt->pstate, planspec->location)));
345 : :
346 : 200 : validateJsonTableChildPlan(cxt, childPlanSpec, columns);
347 : : }
348 : :
1 349 : 744 : appendJsonTableColumns(cxt, columns, passingArgs, errorOnError);
350 : :
351 : : /* End of column range. */
73 352 [ + + ]: 724 : if (list_length(tf->colvalexprs) == colMin)
353 : : {
354 : : /* No columns in this Scan beside the nested ones. */
355 : 110 : colMax = colMin = -1;
356 : : }
357 : : else
358 : 614 : colMax = list_length(tf->colvalexprs) - 1;
359 : :
360 [ + + + + ]: 724 : if (childPlanSpec || defaultPlan)
361 : : {
362 : : /* transform recursively nested columns */
363 : 640 : childplan = transformJsonTableNestedColumns(cxt, childPlanSpec,
364 : : columns, passingArgs);
365 : : }
366 : :
367 : : /* transform only non-nested columns */
368 : 712 : scan = (JsonTablePathScan *) makeJsonTablePathScan(cxt, pathspec,
369 : : planspec,
370 : : errorOnError,
371 : : colMin,
372 : : colMax,
373 : : childplan);
374 : :
375 : 712 : return (JsonTablePlan *) scan;
376 : : }
377 : :
378 : : /* Append transformed non-nested JSON_TABLE columns to the TableFunc node */
379 : : static void
1 380 : 744 : appendJsonTableColumns(JsonTableParseContext *cxt, List *columns,
381 : : List *passingArgs, bool errorOnError)
382 : : {
383 : : ListCell *col;
73 384 : 744 : ParseState *pstate = cxt->pstate;
385 : 744 : TableFunc *tf = cxt->tf;
386 : 744 : bool ordinality_found = false;
387 : 744 : Oid contextItemTypid = exprType(tf->docexpr);
388 : :
899 amitlan@postgresql.o 389 [ + - + + :CBC 2068 : foreach(col, columns)
+ + ]
390 : : {
391 : 1344 : JsonTableColumn *rawc = castNode(JsonTableColumn, lfirst(col));
392 : : Oid typid;
393 : : int32 typmod;
394 : 1344 : Oid typcoll = InvalidOid;
395 : : Node *colexpr;
396 : :
73 akorotkov@postgresql 397 [ + + ]:GNC 1344 : if (rawc->name)
895 amitlan@postgresql.o 398 :CBC 1002 : tf->colnames = lappend(tf->colnames,
399 : 1002 : makeString(pstrdup(rawc->name)));
400 : :
401 : : /*
402 : : * Determine the type and typmod for the new column. FOR ORDINALITY
403 : : * columns are INTEGER by standard; the others are user-specified.
404 : : */
899 405 [ + + + + : 1344 : switch (rawc->coltype)
- ]
406 : : {
407 : 100 : case JTC_FOR_ORDINALITY:
408 [ + + ]: 100 : if (ordinality_found)
409 [ + - ]: 4 : ereport(ERROR,
410 : : (errcode(ERRCODE_SYNTAX_ERROR),
411 : : errmsg("only one FOR ORDINALITY column is allowed"),
412 : : parser_errposition(pstate, rawc->location)));
413 : 96 : ordinality_found = true;
414 : 96 : colexpr = NULL;
415 : 96 : typid = INT4OID;
416 : 96 : typmod = -1;
417 : 96 : break;
418 : :
419 : 702 : case JTC_REGULAR:
420 : 702 : typenameTypeIdAndMod(pstate, rawc->typeName, &typid, &typmod);
421 : :
422 : : /*
423 : : * Use JTC_FORMATTED so as to use JSON_QUERY for this column
424 : : * if the specified type is one that's better handled using
425 : : * JSON_QUERY() or if non-default WRAPPER or QUOTES behavior
426 : : * is specified.
427 : : */
428 [ + + ]: 702 : if (isCompositeType(typid) ||
429 [ + + ]: 570 : rawc->quotes != JS_QUOTES_UNSPEC ||
430 [ - + ]: 542 : rawc->wrapper != JSW_UNSPEC)
431 : 160 : rawc->coltype = JTC_FORMATTED;
432 : :
433 : : pg_fallthrough;
434 : : case JTC_FORMATTED:
435 : : case JTC_EXISTS:
436 : : {
437 : : JsonFuncExpr *jfe;
438 : 902 : CaseTestExpr *param = makeNode(CaseTestExpr);
439 : :
440 : 902 : param->collation = InvalidOid;
441 : 902 : param->typeId = contextItemTypid;
442 : 902 : param->typeMod = -1;
443 : :
444 : 902 : jfe = transformJsonTableColumn(rawc, (Node *) param,
445 : : passingArgs, errorOnError);
446 : :
447 : 902 : colexpr = transformExpr(pstate, (Node *) jfe,
448 : : EXPR_KIND_FROM_FUNCTION);
449 : 886 : assign_expr_collations(pstate, colexpr);
450 : :
451 : 886 : typid = exprType(colexpr);
452 : 886 : typmod = exprTypmod(colexpr);
453 : 886 : typcoll = exprCollation(colexpr);
454 : 886 : break;
455 : : }
456 : :
895 457 : 342 : case JTC_NESTED:
458 : 342 : continue;
459 : :
899 amitlan@postgresql.o 460 :UBC 0 : default:
461 [ # # ]: 0 : elog(ERROR, "unknown JSON_TABLE column type: %d", (int) rawc->coltype);
462 : : break;
463 : : }
464 : :
899 amitlan@postgresql.o 465 :CBC 982 : tf->coltypes = lappend_oid(tf->coltypes, typid);
466 : 982 : tf->coltypmods = lappend_int(tf->coltypmods, typmod);
467 : 982 : tf->colcollations = lappend_oid(tf->colcollations, typcoll);
468 : 982 : tf->colvalexprs = lappend(tf->colvalexprs, colexpr);
469 : : }
899 amitlan@postgresql.o 470 :GIC 724 : }
471 : :
472 : : /*
473 : : * Check if the type is "composite" for the purpose of checking whether to use
474 : : * JSON_VALUE() or JSON_QUERY() for a given JsonTableColumn.
475 : : */
476 : : static bool
899 amitlan@postgresql.o 477 :CBC 730 : isCompositeType(Oid typid)
478 : : {
479 : 730 : char typtype = get_typtype(typid);
480 : :
481 [ + + ]: 694 : return typid == JSONOID ||
482 [ + - ]: 650 : typid == JSONBOID ||
483 [ + + ]: 650 : typid == RECORDOID ||
484 [ + + ]: 1252 : type_is_array(typid) ||
485 [ + + + + ]: 1452 : typtype == TYPTYPE_COMPOSITE ||
486 : : /* domain over one of the above? */
487 [ - + ]: 28 : (typtype == TYPTYPE_DOMAIN &&
488 : 28 : isCompositeType(getBaseType(typid)));
489 : : }
490 : :
491 : : /*
492 : : * Transform JSON_TABLE column definition into a JsonFuncExpr
493 : : * This turns:
494 : : * - regular column into JSON_VALUE()
495 : : * - FORMAT JSON column into JSON_QUERY()
496 : : * - EXISTS column into JSON_EXISTS()
497 : : */
498 : : static JsonFuncExpr *
499 : 902 : transformJsonTableColumn(JsonTableColumn *jtc, Node *contextItemExpr,
500 : : List *passingArgs, bool errorOnError)
501 : : {
502 : : Node *pathspec;
503 : 902 : JsonFuncExpr *jfexpr = makeNode(JsonFuncExpr);
504 : :
505 [ + + ]: 902 : if (jtc->coltype == JTC_REGULAR)
506 : 542 : jfexpr->op = JSON_VALUE_OP;
507 [ + + ]: 360 : else if (jtc->coltype == JTC_EXISTS)
508 : 108 : jfexpr->op = JSON_EXISTS_OP;
509 : : else
510 : 252 : jfexpr->op = JSON_QUERY_OP;
511 : :
512 : : /* Pass the column name so any runtime JsonExpr errors can print it. */
885 513 [ - + ]: 902 : Assert(jtc->name != NULL);
514 : 902 : jfexpr->column_name = pstrdup(jtc->name);
515 : :
899 516 : 902 : jfexpr->context_item = makeJsonValueExpr((Expr *) contextItemExpr, NULL,
517 : : makeJsonFormat(JS_FORMAT_DEFAULT,
518 : : JS_ENC_DEFAULT,
519 : : -1));
520 [ + + ]: 902 : if (jtc->pathspec)
521 : 820 : pathspec = (Node *) jtc->pathspec->string;
522 : : else
523 : : {
524 : : /* Construct default path as '$."column_name"' */
525 : : StringInfoData path;
526 : :
527 : 82 : initStringInfo(&path);
528 : :
529 : 82 : appendStringInfoString(&path, "$.");
530 : 82 : escape_json(&path, jtc->name);
531 : :
532 : 82 : pathspec = makeStringConst(path.data, -1);
533 : : }
534 : 902 : jfexpr->pathspec = pathspec;
535 : 902 : jfexpr->passing = passingArgs;
536 : 902 : jfexpr->output = makeNode(JsonOutput);
537 : 902 : jfexpr->output->typeName = jtc->typeName;
538 : 902 : jfexpr->output->returning = makeNode(JsonReturning);
539 : 902 : jfexpr->output->returning->format = jtc->format;
540 : 902 : jfexpr->on_empty = jtc->on_empty;
541 : 902 : jfexpr->on_error = jtc->on_error;
542 : :
543 : : /*
544 : : * Per the SQL/JSON standard, a regular or formatted column that does not
545 : : * specify its own ON ERROR clause inherits ERROR ON ERROR from a
546 : : * table-level ERROR ON ERROR clause; otherwise it defaults to NULL ON
547 : : * ERROR (applied downstream in transformJsonExprCommon()). See ISO/IEC
548 : : * 9075-2:2023, 7.11 <JSON table>, Syntax Rules 1)e)iv) (regular columns)
549 : : * and 1)f)xi) (formatted columns). EXISTS columns are not covered by the
550 : : * standard, so they keep their own default (FALSE ON ERROR).
551 : : */
1 akorotkov@postgresql 552 [ + + + + ]:GNC 902 : if (jfexpr->on_error == NULL && errorOnError &&
553 [ + + ]: 32 : jfexpr->op != JSON_EXISTS_OP)
554 : 28 : jfexpr->on_error = makeJsonBehavior(JSON_BEHAVIOR_ERROR, NULL, -1);
555 : :
899 amitlan@postgresql.o 556 :CBC 902 : jfexpr->quotes = jtc->quotes;
557 : 902 : jfexpr->wrapper = jtc->wrapper;
558 : 902 : jfexpr->location = jtc->location;
559 : :
560 : 902 : return jfexpr;
561 : : }
562 : :
563 : : static JsonTableColumn *
73 akorotkov@postgresql 564 :GNC 128 : findNestedJsonTableColumn(List *columns, const char *pathname)
565 : : {
566 : : ListCell *lc;
567 : :
568 [ + - + - : 488 : foreach(lc, columns)
+ - ]
569 : : {
570 : 488 : JsonTableColumn *jtc = castNode(JsonTableColumn, lfirst(lc));
571 : :
572 [ + + ]: 488 : if (jtc->coltype == JTC_NESTED &&
573 [ + - ]: 176 : jtc->pathspec->name &&
574 [ + + ]: 176 : !strcmp(jtc->pathspec->name, pathname))
575 : 128 : return jtc;
576 : : }
577 : :
73 akorotkov@postgresql 578 :UNC 0 : return NULL;
579 : : }
580 : :
581 : : /*
582 : : * Recursively transform nested columns and create child plan(s) that will be
583 : : * used to evaluate their row patterns.
584 : : *
585 : : * Default plan is transformed into a cross/union join of its nested columns.
586 : : * Simple and outer/inner plans are transformed into a JsonTablePlan by
587 : : * finding and transforming corresponding nested column.
588 : : * Sibling plans are recursively transformed into a JsonTableSiblingJoin.
589 : : */
590 : : static JsonTablePlan *
895 amitlan@postgresql.o 591 :CBC 744 : transformJsonTableNestedColumns(JsonTableParseContext *cxt,
592 : : JsonTablePlanSpec *planspec,
593 : : List *columns,
594 : : List *passingArgs)
595 : : {
73 akorotkov@postgresql 596 :GNC 744 : JsonTableColumn *jtc = NULL;
597 : :
598 [ + + + + ]: 744 : if (!planspec || planspec->plan_type == JSTP_DEFAULT)
599 : : {
600 : : /* unspecified or default plan */
601 : 560 : JsonTablePlan *plan = NULL;
602 : : ListCell *lc;
603 [ + + + + ]: 560 : bool cross = planspec && (planspec->join_type & JSTP_JOIN_CROSS);
604 : :
605 : : /*
606 : : * If there are multiple NESTED COLUMNS clauses in 'columns', their
607 : : * respective plans will be combined using a "sibling join" plan,
608 : : * which effectively does a UNION of the sets of rows coming from each
609 : : * nested plan.
610 : : */
611 [ + - + + : 1496 : foreach(lc, columns)
+ + ]
612 : : {
613 : 936 : JsonTableColumn *col = castNode(JsonTableColumn, lfirst(lc));
614 : : JsonTablePlan *nested;
615 : :
616 [ + + ]: 936 : if (col->coltype != JTC_NESTED)
617 : 730 : continue;
618 : :
619 [ + + ]: 206 : if (col->pathspec->name == NULL)
620 : : {
621 : 96 : col->pathspec->name = generateJsonTablePathName(cxt);
622 : : }
623 : :
624 : 206 : nested = transformJsonTableColumns(cxt, planspec, col->columns,
625 : : passingArgs,
626 : : col->pathspec);
627 : :
628 : : /* Join nested plan with previous sibling nested plans. */
629 [ + + ]: 206 : if (plan)
630 : 76 : plan = makeJsonTableSiblingJoin(cross, plan, nested);
631 : : else
632 : 130 : plan = nested;
633 : : }
634 : :
635 : 560 : return plan;
636 : : }
637 [ + + ]: 184 : else if (planspec->plan_type == JSTP_SIMPLE)
638 : : {
639 : 92 : jtc = findNestedJsonTableColumn(columns, planspec->pathname);
640 : : }
641 [ + - ]: 92 : else if (planspec->plan_type == JSTP_JOINED)
642 : : {
643 [ + + ]: 92 : if (planspec->join_type == JSTP_JOIN_INNER ||
644 [ + + ]: 68 : planspec->join_type == JSTP_JOIN_OUTER)
645 : : {
646 [ - + ]: 36 : Assert(planspec->plan1->plan_type == JSTP_SIMPLE);
647 : 36 : jtc = findNestedJsonTableColumn(columns, planspec->plan1->pathname);
648 : : }
649 : : else
650 : : {
651 : 56 : JsonTablePlan *lplan = transformJsonTableNestedColumns(cxt,
652 : 56 : planspec->plan1,
653 : : columns,
654 : : passingArgs);
655 : 48 : JsonTablePlan *rplan = transformJsonTableNestedColumns(cxt,
656 : 48 : planspec->plan2,
657 : : columns,
658 : : passingArgs);
659 : :
660 : 44 : return makeJsonTableSiblingJoin(planspec->join_type == JSTP_JOIN_CROSS,
661 : : lplan, rplan);
662 : : }
663 : : }
664 : : else
73 akorotkov@postgresql 665 [ # # ]:UNC 0 : elog(ERROR, "invalid JSON_TABLE plan type %d", planspec->plan_type);
666 : :
667 : : /*
668 : : * The plan's path names were already matched one-to-one against the
669 : : * nested columns by validateJsonTableChildPlan(), so a nested column with
670 : : * this path name must exist.
671 : : */
67 akorotkov@postgresql 672 [ - + ]:GNC 128 : Assert(jtc != NULL);
673 : :
73 674 : 128 : return transformJsonTableColumns(cxt, planspec, jtc->columns,
675 : : passingArgs,
676 : : jtc->pathspec);
677 : : }
678 : :
679 : : /*
680 : : * Create transformed JSON_TABLE parent plan node by appending all non-nested
681 : : * columns to the TableFunc node and remembering their indices in the
682 : : * colvalexprs list.
683 : : *
684 : : * colMin and colMax give the range of columns computed by this scan in the
685 : : * global flat list of column expressions that will be passed to the
686 : : * JSON_TABLE's TableFunc. Both are -1 when all of columns are nested and
687 : : * thus computed by 'childplan'.
688 : : */
689 : : static JsonTablePlan *
690 : 712 : makeJsonTablePathScan(JsonTableParseContext *cxt, JsonTablePathSpec *pathspec,
691 : : JsonTablePlanSpec *planspec,
692 : : bool errorOnError,
693 : : int colMin, int colMax,
694 : : JsonTablePlan *childplan)
695 : : {
899 amitlan@postgresql.o 696 :CBC 712 : JsonTablePathScan *scan = makeNode(JsonTablePathScan);
697 : : char *pathstring;
698 : : Const *value;
699 : :
700 [ - + ]: 712 : Assert(IsA(pathspec->string, A_Const));
701 : 712 : pathstring = castNode(A_Const, pathspec->string)->val.sval.sval;
702 : 712 : value = makeConst(JSONPATHOID, -1, InvalidOid, -1,
703 : : DirectFunctionCall1(jsonpath_in,
704 : : CStringGetDatum(pathstring)),
705 : : false, false);
706 : :
707 : 712 : scan->plan.type = T_JsonTablePathScan;
708 : 712 : scan->path = makeJsonTablePath(value, pathspec->name);
709 : 712 : scan->errorOnError = errorOnError;
710 : :
895 711 : 712 : scan->child = childplan;
712 : :
713 : 712 : scan->colMin = colMin;
714 : 712 : scan->colMax = colMax;
715 : :
73 akorotkov@postgresql 716 [ + + ]:GNC 712 : if (scan->child)
717 [ + + ]: 286 : scan->outerJoin = planspec == NULL ||
718 [ + + ]: 286 : (planspec->join_type & JSTP_JOIN_OUTER);
719 : : /* else: default plan case, no children found */
720 : :
899 amitlan@postgresql.o 721 :CBC 712 : return (JsonTablePlan *) scan;
722 : : }
723 : :
724 : : /*
725 : : * Create a JsonTablePlan that will perform a join of the rows coming from
726 : : * 'lplan' and 'rplan'.
727 : : *
728 : : * The default way of "joining" the rows is to perform a UNION between the
729 : : * sets of rows from 'lplan' and 'rplan'.
730 : : */
731 : : static JsonTablePlan *
73 akorotkov@postgresql 732 :GNC 120 : makeJsonTableSiblingJoin(bool cross, JsonTablePlan *lplan, JsonTablePlan *rplan)
733 : : {
895 amitlan@postgresql.o 734 :CBC 120 : JsonTableSiblingJoin *join = makeNode(JsonTableSiblingJoin);
735 : :
736 : 120 : join->plan.type = T_JsonTableSiblingJoin;
737 : 120 : join->lplan = lplan;
738 : 120 : join->rplan = rplan;
73 akorotkov@postgresql 739 :GNC 120 : join->cross = cross;
740 : :
895 amitlan@postgresql.o 741 :CBC 120 : return (JsonTablePlan *) join;
742 : : }
743 : :
744 : : /* Collect sibling path names from plan to the specified list. */
745 : : static void
73 akorotkov@postgresql 746 :GNC 236 : collectSiblingPathsInJsonTablePlan(JsonTablePlanSpec *plan, List **paths)
747 : : {
748 [ + + ]: 236 : if (plan->plan_type == JSTP_SIMPLE)
749 : 132 : *paths = lappend(*paths, plan->pathname);
750 [ + - ]: 104 : else if (plan->plan_type == JSTP_JOINED)
751 : : {
752 [ + + ]: 104 : if (plan->join_type == JSTP_JOIN_INNER ||
753 [ + + ]: 80 : plan->join_type == JSTP_JOIN_OUTER)
754 : : {
755 [ - + ]: 36 : Assert(plan->plan1->plan_type == JSTP_SIMPLE);
756 : 36 : *paths = lappend(*paths, plan->plan1->pathname);
757 : : }
758 [ + + ]: 68 : else if (plan->join_type == JSTP_JOIN_CROSS ||
759 [ + - ]: 24 : plan->join_type == JSTP_JOIN_UNION)
760 : : {
761 : 68 : collectSiblingPathsInJsonTablePlan(plan->plan1, paths);
762 : 68 : collectSiblingPathsInJsonTablePlan(plan->plan2, paths);
763 : : }
764 : : else
73 akorotkov@postgresql 765 [ # # ]:UNC 0 : elog(ERROR, "invalid JSON_TABLE join type %d",
766 : : plan->join_type);
767 : : }
73 akorotkov@postgresql 768 :GNC 236 : }
769 : :
770 : : /*
771 : : * Validate child JSON_TABLE plan by checking that:
772 : : * - all nested columns have path names specified
773 : : * - all nested columns have corresponding node in the sibling plan
774 : : * - plan does not contain duplicate or extra nodes
775 : : */
776 : : static void
777 : 200 : validateJsonTableChildPlan(JsonTableParseContext *cxt, JsonTablePlanSpec *plan,
778 : : List *columns)
779 : : {
780 : 200 : ParseState *pstate = cxt->pstate;
781 : : ListCell *lc1;
782 : 200 : List *siblings = NIL;
783 : 200 : int nchildren = 0;
784 : :
785 [ + + ]: 200 : if (plan)
786 : 100 : collectSiblingPathsInJsonTablePlan(plan, &siblings);
787 : :
788 [ + - + + : 604 : foreach(lc1, columns)
+ + ]
789 : : {
790 : 436 : JsonTableColumn *jtc = castNode(JsonTableColumn, lfirst(lc1));
791 : :
792 [ + + ]: 436 : if (jtc->coltype == JTC_NESTED)
793 : : {
794 : : ListCell *lc2;
795 : 188 : bool found = false;
796 : :
797 : : /*
798 : : * A NESTED path need not be named; generate a name if it was left
799 : : * unnamed. A generated name cannot be referenced by a specific
800 : : * PLAN(), so such a path is reported just below as a nested path
801 : : * not covered by the plan.
802 : : */
803 [ + + ]: 188 : if (jtc->pathspec->name == NULL)
804 : 8 : jtc->pathspec->name = generateJsonTablePathName(cxt);
805 : :
806 : : /* find nested path name in the list of sibling path names */
807 [ + + + + : 272 : foreach(lc2, siblings)
+ + ]
808 : : {
809 [ + + ]: 240 : if ((found = !strcmp(jtc->pathspec->name, lfirst(lc2))))
810 : 156 : break;
811 : : }
812 : :
813 [ + + ]: 188 : if (!found)
814 [ + - ]: 32 : ereport(ERROR,
815 : : errcode(ERRCODE_SYNTAX_ERROR),
816 : : errmsg("invalid JSON_TABLE specification"),
817 : : errdetail("PLAN clause for nested path %s was not found.",
818 : : jtc->pathspec->name),
819 : : parser_errposition(pstate, jtc->location));
820 : :
821 : 156 : nchildren++;
822 : : }
823 : : }
824 : :
825 [ + + ]: 168 : if (list_length(siblings) > nchildren)
826 [ + - + - ]: 4 : ereport(ERROR,
827 : : errcode(ERRCODE_SYNTAX_ERROR),
828 : : errmsg("invalid JSON_TABLE plan clause"),
829 : : errdetail("PLAN clause contains some extra or duplicate sibling nodes."),
830 : : parser_errposition(pstate, plan ? plan->location : -1));
831 : 164 : }
|