Debian Codegraph @

src/backend/utils/adt/jsonpath_exec.c

raw
1 /*-------------------------------------------------------------------------
2 *
3 * jsonpath_exec.c
4 * Routines for SQL/JSON path execution.
5 *
6 * Jsonpath is executed in the global context stored in JsonPathExecContext,
7 * which is passed to almost every function involved into execution. Entry
8 * point for jsonpath execution is executeJsonPath() function, which
9 * initializes execution context including initial JsonPathItem and JsonbValue,
10 * flags, stack for calculation of @ in filters.
11 *
12 * The result of jsonpath query execution is enum JsonPathExecResult and
13 * if succeeded sequence of JsonbValue, written to JsonValueList *found, which
14 * is passed through the jsonpath items. When found == NULL, we're inside
15 * exists-query and we're interested only in whether result is empty. In this
16 * case execution is stopped once first result item is found, and the only
17 * execution result is JsonPathExecResult. The values of JsonPathExecResult
18 * are following:
19 * - jperOk -- result sequence is not empty
20 * - jperNotFound -- result sequence is empty
21 * - jperError -- error occurred during execution
22 *
23 * Jsonpath is executed recursively (see executeItem()) starting form the
24 * first path item (which in turn might be, for instance, an arithmetic
25 * expression evaluated separately). On each step single JsonbValue obtained
26 * from previous path item is processed. The result of processing is a
27 * sequence of JsonbValue (probably empty), which is passed to the next path
28 * item one by one. When there is no next path item, then JsonbValue is added
29 * to the 'found' list. When found == NULL, then execution functions just
30 * return jperOk (see executeNextItem()).
31 *
32 * Many of jsonpath operations require automatic unwrapping of arrays in lax
33 * mode. So, if input value is array, then corresponding operation is
34 * processed not on array itself, but on all of its members one by one.
35 * executeItemOptUnwrapTarget() function have 'unwrap' argument, which indicates
36 * whether unwrapping of array is needed. When unwrap == true, each of array
37 * members is passed to executeItemOptUnwrapTarget() again but with unwrap == false
38 * in order to avoid subsequent array unwrapping.
39 *
40 * All boolean expressions (predicates) are evaluated by executeBoolItem()
41 * function, which returns tri-state JsonPathBool. When error is occurred
42 * during predicate execution, it returns jpbUnknown. According to standard
43 * predicates can be only inside filters. But we support their usage as
44 * jsonpath expression. This helps us to implement @@ operator. In this case
45 * resulting JsonPathBool is transformed into jsonb bool or null.
46 *
47 * Arithmetic and boolean expression are evaluated recursively from expression
48 * tree top down to the leaves. Therefore, for binary arithmetic expressions
49 * we calculate operands first. Then we check that results are numeric
50 * singleton lists, calculate the result and pass it to the next path item.
51 *
52 * Copyright (c) 2019-2025, PostgreSQL Global Development Group
53 *
54 * IDENTIFICATION
55 * src/backend/utils/adt/jsonpath_exec.c
56 *
57 *-------------------------------------------------------------------------
58 */
59
60 #include "postgres.h"
61
62 #include "catalog/pg_collation.h"
63 #include "catalog/pg_type.h"
64 #include "funcapi.h"
65 #include "miscadmin.h"
66 #include "nodes/miscnodes.h"
67 #include "nodes/nodeFuncs.h"
68 #include "regex/regex.h"
69 #include "utils/builtins.h"
70 #include "utils/date.h"
71 #include "utils/datetime.h"
72 #include "utils/float.h"
73 #include "utils/formatting.h"
74 #include "utils/json.h"
75 #include "utils/jsonpath.h"
76 #include "utils/memutils.h"
77 #include "utils/timestamp.h"
78
79 /*
80 * Represents "base object" and its "id" for .keyvalue() evaluation.
81 */
82 typedef struct JsonBaseObjectInfo
83 {
84 JsonbContainer *jbc;
85 int id;
86 } JsonBaseObjectInfo;
87
88 /* Callbacks for executeJsonPath() */
89 typedef JsonbValue *(*JsonPathGetVarCallback) (void *vars, char *varName, int varNameLen,
90 JsonbValue *baseObject, int *baseObjectId);
91 typedef int (*JsonPathCountVarsCallback) (void *vars);
92
93 /*
94 * Context of jsonpath execution.
95 */
96 typedef struct JsonPathExecContext
97 {
98 void *vars; /* variables to substitute into jsonpath */
99 JsonPathGetVarCallback getVar; /* callback to extract a given variable
100 * from 'vars' */
101 JsonbValue *root; /* for $ evaluation */
102 JsonbValue *current; /* for @ evaluation */
103 JsonBaseObjectInfo baseObject; /* "base object" for .keyvalue()
104 * evaluation */
105 int lastGeneratedObjectId; /* "id" counter for .keyvalue()
106 * evaluation */
107 int innermostArraySize; /* for LAST array index evaluation */
108 bool laxMode; /* true for "lax" mode, false for "strict"
109 * mode */
110 bool ignoreStructuralErrors; /* with "true" structural errors such
111 * as absence of required json item or
112 * unexpected json item type are
113 * ignored */
114 bool throwErrors; /* with "false" all suppressible errors are
115 * suppressed */
116 bool useTz;
117 } JsonPathExecContext;
118
119 /* Context for LIKE_REGEX execution. */
120 typedef struct JsonLikeRegexContext
121 {
122 text *regex;
123 int cflags;
124 } JsonLikeRegexContext;
125
126 /* Result of jsonpath predicate evaluation */
127 typedef enum JsonPathBool
128 {
129 jpbFalse = 0,
130 jpbTrue = 1,
131 jpbUnknown = 2
132 } JsonPathBool;
133
134 /* Result of jsonpath expression evaluation */
135 typedef enum JsonPathExecResult
136 {
137 jperOk = 0,
138 jperNotFound = 1,
139 jperError = 2
140 } JsonPathExecResult;
141
142 #define jperIsError(jper) ((jper) == jperError)
143
144 /*
145 * List of jsonb values with shortcut for single-value list.
146 */
147 typedef struct JsonValueList
148 {
149 JsonbValue *singleton;
150 List *list;
151 } JsonValueList;
152
153 typedef struct JsonValueListIterator
154 {
155 JsonbValue *value;
156 List *list;
157 ListCell *next;
158 } JsonValueListIterator;
159
160 /* Structures for JSON_TABLE execution */
161
162 /*
163 * Struct holding the result of jsonpath evaluation, to be used as source row
164 * for JsonTableGetValue() which in turn computes the values of individual
165 * JSON_TABLE columns.
166 */
167 typedef struct JsonTablePlanRowSource
168 {
169 Datum value;
170 bool isnull;
171 } JsonTablePlanRowSource;
172
173 /*
174 * State of evaluation of row pattern derived by applying jsonpath given in
175 * a JsonTablePlan to an input document given in the parent TableFunc.
176 */
177 typedef struct JsonTablePlanState
178 {
179 /* Original plan */
180 JsonTablePlan *plan;
181
182 /* The following fields are only valid for JsonTablePathScan plans */
183
184 /* jsonpath to evaluate against the input doc to get the row pattern */
185 JsonPath *path;
186
187 /*
188 * Memory context to use when evaluating the row pattern from the jsonpath
189 */
190 MemoryContext mcxt;
191
192 /* PASSING arguments passed to jsonpath executor */
193 List *args;
194
195 /* List and iterator of jsonpath result values */
196 JsonValueList found;
197 JsonValueListIterator iter;
198
199 /* Currently selected row for JsonTableGetValue() to use */
200 JsonTablePlanRowSource current;
201
202 /* Counter for ORDINAL columns */
203 int ordinal;
204
205 /* Nested plan, if any */
206 struct JsonTablePlanState *nested;
207
208 /* Left sibling, if any */
209 struct JsonTablePlanState *left;
210
211 /* Right sibling, if any */
212 struct JsonTablePlanState *right;
213
214 /* Parent plan, if this is a nested plan */
215 struct JsonTablePlanState *parent;
216 } JsonTablePlanState;
217
218 /* Random number to identify JsonTableExecContext for sanity checking */
219 #define JSON_TABLE_EXEC_CONTEXT_MAGIC 418352867
220
221 typedef struct JsonTableExecContext
222 {
223 int magic;
224
225 /* State of the plan providing a row evaluated from "root" jsonpath */
226 JsonTablePlanState *rootplanstate;
227
228 /*
229 * Per-column JsonTablePlanStates for all columns including the nested
230 * ones.
231 */
232 JsonTablePlanState **colplanstates;
233 } JsonTableExecContext;
234
235 /* strict/lax flags is decomposed into four [un]wrap/error flags */
236 #define jspStrictAbsenceOfErrors(cxt) (!(cxt)->laxMode)
237 #define jspAutoUnwrap(cxt) ((cxt)->laxMode)
238 #define jspAutoWrap(cxt) ((cxt)->laxMode)
239 #define jspIgnoreStructuralErrors(cxt) ((cxt)->ignoreStructuralErrors)
240 #define jspThrowErrors(cxt) ((cxt)->throwErrors)
241
242 /* Convenience macro: return or throw error depending on context */
243 #define RETURN_ERROR(throw_error) \
244 do { \
245 if (jspThrowErrors(cxt)) \
246 throw_error; \
247 else \
248 return jperError; \
249 } while (0)
250
251 typedef JsonPathBool (*JsonPathPredicateCallback) (JsonPathItem *jsp,
252 JsonbValue *larg,
253 JsonbValue *rarg,
254 void *param);
255 typedef Numeric (*BinaryArithmFunc) (Numeric num1, Numeric num2, bool *error);
256
257 static JsonPathExecResult executeJsonPath(JsonPath *path, void *vars,
258 JsonPathGetVarCallback getVar,
259 JsonPathCountVarsCallback countVars,
260 Jsonb *json, bool throwErrors,
261 JsonValueList *result, bool useTz);
262 static JsonPathExecResult executeItem(JsonPathExecContext *cxt,
263 JsonPathItem *jsp, JsonbValue *jb, JsonValueList *found);
264 static JsonPathExecResult executeItemOptUnwrapTarget(JsonPathExecContext *cxt,
265 JsonPathItem *jsp, JsonbValue *jb,
266 JsonValueList *found, bool unwrap);
267 static JsonPathExecResult executeItemUnwrapTargetArray(JsonPathExecContext *cxt,
268 JsonPathItem *jsp, JsonbValue *jb,
269 JsonValueList *found, bool unwrapElements);
270 static JsonPathExecResult executeNextItem(JsonPathExecContext *cxt,
271 JsonPathItem *cur, JsonPathItem *next,
272 JsonbValue *v, JsonValueList *found, bool copy);
273 static JsonPathExecResult executeItemOptUnwrapResult(JsonPathExecContext *cxt, JsonPathItem *jsp, JsonbValue *jb,
274 bool unwrap, JsonValueList *found);
275 static JsonPathExecResult executeItemOptUnwrapResultNoThrow(JsonPathExecContext *cxt, JsonPathItem *jsp,
276 JsonbValue *jb, bool unwrap, JsonValueList *found);
277 static JsonPathBool executeBoolItem(JsonPathExecContext *cxt,
278 JsonPathItem *jsp, JsonbValue *jb, bool canHaveNext);
279 static JsonPathBool executeNestedBoolItem(JsonPathExecContext *cxt,
280 JsonPathItem *jsp, JsonbValue *jb);
281 static JsonPathExecResult executeAnyItem(JsonPathExecContext *cxt,
282 JsonPathItem *jsp, JsonbContainer *jbc, JsonValueList *found,
283 uint32 level, uint32 first, uint32 last,
284 bool ignoreStructuralErrors, bool unwrapNext);
285 static JsonPathBool executePredicate(JsonPathExecContext *cxt,
286 JsonPathItem *pred, JsonPathItem *larg, JsonPathItem *rarg,
287 JsonbValue *jb, bool unwrapRightArg,
288 JsonPathPredicateCallback exec, void *param);
289 static JsonPathExecResult executeBinaryArithmExpr(JsonPathExecContext *cxt,
290 JsonPathItem *jsp, JsonbValue *jb,
291 BinaryArithmFunc func, JsonValueList *found);
292 static JsonPathExecResult executeUnaryArithmExpr(JsonPathExecContext *cxt,
293 JsonPathItem *jsp, JsonbValue *jb, PGFunction func,
294 JsonValueList *found);
295 static JsonPathBool executeStartsWith(JsonPathItem *jsp,
296 JsonbValue *whole, JsonbValue *initial, void *param);
297 static JsonPathBool executeLikeRegex(JsonPathItem *jsp, JsonbValue *str,
298 JsonbValue *rarg, void *param);
299 static JsonPathExecResult executeNumericItemMethod(JsonPathExecContext *cxt,
300 JsonPathItem *jsp, JsonbValue *jb, bool unwrap, PGFunction func,
301 JsonValueList *found);
302 static JsonPathExecResult executeDateTimeMethod(JsonPathExecContext *cxt, JsonPathItem *jsp,
303 JsonbValue *jb, JsonValueList *found);
304 static JsonPathExecResult executeKeyValueMethod(JsonPathExecContext *cxt,
305 JsonPathItem *jsp, JsonbValue *jb, JsonValueList *found);
306 static JsonPathExecResult appendBoolResult(JsonPathExecContext *cxt,
307 JsonPathItem *jsp, JsonValueList *found, JsonPathBool res);
308 static void getJsonPathItem(JsonPathExecContext *cxt, JsonPathItem *item,
309 JsonbValue *value);
310 static JsonbValue *GetJsonPathVar(void *cxt, char *varName, int varNameLen,
311 JsonbValue *baseObject, int *baseObjectId);
312 static int CountJsonPathVars(void *cxt);
313 static void JsonItemFromDatum(Datum val, Oid typid, int32 typmod,
314 JsonbValue *res);
315 static void JsonbValueInitNumericDatum(JsonbValue *jbv, Datum num);
316 static void getJsonPathVariable(JsonPathExecContext *cxt,
317 JsonPathItem *variable, JsonbValue *value);
318 static int countVariablesFromJsonb(void *varsJsonb);
319 static JsonbValue *getJsonPathVariableFromJsonb(void *varsJsonb, char *varName,
320 int varNameLength,
321 JsonbValue *baseObject,
322 int *baseObjectId);
323 static int JsonbArraySize(JsonbValue *jb);
324 static JsonPathBool executeComparison(JsonPathItem *cmp, JsonbValue *lv,
325 JsonbValue *rv, void *p);
326 static JsonPathBool compareItems(int32 op, JsonbValue *jb1, JsonbValue *jb2,
327 bool useTz);
328 static int compareNumeric(Numeric a, Numeric b);
329 static JsonbValue *copyJsonbValue(JsonbValue *src);
330 static JsonPathExecResult getArrayIndex(JsonPathExecContext *cxt,
331 JsonPathItem *jsp, JsonbValue *jb, int32 *index);
332 static JsonBaseObjectInfo setBaseObject(JsonPathExecContext *cxt,
333 JsonbValue *jbv, int32 id);
334 static void JsonValueListClear(JsonValueList *jvl);
335 static void JsonValueListAppend(JsonValueList *jvl, JsonbValue *jbv);
336 static int JsonValueListLength(const JsonValueList *jvl);
337 static bool JsonValueListIsEmpty(JsonValueList *jvl);
338 static JsonbValue *JsonValueListHead(JsonValueList *jvl);
339 static List *JsonValueListGetList(JsonValueList *jvl);
340 static void JsonValueListInitIterator(const JsonValueList *jvl,
341 JsonValueListIterator *it);
342 static JsonbValue *JsonValueListNext(const JsonValueList *jvl,
343 JsonValueListIterator *it);
344 static JsonbValue *JsonbInitBinary(JsonbValue *jbv, Jsonb *jb);
345 static int JsonbType(JsonbValue *jb);
346 static JsonbValue *getScalar(JsonbValue *scalar, enum jbvType type);
347 static JsonbValue *wrapItemsInArray(const JsonValueList *items);
348 static int compareDatetime(Datum val1, Oid typid1, Datum val2, Oid typid2,
349 bool useTz, bool *cast_error);
350 static void checkTimezoneIsUsedForCast(bool useTz, const char *type1,
351 const char *type2);
352
353 static void JsonTableInitOpaque(TableFuncScanState *state, int natts);
354 static JsonTablePlanState *JsonTableInitPlan(JsonTableExecContext *cxt,
355 JsonTablePlan *plan,
356 JsonTablePlanState *parentstate,
357 List *args,
358 MemoryContext mcxt);
359 static void JsonTableSetDocument(TableFuncScanState *state, Datum value);
360 static void JsonTableResetRowPattern(JsonTablePlanState *planstate, Datum item);
361 static bool JsonTableFetchRow(TableFuncScanState *state);
362 static Datum JsonTableGetValue(TableFuncScanState *state, int colnum,
363 Oid typid, int32 typmod, bool *isnull);
364 static void JsonTableDestroyOpaque(TableFuncScanState *state);
365 static bool JsonTablePlanScanNextRow(JsonTablePlanState *planstate);
366 static void JsonTableResetNestedPlan(JsonTablePlanState *planstate);
367 static bool JsonTablePlanJoinNextRow(JsonTablePlanState *planstate);
368 static bool JsonTablePlanNextRow(JsonTablePlanState *planstate);
369
370 const TableFuncRoutine JsonbTableRoutine =
371 {
372 .InitOpaque = JsonTableInitOpaque,
373 .SetDocument = JsonTableSetDocument,
374 .SetNamespace = NULL,
375 .SetRowFilter = NULL,
376 .SetColumnFilter = NULL,
377 .FetchRow = JsonTableFetchRow,
378 .GetValue = JsonTableGetValue,
379 .DestroyOpaque = JsonTableDestroyOpaque
380 };
381
382 /****************** User interface to JsonPath executor ********************/
383
384 /*
385 * jsonb_path_exists
386 * Returns true if jsonpath returns at least one item for the specified
387 * jsonb value. This function and jsonb_path_match() are used to
388 * implement @? and @@ operators, which in turn are intended to have an
389 * index support. Thus, it's desirable to make it easier to achieve
390 * consistency between index scan results and sequential scan results.
391 * So, we throw as few errors as possible. Regarding this function,
392 * such behavior also matches behavior of JSON_EXISTS() clause of
393 * SQL/JSON. Regarding jsonb_path_match(), this function doesn't have
394 * an analogy in SQL/JSON, so we define its behavior on our own.
395 */
396 static Datum
397 jsonb_path_exists_internal(FunctionCallInfo fcinfo, bool tz)
398 {
399 Jsonb *jb = PG_GETARG_JSONB_P(0);
400 JsonPath *jp = PG_GETARG_JSONPATH_P(1);
401 JsonPathExecResult res;
402 Jsonb *vars = NULL;
403 bool silent = true;
404
405 if (PG_NARGS() == 4)
406 {
407 vars = PG_GETARG_JSONB_P(2);
408 silent = PG_GETARG_BOOL(3);
409 }
410
411 res = executeJsonPath(jp, vars, getJsonPathVariableFromJsonb,
412 countVariablesFromJsonb,
413 jb, !silent, NULL, tz);
414
415 PG_FREE_IF_COPY(jb, 0);
416 PG_FREE_IF_COPY(jp, 1);
417
418 if (jperIsError(res))
419 PG_RETURN_NULL();
420
421 PG_RETURN_BOOL(res == jperOk);
422 }
423
424 Datum
425 jsonb_path_exists(PG_FUNCTION_ARGS)
426 {
427 return jsonb_path_exists_internal(fcinfo, false);
428 }
429
430 Datum
431 jsonb_path_exists_tz(PG_FUNCTION_ARGS)
432 {
433 return jsonb_path_exists_internal(fcinfo, true);
434 }
435
436 /*
437 * jsonb_path_exists_opr
438 * Implementation of operator "jsonb @? jsonpath" (2-argument version of
439 * jsonb_path_exists()).
440 */
441 Datum
442 jsonb_path_exists_opr(PG_FUNCTION_ARGS)
443 {
444 /* just call the other one -- it can handle both cases */
445 return jsonb_path_exists_internal(fcinfo, false);
446 }
447
448 /*
449 * jsonb_path_match
450 * Returns jsonpath predicate result item for the specified jsonb value.
451 * See jsonb_path_exists() comment for details regarding error handling.
452 */
453 static Datum
454 jsonb_path_match_internal(FunctionCallInfo fcinfo, bool tz)
455 {
456 Jsonb *jb = PG_GETARG_JSONB_P(0);
457 JsonPath *jp = PG_GETARG_JSONPATH_P(1);
458 JsonValueList found = {0};
459 Jsonb *vars = NULL;
460 bool silent = true;
461
462 if (PG_NARGS() == 4)
463 {
464 vars = PG_GETARG_JSONB_P(2);
465 silent = PG_GETARG_BOOL(3);
466 }
467
468 (void) executeJsonPath(jp, vars, getJsonPathVariableFromJsonb,
469 countVariablesFromJsonb,
470 jb, !silent, &found, tz);
471
472 PG_FREE_IF_COPY(jb, 0);
473 PG_FREE_IF_COPY(jp, 1);
474
475 if (JsonValueListLength(&found) == 1)
476 {
477 JsonbValue *jbv = JsonValueListHead(&found);
478
479 if (jbv->type == jbvBool)
480 PG_RETURN_BOOL(jbv->val.boolean);
481
482 if (jbv->type == jbvNull)
483 PG_RETURN_NULL();
484 }
485
486 if (!silent)
487 ereport(ERROR,
488 (errcode(ERRCODE_SINGLETON_SQL_JSON_ITEM_REQUIRED),
489 errmsg("single boolean result is expected")));
490
491 PG_RETURN_NULL();
492 }
493
494 Datum
495 jsonb_path_match(PG_FUNCTION_ARGS)
496 {
497 return jsonb_path_match_internal(fcinfo, false);
498 }
499
500 Datum
501 jsonb_path_match_tz(PG_FUNCTION_ARGS)
502 {
503 return jsonb_path_match_internal(fcinfo, true);
504 }
505
506 /*
507 * jsonb_path_match_opr
508 * Implementation of operator "jsonb @@ jsonpath" (2-argument version of
509 * jsonb_path_match()).
510 */
511 Datum
512 jsonb_path_match_opr(PG_FUNCTION_ARGS)
513 {
514 /* just call the other one -- it can handle both cases */
515 return jsonb_path_match_internal(fcinfo, false);
516 }
517
518 /*
519 * jsonb_path_query
520 * Executes jsonpath for given jsonb document and returns result as
521 * rowset.
522 */
523 static Datum
524 jsonb_path_query_internal(FunctionCallInfo fcinfo, bool tz)
525 {
526 FuncCallContext *funcctx;
527 List *found;
528 JsonbValue *v;
529 ListCell *c;
530
531 if (SRF_IS_FIRSTCALL())
532 {
533 JsonPath *jp;
534 Jsonb *jb;
535 MemoryContext oldcontext;
536 Jsonb *vars;
537 bool silent;
538 JsonValueList found = {0};
539
540 funcctx = SRF_FIRSTCALL_INIT();
541 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
542
543 jb = PG_GETARG_JSONB_P_COPY(0);
544 jp = PG_GETARG_JSONPATH_P_COPY(1);
545 vars = PG_GETARG_JSONB_P_COPY(2);
546 silent = PG_GETARG_BOOL(3);
547
548 (void) executeJsonPath(jp, vars, getJsonPathVariableFromJsonb,
549 countVariablesFromJsonb,
550 jb, !silent, &found, tz);
551
552 funcctx->user_fctx = JsonValueListGetList(&found);
553
554 MemoryContextSwitchTo(oldcontext);
555 }
556
557 funcctx = SRF_PERCALL_SETUP();
558 found = funcctx->user_fctx;
559
560 c = list_head(found);
561
562 if (c == NULL)
563 SRF_RETURN_DONE(funcctx);
564
565 v = lfirst(c);
566 funcctx->user_fctx = list_delete_first(found);
567
568 SRF_RETURN_NEXT(funcctx, JsonbPGetDatum(JsonbValueToJsonb(v)));
569 }
570
571 Datum
572 jsonb_path_query(PG_FUNCTION_ARGS)
573 {
574 return jsonb_path_query_internal(fcinfo, false);
575 }
576
577 Datum
578 jsonb_path_query_tz(PG_FUNCTION_ARGS)
579 {
580 return jsonb_path_query_internal(fcinfo, true);
581 }
582
583 /*
584 * jsonb_path_query_array
585 * Executes jsonpath for given jsonb document and returns result as
586 * jsonb array.
587 */
588 static Datum
589 jsonb_path_query_array_internal(FunctionCallInfo fcinfo, bool tz)
590 {
591 Jsonb *jb = PG_GETARG_JSONB_P(0);
592 JsonPath *jp = PG_GETARG_JSONPATH_P(1);
593 JsonValueList found = {0};
594 Jsonb *vars = PG_GETARG_JSONB_P(2);
595 bool silent = PG_GETARG_BOOL(3);
596
597 (void) executeJsonPath(jp, vars, getJsonPathVariableFromJsonb,
598 countVariablesFromJsonb,
599 jb, !silent, &found, tz);
600
601 PG_RETURN_JSONB_P(JsonbValueToJsonb(wrapItemsInArray(&found)));
602 }
603
604 Datum
605 jsonb_path_query_array(PG_FUNCTION_ARGS)
606 {
607 return jsonb_path_query_array_internal(fcinfo, false);
608 }
609
610 Datum
611 jsonb_path_query_array_tz(PG_FUNCTION_ARGS)
612 {
613 return jsonb_path_query_array_internal(fcinfo, true);
614 }
615
616 /*
617 * jsonb_path_query_first
618 * Executes jsonpath for given jsonb document and returns first result
619 * item. If there are no items, NULL returned.
620 */
621 static Datum
622 jsonb_path_query_first_internal(FunctionCallInfo fcinfo, bool tz)
623 {
624 Jsonb *jb = PG_GETARG_JSONB_P(0);
625 JsonPath *jp = PG_GETARG_JSONPATH_P(1);
626 JsonValueList found = {0};
627 Jsonb *vars = PG_GETARG_JSONB_P(2);
628 bool silent = PG_GETARG_BOOL(3);
629
630 (void) executeJsonPath(jp, vars, getJsonPathVariableFromJsonb,
631 countVariablesFromJsonb,
632 jb, !silent, &found, tz);
633
634 if (JsonValueListLength(&found) >= 1)
635 PG_RETURN_JSONB_P(JsonbValueToJsonb(JsonValueListHead(&found)));
636 else
637 PG_RETURN_NULL();
638 }
639
640 Datum
641 jsonb_path_query_first(PG_FUNCTION_ARGS)
642 {
643 return jsonb_path_query_first_internal(fcinfo, false);
644 }
645
646 Datum
647 jsonb_path_query_first_tz(PG_FUNCTION_ARGS)
648 {
649 return jsonb_path_query_first_internal(fcinfo, true);
650 }
651
652 /********************Execute functions for JsonPath**************************/
653
654 /*
655 * Interface to jsonpath executor
656 *
657 * 'path' - jsonpath to be executed
658 * 'vars' - variables to be substituted to jsonpath
659 * 'getVar' - callback used by getJsonPathVariable() to extract variables from
660 * 'vars'
661 * 'countVars' - callback to count the number of jsonpath variables in 'vars'
662 * 'json' - target document for jsonpath evaluation
663 * 'throwErrors' - whether we should throw suppressible errors
664 * 'result' - list to store result items into
665 *
666 * Returns an error if a recoverable error happens during processing, or NULL
667 * on no error.
668 *
669 * Note, jsonb and jsonpath values should be available and untoasted during
670 * work because JsonPathItem, JsonbValue and result item could have pointers
671 * into input values. If caller needs to just check if document matches
672 * jsonpath, then it doesn't provide a result arg. In this case executor
673 * works till first positive result and does not check the rest if possible.
674 * In other case it tries to find all the satisfied result items.
675 */
676 static JsonPathExecResult
677 executeJsonPath(JsonPath *path, void *vars, JsonPathGetVarCallback getVar,
678 JsonPathCountVarsCallback countVars,
679 Jsonb *json, bool throwErrors, JsonValueList *result,
680 bool useTz)
681 {
682 JsonPathExecContext cxt;
683 JsonPathExecResult res;
684 JsonPathItem jsp;
685 JsonbValue jbv;
686
687 jspInit(&jsp, path);
688
689 if (!JsonbExtractScalar(&json->root, &jbv))
690 JsonbInitBinary(&jbv, json);
691
692 cxt.vars = vars;
693 cxt.getVar = getVar;
694 cxt.laxMode = (path->header & JSONPATH_LAX) != 0;
695 cxt.ignoreStructuralErrors = cxt.laxMode;
696 cxt.root = &jbv;
697 cxt.current = &jbv;
698 cxt.baseObject.jbc = NULL;
699 cxt.baseObject.id = 0;
700 /* 1 + number of base objects in vars */
701 cxt.lastGeneratedObjectId = 1 + countVars(vars);
702 cxt.innermostArraySize = -1;
703 cxt.throwErrors = throwErrors;
704 cxt.useTz = useTz;
705
706 if (jspStrictAbsenceOfErrors(&cxt) && !result)
707 {
708 /*
709 * In strict mode we must get a complete list of values to check that
710 * there are no errors at all.
711 */
712 JsonValueList vals = {0};
713
714 res = executeItem(&cxt, &jsp, &jbv, &vals);
715
716 if (jperIsError(res))
717 return res;
718
719 return JsonValueListIsEmpty(&vals) ? jperNotFound : jperOk;
720 }
721
722 res = executeItem(&cxt, &jsp, &jbv, result);
723
724 Assert(!throwErrors || !jperIsError(res));
725
726 return res;
727 }
728
729 /*
730 * Execute jsonpath with automatic unwrapping of current item in lax mode.
731 */
732 static JsonPathExecResult
733 executeItem(JsonPathExecContext *cxt, JsonPathItem *jsp,
734 JsonbValue *jb, JsonValueList *found)
735 {
736 return executeItemOptUnwrapTarget(cxt, jsp, jb, found, jspAutoUnwrap(cxt));
737 }
738
739 /*
740 * Main jsonpath executor function: walks on jsonpath structure, finds
741 * relevant parts of jsonb and evaluates expressions over them.
742 * When 'unwrap' is true current SQL/JSON item is unwrapped if it is an array.
743 */
744 static JsonPathExecResult
745 executeItemOptUnwrapTarget(JsonPathExecContext *cxt, JsonPathItem *jsp,
746 JsonbValue *jb, JsonValueList *found, bool unwrap)
747 {
748 JsonPathItem elem;
749 JsonPathExecResult res = jperNotFound;
750 JsonBaseObjectInfo baseObject;
751
752 check_stack_depth();
753 CHECK_FOR_INTERRUPTS();
754
755 switch (jsp->type)
756 {
757 case jpiNull:
758 case jpiBool:
759 case jpiNumeric:
760 case jpiString:
761 case jpiVariable:
762 {
763 JsonbValue vbuf;
764 JsonbValue *v;
765 bool hasNext = jspGetNext(jsp, &elem);
766
767 if (!hasNext && !found && jsp->type != jpiVariable)
768 {
769 /*
770 * Skip evaluation, but not for variables. We must
771 * trigger an error for the missing variable.
772 */
773 res = jperOk;
774 break;
775 }
776
777 v = hasNext ? &vbuf : palloc(sizeof(*v));
778
779 baseObject = cxt->baseObject;
780 getJsonPathItem(cxt, jsp, v);
781
782 res = executeNextItem(cxt, jsp, &elem,
783 v, found, hasNext);
784 cxt->baseObject = baseObject;
785 }
786 break;
787
788 /* all boolean item types: */
789 case jpiAnd:
790 case jpiOr:
791 case jpiNot:
792 case jpiIsUnknown:
793 case jpiEqual:
794 case jpiNotEqual:
795 case jpiLess:
796 case jpiGreater:
797 case jpiLessOrEqual:
798 case jpiGreaterOrEqual:
799 case jpiExists:
800 case jpiStartsWith:
801 case jpiLikeRegex:
802 {
803 JsonPathBool st = executeBoolItem(cxt, jsp, jb, true);
804
805 res = appendBoolResult(cxt, jsp, found, st);
806 break;
807 }
808
809 case jpiAdd:
810 return executeBinaryArithmExpr(cxt, jsp, jb,
811 numeric_add_opt_error, found);
812
813 case jpiSub:
814 return executeBinaryArithmExpr(cxt, jsp, jb,
815 numeric_sub_opt_error, found);
816
817 case jpiMul:
818 return executeBinaryArithmExpr(cxt, jsp, jb,
819 numeric_mul_opt_error, found);
820
821 case jpiDiv:
822 return executeBinaryArithmExpr(cxt, jsp, jb,
823 numeric_div_opt_error, found);
824
825 case jpiMod:
826 return executeBinaryArithmExpr(cxt, jsp, jb,
827 numeric_mod_opt_error, found);
828
829 case jpiPlus:
830 return executeUnaryArithmExpr(cxt, jsp, jb, NULL, found);
831
832 case jpiMinus:
833 return executeUnaryArithmExpr(cxt, jsp, jb, numeric_uminus,
834 found);
835
836 case jpiAnyArray:
837 if (JsonbType(jb) == jbvArray)
838 {
839 bool hasNext = jspGetNext(jsp, &elem);
840
841 res = executeItemUnwrapTargetArray(cxt, hasNext ? &elem : NULL,
842 jb, found, jspAutoUnwrap(cxt));
843 }
844 else if (jspAutoWrap(cxt))
845 res = executeNextItem(cxt, jsp, NULL, jb, found, true);
846 else if (!jspIgnoreStructuralErrors(cxt))
847 RETURN_ERROR(ereport(ERROR,
848 (errcode(ERRCODE_SQL_JSON_ARRAY_NOT_FOUND),
849 errmsg("jsonpath wildcard array accessor can only be applied to an array"))));
850 break;
851
852 case jpiAnyKey:
853 if (JsonbType(jb) == jbvObject)
854 {
855 bool hasNext = jspGetNext(jsp, &elem);
856
857 if (jb->type != jbvBinary)
858 elog(ERROR, "invalid jsonb object type: %d", jb->type);
859
860 return executeAnyItem
861 (cxt, hasNext ? &elem : NULL,
862 jb->val.binary.data, found, 1, 1, 1,
863 false, jspAutoUnwrap(cxt));
864 }
865 else if (unwrap && JsonbType(jb) == jbvArray)
866 return executeItemUnwrapTargetArray(cxt, jsp, jb, found, false);
867 else if (!jspIgnoreStructuralErrors(cxt))
868 {
869 Assert(found);
870 RETURN_ERROR(ereport(ERROR,
871 (errcode(ERRCODE_SQL_JSON_OBJECT_NOT_FOUND),
872 errmsg("jsonpath wildcard member accessor can only be applied to an object"))));
873 }
874 break;
875
876 case jpiIndexArray:
877 if (JsonbType(jb) == jbvArray || jspAutoWrap(cxt))
878 {
879 int innermostArraySize = cxt->innermostArraySize;
880 int i;
881 int size = JsonbArraySize(jb);
882 bool singleton = size < 0;
883 bool hasNext = jspGetNext(jsp, &elem);
884
885 if (singleton)
886 size = 1;
887
888 cxt->innermostArraySize = size; /* for LAST evaluation */
889
890 for (i = 0; i < jsp->content.array.nelems; i++)
891 {
892 JsonPathItem from;
893 JsonPathItem to;
894 int32 index;
895 int32 index_from;
896 int32 index_to;
897 bool range = jspGetArraySubscript(jsp, &from,
898 &to, i);
899
900 res = getArrayIndex(cxt, &from, jb, &index_from);
901
902 if (jperIsError(res))
903 break;
904
905 if (range)
906 {
907 res = getArrayIndex(cxt, &to, jb, &index_to);
908
909 if (jperIsError(res))
910 break;
911 }
912 else
913 index_to = index_from;
914
915 if (!jspIgnoreStructuralErrors(cxt) &&
916 (index_from < 0 ||
917 index_from > index_to ||
918 index_to >= size))
919 RETURN_ERROR(ereport(ERROR,
920 (errcode(ERRCODE_INVALID_SQL_JSON_SUBSCRIPT),
921 errmsg("jsonpath array subscript is out of bounds"))));
922
923 if (index_from < 0)
924 index_from = 0;
925
926 if (index_to >= size)
927 index_to = size - 1;
928
929 res = jperNotFound;
930
931 for (index = index_from; index <= index_to; index++)
932 {
933 JsonbValue *v;
934 bool copy;
935
936 if (singleton)
937 {
938 v = jb;
939 copy = true;
940 }
941 else
942 {
943 v = getIthJsonbValueFromContainer(jb->val.binary.data,
944 (uint32) index);
945
946 if (v == NULL)
947 continue;
948
949 copy = false;
950 }
951
952 if (!hasNext && !found)
953 return jperOk;
954
955 res = executeNextItem(cxt, jsp, &elem, v, found,
956 copy);
957
958 if (jperIsError(res))
959 break;
960
961 if (res == jperOk && !found)
962 break;
963 }
964
965 if (jperIsError(res))
966 break;
967
968 if (res == jperOk && !found)
969 break;
970 }
971
972 cxt->innermostArraySize = innermostArraySize;
973 }
974 else if (!jspIgnoreStructuralErrors(cxt))
975 {
976 RETURN_ERROR(ereport(ERROR,
977 (errcode(ERRCODE_SQL_JSON_ARRAY_NOT_FOUND),
978 errmsg("jsonpath array accessor can only be applied to an array"))));
979 }
980 break;
981
982 case jpiAny:
983 {
984 bool hasNext = jspGetNext(jsp, &elem);
985
986 /* first try without any intermediate steps */
987 if (jsp->content.anybounds.first == 0)
988 {
989 bool savedIgnoreStructuralErrors;
990
991 savedIgnoreStructuralErrors = cxt->ignoreStructuralErrors;
992 cxt->ignoreStructuralErrors = true;
993 res = executeNextItem(cxt, jsp, &elem,
994 jb, found, true);
995 cxt->ignoreStructuralErrors = savedIgnoreStructuralErrors;
996
997 if (res == jperOk && !found)
998 break;
999 }
1000
1001 if (jb->type == jbvBinary)
1002 res = executeAnyItem
1003 (cxt, hasNext ? &elem : NULL,
1004 jb->val.binary.data, found,
1005 1,
1006 jsp->content.anybounds.first,
1007 jsp->content.anybounds.last,
1008 true, jspAutoUnwrap(cxt));
1009 break;
1010 }
1011
1012 case jpiKey:
1013 if (JsonbType(jb) == jbvObject)
1014 {
1015 JsonbValue *v;
1016 JsonbValue key;
1017
1018 key.type = jbvString;
1019 key.val.string.val = jspGetString(jsp, &key.val.string.len);
1020
1021 v = findJsonbValueFromContainer(jb->val.binary.data,
1022 JB_FOBJECT, &key);
1023
1024 if (v != NULL)
1025 {
1026 res = executeNextItem(cxt, jsp, NULL,
1027 v, found, false);
1028
1029 /* free value if it was not added to found list */
1030 if (jspHasNext(jsp) || !found)
1031 pfree(v);
1032 }
1033 else if (!jspIgnoreStructuralErrors(cxt))
1034 {
1035 Assert(found);
1036
1037 if (!jspThrowErrors(cxt))
1038 return jperError;
1039
1040 ereport(ERROR,
1041 (errcode(ERRCODE_SQL_JSON_MEMBER_NOT_FOUND), \
1042 errmsg("JSON object does not contain key \"%s\"",
1043 pnstrdup(key.val.string.val,
1044 key.val.string.len))));
1045 }
1046 }
1047 else if (unwrap && JsonbType(jb) == jbvArray)
1048 return executeItemUnwrapTargetArray(cxt, jsp, jb, found, false);
1049 else if (!jspIgnoreStructuralErrors(cxt))
1050 {
1051 Assert(found);
1052 RETURN_ERROR(ereport(ERROR,
1053 (errcode(ERRCODE_SQL_JSON_MEMBER_NOT_FOUND),
1054 errmsg("jsonpath member accessor can only be applied to an object"))));
1055 }
1056 break;
1057
1058 case jpiCurrent:
1059 res = executeNextItem(cxt, jsp, NULL, cxt->current,
1060 found, true);
1061 break;
1062
1063 case jpiRoot:
1064 jb = cxt->root;
1065 baseObject = setBaseObject(cxt, jb, 0);
1066 res = executeNextItem(cxt, jsp, NULL, jb, found, true);
1067 cxt->baseObject = baseObject;
1068 break;
1069
1070 case jpiFilter:
1071 {
1072 JsonPathBool st;
1073
1074 if (unwrap && JsonbType(jb) == jbvArray)
1075 return executeItemUnwrapTargetArray(cxt, jsp, jb, found,
1076 false);
1077
1078 jspGetArg(jsp, &elem);
1079 st = executeNestedBoolItem(cxt, &elem, jb);
1080 if (st != jpbTrue)
1081 res = jperNotFound;
1082 else
1083 res = executeNextItem(cxt, jsp, NULL,
1084 jb, found, true);
1085 break;
1086 }
1087
1088 case jpiType:
1089 {
1090 JsonbValue *jbv = palloc(sizeof(*jbv));
1091
1092 jbv->type = jbvString;
1093 jbv->val.string.val = pstrdup(JsonbTypeName(jb));
1094 jbv->val.string.len = strlen(jbv->val.string.val);
1095
1096 res = executeNextItem(cxt, jsp, NULL, jbv,
1097 found, false);
1098 }
1099 break;
1100
1101 case jpiSize:
1102 {
1103 int size = JsonbArraySize(jb);
1104
1105 if (size < 0)
1106 {
1107 if (!jspAutoWrap(cxt))
1108 {
1109 if (!jspIgnoreStructuralErrors(cxt))
1110 RETURN_ERROR(ereport(ERROR,
1111 (errcode(ERRCODE_SQL_JSON_ARRAY_NOT_FOUND),
1112 errmsg("jsonpath item method .%s() can only be applied to an array",
1113 jspOperationName(jsp->type)))));
1114 break;
1115 }
1116
1117 size = 1;
1118 }
1119
1120 jb = palloc(sizeof(*jb));
1121
1122 jb->type = jbvNumeric;
1123 jb->val.numeric = int64_to_numeric(size);
1124
1125 res = executeNextItem(cxt, jsp, NULL, jb, found, false);
1126 }
1127 break;
1128
1129 case jpiAbs:
1130 return executeNumericItemMethod(cxt, jsp, jb, unwrap, numeric_abs,
1131 found);
1132
1133 case jpiFloor:
1134 return executeNumericItemMethod(cxt, jsp, jb, unwrap, numeric_floor,
1135 found);
1136
1137 case jpiCeiling:
1138 return executeNumericItemMethod(cxt, jsp, jb, unwrap, numeric_ceil,
1139 found);
1140
1141 case jpiDouble:
1142 {
1143 JsonbValue jbv;
1144
1145 if (unwrap && JsonbType(jb) == jbvArray)
1146 return executeItemUnwrapTargetArray(cxt, jsp, jb, found,
1147 false);
1148
1149 if (jb->type == jbvNumeric)
1150 {
1151 char *tmp = DatumGetCString(DirectFunctionCall1(numeric_out,
1152 NumericGetDatum(jb->val.numeric)));
1153 double val;
1154 ErrorSaveContext escontext = {T_ErrorSaveContext};
1155
1156 val = float8in_internal(tmp,
1157 NULL,
1158 "double precision",
1159 tmp,
1160 (Node *) &escontext);
1161
1162 if (escontext.error_occurred)
1163 RETURN_ERROR(ereport(ERROR,
1164 (errcode(ERRCODE_NON_NUMERIC_SQL_JSON_ITEM),
1165 errmsg("argument \"%s\" of jsonpath item method .%s() is invalid for type %s",
1166 tmp, jspOperationName(jsp->type), "double precision"))));
1167 if (isinf(val) || isnan(val))
1168 RETURN_ERROR(ereport(ERROR,
1169 (errcode(ERRCODE_NON_NUMERIC_SQL_JSON_ITEM),
1170 errmsg("NaN or Infinity is not allowed for jsonpath item method .%s()",
1171 jspOperationName(jsp->type)))));
1172 res = jperOk;
1173 }
1174 else if (jb->type == jbvString)
1175 {
1176 /* cast string as double */
1177 double val;
1178 char *tmp = pnstrdup(jb->val.string.val,
1179 jb->val.string.len);
1180 ErrorSaveContext escontext = {T_ErrorSaveContext};
1181
1182 val = float8in_internal(tmp,
1183 NULL,
1184 "double precision",
1185 tmp,
1186 (Node *) &escontext);
1187
1188 if (escontext.error_occurred)
1189 RETURN_ERROR(ereport(ERROR,
1190 (errcode(ERRCODE_NON_NUMERIC_SQL_JSON_ITEM),
1191 errmsg("argument \"%s\" of jsonpath item method .%s() is invalid for type %s",
1192 tmp, jspOperationName(jsp->type), "double precision"))));
1193 if (isinf(val) || isnan(val))
1194 RETURN_ERROR(ereport(ERROR,
1195 (errcode(ERRCODE_NON_NUMERIC_SQL_JSON_ITEM),
1196 errmsg("NaN or Infinity is not allowed for jsonpath item method .%s()",
1197 jspOperationName(jsp->type)))));
1198
1199 jb = &jbv;
1200 jb->type = jbvNumeric;
1201 jb->val.numeric = DatumGetNumeric(DirectFunctionCall1(float8_numeric,
1202 Float8GetDatum(val)));
1203 res = jperOk;
1204 }
1205
1206 if (res == jperNotFound)
1207 RETURN_ERROR(ereport(ERROR,
1208 (errcode(ERRCODE_NON_NUMERIC_SQL_JSON_ITEM),
1209 errmsg("jsonpath item method .%s() can only be applied to a string or numeric value",
1210 jspOperationName(jsp->type)))));
1211
1212 res = executeNextItem(cxt, jsp, NULL, jb, found, true);
1213 }
1214 break;
1215
1216 case jpiDatetime:
1217 case jpiDate:
1218 case jpiTime:
1219 case jpiTimeTz:
1220 case jpiTimestamp:
1221 case jpiTimestampTz:
1222 if (unwrap && JsonbType(jb) == jbvArray)
1223 return executeItemUnwrapTargetArray(cxt, jsp, jb, found, false);
1224
1225 return executeDateTimeMethod(cxt, jsp, jb, found);
1226
1227 case jpiKeyValue:
1228 if (unwrap && JsonbType(jb) == jbvArray)
1229 return executeItemUnwrapTargetArray(cxt, jsp, jb, found, false);
1230
1231 return executeKeyValueMethod(cxt, jsp, jb, found);
1232
1233 case jpiLast:
1234 {
1235 JsonbValue tmpjbv;
1236 JsonbValue *lastjbv;
1237 int last;
1238 bool hasNext = jspGetNext(jsp, &elem);
1239
1240 if (cxt->innermostArraySize < 0)
1241 elog(ERROR, "evaluating jsonpath LAST outside of array subscript");
1242
1243 if (!hasNext && !found)
1244 {
1245 res = jperOk;
1246 break;
1247 }
1248
1249 last = cxt->innermostArraySize - 1;
1250
1251 lastjbv = hasNext ? &tmpjbv : palloc(sizeof(*lastjbv));
1252
1253 lastjbv->type = jbvNumeric;
1254 lastjbv->val.numeric = int64_to_numeric(last);
1255
1256 res = executeNextItem(cxt, jsp, &elem,
1257 lastjbv, found, hasNext);
1258 }
1259 break;
1260
1261 case jpiBigint:
1262 {
1263 JsonbValue jbv;
1264 Datum datum;
1265
1266 if (unwrap && JsonbType(jb) == jbvArray)
1267 return executeItemUnwrapTargetArray(cxt, jsp, jb, found,
1268 false);
1269
1270 if (jb->type == jbvNumeric)
1271 {
1272 bool have_error;
1273 int64 val;
1274
1275 val = numeric_int8_opt_error(jb->val.numeric, &have_error);
1276 if (have_error)
1277 RETURN_ERROR(ereport(ERROR,
1278 (errcode(ERRCODE_NON_NUMERIC_SQL_JSON_ITEM),
1279 errmsg("argument \"%s\" of jsonpath item method .%s() is invalid for type %s",
1280 DatumGetCString(DirectFunctionCall1(numeric_out,
1281 NumericGetDatum(jb->val.numeric))),
1282 jspOperationName(jsp->type),
1283 "bigint"))));
1284
1285 datum = Int64GetDatum(val);
1286 res = jperOk;
1287 }
1288 else if (jb->type == jbvString)
1289 {
1290 /* cast string as bigint */
1291 char *tmp = pnstrdup(jb->val.string.val,
1292 jb->val.string.len);
1293 ErrorSaveContext escontext = {T_ErrorSaveContext};
1294 bool noerr;
1295
1296 noerr = DirectInputFunctionCallSafe(int8in, tmp,
1297 InvalidOid, -1,
1298 (Node *) &escontext,
1299 &datum);
1300
1301 if (!noerr || escontext.error_occurred)
1302 RETURN_ERROR(ereport(ERROR,
1303 (errcode(ERRCODE_NON_NUMERIC_SQL_JSON_ITEM),
1304 errmsg("argument \"%s\" of jsonpath item method .%s() is invalid for type %s",
1305 tmp, jspOperationName(jsp->type), "bigint"))));
1306 res = jperOk;
1307 }
1308
1309 if (res == jperNotFound)
1310 RETURN_ERROR(ereport(ERROR,
1311 (errcode(ERRCODE_NON_NUMERIC_SQL_JSON_ITEM),
1312 errmsg("jsonpath item method .%s() can only be applied to a string or numeric value",
1313 jspOperationName(jsp->type)))));
1314
1315 jb = &jbv;
1316 jb->type = jbvNumeric;
1317 jb->val.numeric = DatumGetNumeric(DirectFunctionCall1(int8_numeric,
1318 datum));
1319
1320 res = executeNextItem(cxt, jsp, NULL, jb, found, true);
1321 }
1322 break;
1323
1324 case jpiBoolean:
1325 {
1326 JsonbValue jbv;
1327 bool bval;
1328
1329 if (unwrap && JsonbType(jb) == jbvArray)
1330 return executeItemUnwrapTargetArray(cxt, jsp, jb, found,
1331 false);
1332
1333 if (jb->type == jbvBool)
1334 {
1335 bval = jb->val.boolean;
1336
1337 res = jperOk;
1338 }
1339 else if (jb->type == jbvNumeric)
1340 {
1341 int ival;
1342 Datum datum;
1343 bool noerr;
1344 char *tmp = DatumGetCString(DirectFunctionCall1(numeric_out,
1345 NumericGetDatum(jb->val.numeric)));
1346 ErrorSaveContext escontext = {T_ErrorSaveContext};
1347
1348 noerr = DirectInputFunctionCallSafe(int4in, tmp,
1349 InvalidOid, -1,
1350 (Node *) &escontext,
1351 &datum);
1352
1353 if (!noerr || escontext.error_occurred)
1354 RETURN_ERROR(ereport(ERROR,
1355 (errcode(ERRCODE_NON_NUMERIC_SQL_JSON_ITEM),
1356 errmsg("argument \"%s\" of jsonpath item method .%s() is invalid for type %s",
1357 tmp, jspOperationName(jsp->type), "boolean"))));
1358
1359 ival = DatumGetInt32(datum);
1360 if (ival == 0)
1361 bval = false;
1362 else
1363 bval = true;
1364
1365 res = jperOk;
1366 }
1367 else if (jb->type == jbvString)
1368 {
1369 /* cast string as boolean */
1370 char *tmp = pnstrdup(jb->val.string.val,
1371 jb->val.string.len);
1372
1373 if (!parse_bool(tmp, &bval))
1374 RETURN_ERROR(ereport(ERROR,
1375 (errcode(ERRCODE_NON_NUMERIC_SQL_JSON_ITEM),
1376 errmsg("argument \"%s\" of jsonpath item method .%s() is invalid for type %s",
1377 tmp, jspOperationName(jsp->type), "boolean"))));
1378
1379 res = jperOk;
1380 }
1381
1382 if (res == jperNotFound)
1383 RETURN_ERROR(ereport(ERROR,
1384 (errcode(ERRCODE_NON_NUMERIC_SQL_JSON_ITEM),
1385 errmsg("jsonpath item method .%s() can only be applied to a boolean, string, or numeric value",
1386 jspOperationName(jsp->type)))));
1387
1388 jb = &jbv;
1389 jb->type = jbvBool;
1390 jb->val.boolean = bval;
1391
1392 res = executeNextItem(cxt, jsp, NULL, jb, found, true);
1393 }
1394 break;
1395
1396 case jpiDecimal:
1397 case jpiNumber:
1398 {
1399 JsonbValue jbv;
1400 Numeric num;
1401 char *numstr = NULL;
1402
1403 if (unwrap && JsonbType(jb) == jbvArray)
1404 return executeItemUnwrapTargetArray(cxt, jsp, jb, found,
1405 false);
1406
1407 if (jb->type == jbvNumeric)
1408 {
1409 num = jb->val.numeric;
1410 if (numeric_is_nan(num) || numeric_is_inf(num))
1411 RETURN_ERROR(ereport(ERROR,
1412 (errcode(ERRCODE_NON_NUMERIC_SQL_JSON_ITEM),
1413 errmsg("NaN or Infinity is not allowed for jsonpath item method .%s()",
1414 jspOperationName(jsp->type)))));
1415
1416 if (jsp->type == jpiDecimal)
1417 numstr = DatumGetCString(DirectFunctionCall1(numeric_out,
1418 NumericGetDatum(num)));
1419 res = jperOk;
1420 }
1421 else if (jb->type == jbvString)
1422 {
1423 /* cast string as number */
1424 Datum datum;
1425 bool noerr;
1426 ErrorSaveContext escontext = {T_ErrorSaveContext};
1427
1428 numstr = pnstrdup(jb->val.string.val, jb->val.string.len);
1429
1430 noerr = DirectInputFunctionCallSafe(numeric_in, numstr,
1431 InvalidOid, -1,
1432 (Node *) &escontext,
1433 &datum);
1434
1435 if (!noerr || escontext.error_occurred)
1436 RETURN_ERROR(ereport(ERROR,
1437 (errcode(ERRCODE_NON_NUMERIC_SQL_JSON_ITEM),
1438 errmsg("argument \"%s\" of jsonpath item method .%s() is invalid for type %s",
1439 numstr, jspOperationName(jsp->type), "numeric"))));
1440
1441 num = DatumGetNumeric(datum);
1442 if (numeric_is_nan(num) || numeric_is_inf(num))
1443 RETURN_ERROR(ereport(ERROR,
1444 (errcode(ERRCODE_NON_NUMERIC_SQL_JSON_ITEM),
1445 errmsg("NaN or Infinity is not allowed for jsonpath item method .%s()",
1446 jspOperationName(jsp->type)))));
1447
1448 res = jperOk;
1449 }
1450
1451 if (res == jperNotFound)
1452 RETURN_ERROR(ereport(ERROR,
1453 (errcode(ERRCODE_NON_NUMERIC_SQL_JSON_ITEM),
1454 errmsg("jsonpath item method .%s() can only be applied to a string or numeric value",
1455 jspOperationName(jsp->type)))));
1456
1457 /*
1458 * If we have arguments, then they must be the precision and
1459 * optional scale used in .decimal(). Convert them to the
1460 * typmod equivalent and then truncate the numeric value per
1461 * this typmod details.
1462 */
1463 if (jsp->type == jpiDecimal && jsp->content.args.left)
1464 {
1465 Datum numdatum;
1466 int32 dtypmod;
1467 int32 precision;
1468 int32 scale = 0;
1469 bool have_error;
1470 bool noerr;
1471 ErrorSaveContext escontext = {T_ErrorSaveContext};
1472
1473 jspGetLeftArg(jsp, &elem);
1474 if (elem.type != jpiNumeric)
1475 elog(ERROR, "invalid jsonpath item type for .decimal() precision");
1476
1477 precision = numeric_int4_opt_error(jspGetNumeric(&elem),
1478 &have_error);
1479 if (have_error)
1480 RETURN_ERROR(ereport(ERROR,
1481 (errcode(ERRCODE_NON_NUMERIC_SQL_JSON_ITEM),
1482 errmsg("precision of jsonpath item method .%s() is out of range for type integer",
1483 jspOperationName(jsp->type)))));
1484
1485 if (jsp->content.args.right)
1486 {
1487 jspGetRightArg(jsp, &elem);
1488 if (elem.type != jpiNumeric)
1489 elog(ERROR, "invalid jsonpath item type for .decimal() scale");
1490
1491 scale = numeric_int4_opt_error(jspGetNumeric(&elem),
1492 &have_error);
1493 if (have_error)
1494 RETURN_ERROR(ereport(ERROR,
1495 (errcode(ERRCODE_NON_NUMERIC_SQL_JSON_ITEM),
1496 errmsg("scale of jsonpath item method .%s() is out of range for type integer",
1497 jspOperationName(jsp->type)))));
1498 }
1499
1500 /* Pack the precision and scale into a numeric typmod */
1501 dtypmod = make_numeric_typmod_safe(precision, scale,
1502 jspThrowErrors(cxt) ? NULL : (Node *) &escontext);
1503 if (escontext.error_occurred)
1504 return jperError;
1505
1506 /* Convert numstr to Numeric with typmod */
1507 Assert(numstr != NULL);
1508 noerr = DirectInputFunctionCallSafe(numeric_in, numstr,
1509 InvalidOid, dtypmod,
1510 (Node *) &escontext,
1511 &numdatum);
1512
1513 if (!noerr || escontext.error_occurred)
1514 RETURN_ERROR(ereport(ERROR,
1515 (errcode(ERRCODE_NON_NUMERIC_SQL_JSON_ITEM),
1516 errmsg("argument \"%s\" of jsonpath item method .%s() is invalid for type %s",
1517 numstr, jspOperationName(jsp->type), "numeric"))));
1518
1519 num = DatumGetNumeric(numdatum);
1520 }
1521
1522 jb = &jbv;
1523 jb->type = jbvNumeric;
1524 jb->val.numeric = num;
1525
1526 res = executeNextItem(cxt, jsp, NULL, jb, found, true);
1527 }
1528 break;
1529
1530 case jpiInteger:
1531 {
1532 JsonbValue jbv;
1533 Datum datum;
1534
1535 if (unwrap && JsonbType(jb) == jbvArray)
1536 return executeItemUnwrapTargetArray(cxt, jsp, jb, found,
1537 false);
1538
1539 if (jb->type == jbvNumeric)
1540 {
1541 bool have_error;
1542 int32 val;
1543
1544 val = numeric_int4_opt_error(jb->val.numeric, &have_error);
1545 if (have_error)
1546 RETURN_ERROR(ereport(ERROR,
1547 (errcode(ERRCODE_NON_NUMERIC_SQL_JSON_ITEM),
1548 errmsg("argument \"%s\" of jsonpath item method .%s() is invalid for type %s",
1549 DatumGetCString(DirectFunctionCall1(numeric_out,
1550 NumericGetDatum(jb->val.numeric))),
1551 jspOperationName(jsp->type), "integer"))));
1552
1553 datum = Int32GetDatum(val);
1554 res = jperOk;
1555 }
1556 else if (jb->type == jbvString)
1557 {
1558 /* cast string as integer */
1559 char *tmp = pnstrdup(jb->val.string.val,
1560 jb->val.string.len);
1561 ErrorSaveContext escontext = {T_ErrorSaveContext};
1562 bool noerr;
1563
1564 noerr = DirectInputFunctionCallSafe(int4in, tmp,
1565 InvalidOid, -1,
1566 (Node *) &escontext,
1567 &datum);
1568
1569 if (!noerr || escontext.error_occurred)
1570 RETURN_ERROR(ereport(ERROR,
1571 (errcode(ERRCODE_NON_NUMERIC_SQL_JSON_ITEM),
1572 errmsg("argument \"%s\" of jsonpath item method .%s() is invalid for type %s",
1573 tmp, jspOperationName(jsp->type), "integer"))));
1574 res = jperOk;
1575 }
1576
1577 if (res == jperNotFound)
1578 RETURN_ERROR(ereport(ERROR,
1579 (errcode(ERRCODE_NON_NUMERIC_SQL_JSON_ITEM),
1580 errmsg("jsonpath item method .%s() can only be applied to a string or numeric value",
1581 jspOperationName(jsp->type)))));
1582
1583 jb = &jbv;
1584 jb->type = jbvNumeric;
1585 jb->val.numeric = DatumGetNumeric(DirectFunctionCall1(int4_numeric,
1586 datum));
1587
1588 res = executeNextItem(cxt, jsp, NULL, jb, found, true);
1589 }
1590 break;
1591
1592 case jpiStringFunc:
1593 {
1594 JsonbValue jbv;
1595 char *tmp = NULL;
1596
1597 if (unwrap && JsonbType(jb) == jbvArray)
1598 return executeItemUnwrapTargetArray(cxt, jsp, jb, found, false);
1599
1600 switch (JsonbType(jb))
1601 {
1602 case jbvString:
1603
1604 /*
1605 * Value is not necessarily null-terminated, so we do
1606 * pnstrdup() here.
1607 */
1608 tmp = pnstrdup(jb->val.string.val,
1609 jb->val.string.len);
1610 break;
1611 case jbvNumeric:
1612 tmp = DatumGetCString(DirectFunctionCall1(numeric_out,
1613 NumericGetDatum(jb->val.numeric)));
1614 break;
1615 case jbvBool:
1616 tmp = (jb->val.boolean) ? "true" : "false";
1617 break;
1618 case jbvDatetime:
1619 {
1620 char buf[MAXDATELEN + 1];
1621
1622 JsonEncodeDateTime(buf,
1623 jb->val.datetime.value,
1624 jb->val.datetime.typid,
1625 &jb->val.datetime.tz);
1626 tmp = pstrdup(buf);
1627 }
1628 break;
1629 case jbvNull:
1630 case jbvArray:
1631 case jbvObject:
1632 case jbvBinary:
1633 RETURN_ERROR(ereport(ERROR,
1634 (errcode(ERRCODE_NON_NUMERIC_SQL_JSON_ITEM),
1635 errmsg("jsonpath item method .%s() can only be applied to a boolean, string, numeric, or datetime value",
1636 jspOperationName(jsp->type)))));
1637 break;
1638 }
1639
1640 jb = &jbv;
1641 Assert(tmp != NULL); /* We must have set tmp above */
1642 jb->val.string.val = tmp;
1643 jb->val.string.len = strlen(jb->val.string.val);
1644 jb->type = jbvString;
1645
1646 res = executeNextItem(cxt, jsp, NULL, jb, found, true);
1647 }
1648 break;
1649
1650 default:
1651 elog(ERROR, "unrecognized jsonpath item type: %d", jsp->type);
1652 }
1653
1654 return res;
1655 }
1656
1657 /*
1658 * Unwrap current array item and execute jsonpath for each of its elements.
1659 */
1660 static JsonPathExecResult
1661 executeItemUnwrapTargetArray(JsonPathExecContext *cxt, JsonPathItem *jsp,
1662 JsonbValue *jb, JsonValueList *found,
1663 bool unwrapElements)
1664 {
1665 if (jb->type != jbvBinary)
1666 {
1667 Assert(jb->type != jbvArray);
1668 elog(ERROR, "invalid jsonb array value type: %d", jb->type);
1669 }
1670
1671 return executeAnyItem
1672 (cxt, jsp, jb->val.binary.data, found, 1, 1, 1,
1673 false, unwrapElements);
1674 }
1675
1676 /*
1677 * Execute next jsonpath item if exists. Otherwise put "v" to the "found"
1678 * list if provided.
1679 */
1680 static JsonPathExecResult
1681 executeNextItem(JsonPathExecContext *cxt,
1682 JsonPathItem *cur, JsonPathItem *next,
1683 JsonbValue *v, JsonValueList *found, bool copy)
1684 {
1685 JsonPathItem elem;
1686 bool hasNext;
1687
1688 if (!cur)
1689 hasNext = next != NULL;
1690 else if (next)
1691 hasNext = jspHasNext(cur);
1692 else
1693 {
1694 next = &elem;
1695 hasNext = jspGetNext(cur, next);
1696 }
1697
1698 if (hasNext)
1699 return executeItem(cxt, next, v, found);
1700
1701 if (found)
1702 JsonValueListAppend(found, copy ? copyJsonbValue(v) : v);
1703
1704 return jperOk;
1705 }
1706
1707 /*
1708 * Same as executeItem(), but when "unwrap == true" automatically unwraps
1709 * each array item from the resulting sequence in lax mode.
1710 */
1711 static JsonPathExecResult
1712 executeItemOptUnwrapResult(JsonPathExecContext *cxt, JsonPathItem *jsp,
1713 JsonbValue *jb, bool unwrap,
1714 JsonValueList *found)
1715 {
1716 if (unwrap && jspAutoUnwrap(cxt))
1717 {
1718 JsonValueList seq = {0};
1719 JsonValueListIterator it;
1720 JsonPathExecResult res = executeItem(cxt, jsp, jb, &seq);
1721 JsonbValue *item;
1722
1723 if (jperIsError(res))
1724 return res;
1725
1726 JsonValueListInitIterator(&seq, &it);
1727 while ((item = JsonValueListNext(&seq, &it)))
1728 {
1729 Assert(item->type != jbvArray);
1730
1731 if (JsonbType(item) == jbvArray)
1732 executeItemUnwrapTargetArray(cxt, NULL, item, found, false);
1733 else
1734 JsonValueListAppend(found, item);
1735 }
1736
1737 return jperOk;
1738 }
1739
1740 return executeItem(cxt, jsp, jb, found);
1741 }
1742
1743 /*
1744 * Same as executeItemOptUnwrapResult(), but with error suppression.
1745 */
1746 static JsonPathExecResult
1747 executeItemOptUnwrapResultNoThrow(JsonPathExecContext *cxt,
1748 JsonPathItem *jsp,
1749 JsonbValue *jb, bool unwrap,
1750 JsonValueList *found)
1751 {
1752 JsonPathExecResult res;
1753 bool throwErrors = cxt->throwErrors;
1754
1755 cxt->throwErrors = false;
1756 res = executeItemOptUnwrapResult(cxt, jsp, jb, unwrap, found);
1757 cxt->throwErrors = throwErrors;
1758
1759 return res;
1760 }
1761
1762 /* Execute boolean-valued jsonpath expression. */
1763 static JsonPathBool
1764 executeBoolItem(JsonPathExecContext *cxt, JsonPathItem *jsp,
1765 JsonbValue *jb, bool canHaveNext)
1766 {
1767 JsonPathItem larg;
1768 JsonPathItem rarg;
1769 JsonPathBool res;
1770 JsonPathBool res2;
1771
1772 /* since this function recurses, it could be driven to stack overflow */
1773 check_stack_depth();
1774
1775 if (!canHaveNext && jspHasNext(jsp))
1776 elog(ERROR, "boolean jsonpath item cannot have next item");
1777
1778 switch (jsp->type)
1779 {
1780 case jpiAnd:
1781 jspGetLeftArg(jsp, &larg);
1782 res = executeBoolItem(cxt, &larg, jb, false);
1783
1784 if (res == jpbFalse)
1785 return jpbFalse;
1786
1787 /*
1788 * SQL/JSON says that we should check second arg in case of
1789 * jperError
1790 */
1791
1792 jspGetRightArg(jsp, &rarg);
1793 res2 = executeBoolItem(cxt, &rarg, jb, false);
1794
1795 return res2 == jpbTrue ? res : res2;
1796
1797 case jpiOr:
1798 jspGetLeftArg(jsp, &larg);
1799 res = executeBoolItem(cxt, &larg, jb, false);
1800
1801 if (res == jpbTrue)
1802 return jpbTrue;
1803
1804 jspGetRightArg(jsp, &rarg);
1805 res2 = executeBoolItem(cxt, &rarg, jb, false);
1806
1807 return res2 == jpbFalse ? res : res2;
1808
1809 case jpiNot:
1810 jspGetArg(jsp, &larg);
1811
1812 res = executeBoolItem(cxt, &larg, jb, false);
1813
1814 if (res == jpbUnknown)
1815 return jpbUnknown;
1816
1817 return res == jpbTrue ? jpbFalse : jpbTrue;
1818
1819 case jpiIsUnknown:
1820 jspGetArg(jsp, &larg);
1821 res = executeBoolItem(cxt, &larg, jb, false);
1822 return res == jpbUnknown ? jpbTrue : jpbFalse;
1823
1824 case jpiEqual:
1825 case jpiNotEqual:
1826 case jpiLess:
1827 case jpiGreater:
1828 case jpiLessOrEqual:
1829 case jpiGreaterOrEqual:
1830 jspGetLeftArg(jsp, &larg);
1831 jspGetRightArg(jsp, &rarg);
1832 return executePredicate(cxt, jsp, &larg, &rarg, jb, true,
1833 executeComparison, cxt);
1834
1835 case jpiStartsWith: /* 'whole STARTS WITH initial' */
1836 jspGetLeftArg(jsp, &larg); /* 'whole' */
1837 jspGetRightArg(jsp, &rarg); /* 'initial' */
1838 return executePredicate(cxt, jsp, &larg, &rarg, jb, false,
1839 executeStartsWith, NULL);
1840
1841 case jpiLikeRegex: /* 'expr LIKE_REGEX pattern FLAGS flags' */
1842 {
1843 /*
1844 * 'expr' is a sequence-returning expression. 'pattern' is a
1845 * regex string literal. SQL/JSON standard requires XQuery
1846 * regexes, but we use Postgres regexes here. 'flags' is a
1847 * string literal converted to integer flags at compile-time.
1848 */
1849 JsonLikeRegexContext lrcxt = {0};
1850
1851 jspInitByBuffer(&larg, jsp->base,
1852 jsp->content.like_regex.expr);
1853
1854 return executePredicate(cxt, jsp, &larg, NULL, jb, false,
1855 executeLikeRegex, &lrcxt);
1856 }
1857
1858 case jpiExists:
1859 jspGetArg(jsp, &larg);
1860
1861 if (jspStrictAbsenceOfErrors(cxt))
1862 {
1863 /*
1864 * In strict mode we must get a complete list of values to
1865 * check that there are no errors at all.
1866 */
1867 JsonValueList vals = {0};
1868 JsonPathExecResult res =
1869 executeItemOptUnwrapResultNoThrow(cxt, &larg, jb,
1870 false, &vals);
1871
1872 if (jperIsError(res))
1873 return jpbUnknown;
1874
1875 return JsonValueListIsEmpty(&vals) ? jpbFalse : jpbTrue;
1876 }
1877 else
1878 {
1879 JsonPathExecResult res =
1880 executeItemOptUnwrapResultNoThrow(cxt, &larg, jb,
1881 false, NULL);
1882
1883 if (jperIsError(res))
1884 return jpbUnknown;
1885
1886 return res == jperOk ? jpbTrue : jpbFalse;
1887 }
1888
1889 default:
1890 elog(ERROR, "invalid boolean jsonpath item type: %d", jsp->type);
1891 return jpbUnknown;
1892 }
1893 }
1894
1895 /*
1896 * Execute nested (filters etc.) boolean expression pushing current SQL/JSON
1897 * item onto the stack.
1898 */
1899 static JsonPathBool
1900 executeNestedBoolItem(JsonPathExecContext *cxt, JsonPathItem *jsp,
1901 JsonbValue *jb)
1902 {
1903 JsonbValue *prev;
1904 JsonPathBool res;
1905
1906 prev = cxt->current;
1907 cxt->current = jb;
1908 res = executeBoolItem(cxt, jsp, jb, false);
1909 cxt->current = prev;
1910
1911 return res;
1912 }
1913
1914 /*
1915 * Implementation of several jsonpath nodes:
1916 * - jpiAny (.** accessor),
1917 * - jpiAnyKey (.* accessor),
1918 * - jpiAnyArray ([*] accessor)
1919 */
1920 static JsonPathExecResult
1921 executeAnyItem(JsonPathExecContext *cxt, JsonPathItem *jsp, JsonbContainer *jbc,
1922 JsonValueList *found, uint32 level, uint32 first, uint32 last,
1923 bool ignoreStructuralErrors, bool unwrapNext)
1924 {
1925 JsonPathExecResult res = jperNotFound;
1926 JsonbIterator *it;
1927 int32 r;
1928 JsonbValue v;
1929
1930 check_stack_depth();
1931
1932 if (level > last)
1933 return res;
1934
1935 it = JsonbIteratorInit(jbc);
1936
1937 /*
1938 * Recursively iterate over jsonb objects/arrays
1939 */
1940 while ((r = JsonbIteratorNext(&it, &v, true)) != WJB_DONE)
1941 {
1942 if (r == WJB_KEY)
1943 {
1944 r = JsonbIteratorNext(&it, &v, true);
1945 Assert(r == WJB_VALUE);
1946 }
1947
1948 if (r == WJB_VALUE || r == WJB_ELEM)
1949 {
1950
1951 if (level >= first ||
1952 (first == PG_UINT32_MAX && last == PG_UINT32_MAX &&
1953 v.type != jbvBinary)) /* leaves only requested */
1954 {
1955 /* check expression */
1956 if (jsp)
1957 {
1958 if (ignoreStructuralErrors)
1959 {
1960 bool savedIgnoreStructuralErrors;
1961
1962 savedIgnoreStructuralErrors = cxt->ignoreStructuralErrors;
1963 cxt->ignoreStructuralErrors = true;
1964 res = executeItemOptUnwrapTarget(cxt, jsp, &v, found, unwrapNext);
1965 cxt->ignoreStructuralErrors = savedIgnoreStructuralErrors;
1966 }
1967 else
1968 res = executeItemOptUnwrapTarget(cxt, jsp, &v, found, unwrapNext);
1969
1970 if (jperIsError(res))
1971 break;
1972
1973 if (res == jperOk && !found)
1974 break;
1975 }
1976 else if (found)
1977 JsonValueListAppend(found, copyJsonbValue(&v));
1978 else
1979 return jperOk;
1980 }
1981
1982 if (level < last && v.type == jbvBinary)
1983 {
1984 res = executeAnyItem
1985 (cxt, jsp, v.val.binary.data, found,
1986 level + 1, first, last,
1987 ignoreStructuralErrors, unwrapNext);
1988
1989 if (jperIsError(res))
1990 break;
1991
1992 if (res == jperOk && found == NULL)
1993 break;
1994 }
1995 }
1996 }
1997
1998 return res;
1999 }
2000
2001 /*
2002 * Execute unary or binary predicate.
2003 *
2004 * Predicates have existence semantics, because their operands are item
2005 * sequences. Pairs of items from the left and right operand's sequences are
2006 * checked. TRUE returned only if any pair satisfying the condition is found.
2007 * In strict mode, even if the desired pair has already been found, all pairs
2008 * still need to be examined to check the absence of errors. If any error
2009 * occurs, UNKNOWN (analogous to SQL NULL) is returned.
2010 */
2011 static JsonPathBool
2012 executePredicate(JsonPathExecContext *cxt, JsonPathItem *pred,
2013 JsonPathItem *larg, JsonPathItem *rarg, JsonbValue *jb,
2014 bool unwrapRightArg, JsonPathPredicateCallback exec,
2015 void *param)
2016 {
2017 JsonPathExecResult res;
2018 JsonValueListIterator lseqit;
2019 JsonValueList lseq = {0};
2020 JsonValueList rseq = {0};
2021 JsonbValue *lval;
2022 bool error = false;
2023 bool found = false;
2024
2025 /* Left argument is always auto-unwrapped. */
2026 res = executeItemOptUnwrapResultNoThrow(cxt, larg, jb, true, &lseq);
2027 if (jperIsError(res))
2028 return jpbUnknown;
2029
2030 if (rarg)
2031 {
2032 /* Right argument is conditionally auto-unwrapped. */
2033 res = executeItemOptUnwrapResultNoThrow(cxt, rarg, jb,
2034 unwrapRightArg, &rseq);
2035 if (jperIsError(res))
2036 return jpbUnknown;
2037 }
2038
2039 JsonValueListInitIterator(&lseq, &lseqit);
2040 while ((lval = JsonValueListNext(&lseq, &lseqit)))
2041 {
2042 JsonValueListIterator rseqit;
2043 JsonbValue *rval;
2044 bool first = true;
2045
2046 JsonValueListInitIterator(&rseq, &rseqit);
2047 if (rarg)
2048 rval = JsonValueListNext(&rseq, &rseqit);
2049 else
2050 rval = NULL;
2051
2052 /* Loop over right arg sequence or do single pass otherwise */
2053 while (rarg ? (rval != NULL) : first)
2054 {
2055 JsonPathBool res = exec(pred, lval, rval, param);
2056
2057 if (res == jpbUnknown)
2058 {
2059 if (jspStrictAbsenceOfErrors(cxt))
2060 return jpbUnknown;
2061
2062 error = true;
2063 }
2064 else if (res == jpbTrue)
2065 {
2066 if (!jspStrictAbsenceOfErrors(cxt))
2067 return jpbTrue;
2068
2069 found = true;
2070 }
2071
2072 first = false;
2073 if (rarg)
2074 rval = JsonValueListNext(&rseq, &rseqit);
2075 }
2076 }
2077
2078 if (found) /* possible only in strict mode */
2079 return jpbTrue;
2080
2081 if (error) /* possible only in lax mode */
2082 return jpbUnknown;
2083
2084 return jpbFalse;
2085 }
2086
2087 /*
2088 * Execute binary arithmetic expression on singleton numeric operands.
2089 * Array operands are automatically unwrapped in lax mode.
2090 */
2091 static JsonPathExecResult
2092 executeBinaryArithmExpr(JsonPathExecContext *cxt, JsonPathItem *jsp,
2093 JsonbValue *jb, BinaryArithmFunc func,
2094 JsonValueList *found)
2095 {
2096 JsonPathExecResult jper;
2097 JsonPathItem elem;
2098 JsonValueList lseq = {0};
2099 JsonValueList rseq = {0};
2100 JsonbValue *lval;
2101 JsonbValue *rval;
2102 Numeric res;
2103
2104 jspGetLeftArg(jsp, &elem);
2105
2106 /*
2107 * XXX: By standard only operands of multiplicative expressions are
2108 * unwrapped. We extend it to other binary arithmetic expressions too.
2109 */
2110 jper = executeItemOptUnwrapResult(cxt, &elem, jb, true, &lseq);
2111 if (jperIsError(jper))
2112 return jper;
2113
2114 jspGetRightArg(jsp, &elem);
2115
2116 jper = executeItemOptUnwrapResult(cxt, &elem, jb, true, &rseq);
2117 if (jperIsError(jper))
2118 return jper;
2119
2120 if (JsonValueListLength(&lseq) != 1 ||
2121 !(lval = getScalar(JsonValueListHead(&lseq), jbvNumeric)))
2122 RETURN_ERROR(ereport(ERROR,
2123 (errcode(ERRCODE_SINGLETON_SQL_JSON_ITEM_REQUIRED),
2124 errmsg("left operand of jsonpath operator %s is not a single numeric value",
2125 jspOperationName(jsp->type)))));
2126
2127 if (JsonValueListLength(&rseq) != 1 ||
2128 !(rval = getScalar(JsonValueListHead(&rseq), jbvNumeric)))
2129 RETURN_ERROR(ereport(ERROR,
2130 (errcode(ERRCODE_SINGLETON_SQL_JSON_ITEM_REQUIRED),
2131 errmsg("right operand of jsonpath operator %s is not a single numeric value",
2132 jspOperationName(jsp->type)))));
2133
2134 if (jspThrowErrors(cxt))
2135 {
2136 res = func(lval->val.numeric, rval->val.numeric, NULL);
2137 }
2138 else
2139 {
2140 bool error = false;
2141
2142 res = func(lval->val.numeric, rval->val.numeric, &error);
2143
2144 if (error)
2145 return jperError;
2146 }
2147
2148 if (!jspGetNext(jsp, &elem) && !found)
2149 return jperOk;
2150
2151 lval = palloc(sizeof(*lval));
2152 lval->type = jbvNumeric;
2153 lval->val.numeric = res;
2154
2155 return executeNextItem(cxt, jsp, &elem, lval, found, false);
2156 }
2157
2158 /*
2159 * Execute unary arithmetic expression for each numeric item in its operand's
2160 * sequence. Array operand is automatically unwrapped in lax mode.
2161 */
2162 static JsonPathExecResult
2163 executeUnaryArithmExpr(JsonPathExecContext *cxt, JsonPathItem *jsp,
2164 JsonbValue *jb, PGFunction func, JsonValueList *found)
2165 {
2166 JsonPathExecResult jper;
2167 JsonPathExecResult jper2;
2168 JsonPathItem elem;
2169 JsonValueList seq = {0};
2170 JsonValueListIterator it;
2171 JsonbValue *val;
2172 bool hasNext;
2173
2174 jspGetArg(jsp, &elem);
2175 jper = executeItemOptUnwrapResult(cxt, &elem, jb, true, &seq);
2176
2177 if (jperIsError(jper))
2178 return jper;
2179
2180 jper = jperNotFound;
2181
2182 hasNext = jspGetNext(jsp, &elem);
2183
2184 JsonValueListInitIterator(&seq, &it);
2185 while ((val = JsonValueListNext(&seq, &it)))
2186 {
2187 if ((val = getScalar(val, jbvNumeric)))
2188 {
2189 if (!found && !hasNext)
2190 return jperOk;
2191 }
2192 else
2193 {
2194 if (!found && !hasNext)
2195 continue; /* skip non-numerics processing */
2196
2197 RETURN_ERROR(ereport(ERROR,
2198 (errcode(ERRCODE_SQL_JSON_NUMBER_NOT_FOUND),
2199 errmsg("operand of unary jsonpath operator %s is not a numeric value",
2200 jspOperationName(jsp->type)))));
2201 }
2202
2203 if (func)
2204 val->val.numeric =
2205 DatumGetNumeric(DirectFunctionCall1(func,
2206 NumericGetDatum(val->val.numeric)));
2207
2208 jper2 = executeNextItem(cxt, jsp, &elem, val, found, false);
2209
2210 if (jperIsError(jper2))
2211 return jper2;
2212
2213 if (jper2 == jperOk)
2214 {
2215 if (!found)
2216 return jperOk;
2217 jper = jperOk;
2218 }
2219 }
2220
2221 return jper;
2222 }
2223
2224 /*
2225 * STARTS_WITH predicate callback.
2226 *
2227 * Check if the 'whole' string starts from 'initial' string.
2228 */
2229 static JsonPathBool
2230 executeStartsWith(JsonPathItem *jsp, JsonbValue *whole, JsonbValue *initial,
2231 void *param)
2232 {
2233 if (!(whole = getScalar(whole, jbvString)))
2234 return jpbUnknown; /* error */
2235
2236 if (!(initial = getScalar(initial, jbvString)))
2237 return jpbUnknown; /* error */
2238
2239 if (whole->val.string.len >= initial->val.string.len &&
2240 !memcmp(whole->val.string.val,
2241 initial->val.string.val,
2242 initial->val.string.len))
2243 return jpbTrue;
2244
2245 return jpbFalse;
2246 }
2247
2248 /*
2249 * LIKE_REGEX predicate callback.
2250 *
2251 * Check if the string matches regex pattern.
2252 */
2253 static JsonPathBool
2254 executeLikeRegex(JsonPathItem *jsp, JsonbValue *str, JsonbValue *rarg,
2255 void *param)
2256 {
2257 JsonLikeRegexContext *cxt = param;
2258
2259 if (!(str = getScalar(str, jbvString)))
2260 return jpbUnknown;
2261
2262 /* Cache regex text and converted flags. */
2263 if (!cxt->regex)
2264 {
2265 cxt->regex =
2266 cstring_to_text_with_len(jsp->content.like_regex.pattern,
2267 jsp->content.like_regex.patternlen);
2268 (void) jspConvertRegexFlags(jsp->content.like_regex.flags,
2269 &(cxt->cflags), NULL);
2270 }
2271
2272 if (RE_compile_and_execute(cxt->regex, str->val.string.val,
2273 str->val.string.len,
2274 cxt->cflags, DEFAULT_COLLATION_OID, 0, NULL))
2275 return jpbTrue;
2276
2277 return jpbFalse;
2278 }
2279
2280 /*
2281 * Execute numeric item methods (.abs(), .floor(), .ceil()) using the specified
2282 * user function 'func'.
2283 */
2284 static JsonPathExecResult
2285 executeNumericItemMethod(JsonPathExecContext *cxt, JsonPathItem *jsp,
2286 JsonbValue *jb, bool unwrap, PGFunction func,
2287 JsonValueList *found)
2288 {
2289 JsonPathItem next;
2290 Datum datum;
2291
2292 if (unwrap && JsonbType(jb) == jbvArray)
2293 return executeItemUnwrapTargetArray(cxt, jsp, jb, found, false);
2294
2295 if (!(jb = getScalar(jb, jbvNumeric)))
2296 RETURN_ERROR(ereport(ERROR,
2297 (errcode(ERRCODE_NON_NUMERIC_SQL_JSON_ITEM),
2298 errmsg("jsonpath item method .%s() can only be applied to a numeric value",
2299 jspOperationName(jsp->type)))));
2300
2301 datum = DirectFunctionCall1(func, NumericGetDatum(jb->val.numeric));
2302
2303 if (!jspGetNext(jsp, &next) && !found)
2304 return jperOk;
2305
2306 jb = palloc(sizeof(*jb));
2307 jb->type = jbvNumeric;
2308 jb->val.numeric = DatumGetNumeric(datum);
2309
2310 return executeNextItem(cxt, jsp, &next, jb, found, false);
2311 }
2312
2313 /*
2314 * Implementation of the .datetime() and related methods.
2315 *
2316 * Converts a string into a date/time value. The actual type is determined at
2317 * run time.
2318 * If an argument is provided, this argument is used as a template string.
2319 * Otherwise, the first fitting ISO format is selected.
2320 *
2321 * .date(), .time(), .time_tz(), .timestamp(), .timestamp_tz() methods don't
2322 * have a format, so ISO format is used. However, except for .date(), they all
2323 * take an optional time precision.
2324 */
2325 static JsonPathExecResult
2326 executeDateTimeMethod(JsonPathExecContext *cxt, JsonPathItem *jsp,
2327 JsonbValue *jb, JsonValueList *found)
2328 {
2329 JsonbValue jbvbuf;
2330 Datum value;
2331 text *datetime;
2332 Oid collid;
2333 Oid typid;
2334 int32 typmod = -1;
2335 int tz = 0;
2336 bool hasNext;
2337 JsonPathExecResult res = jperNotFound;
2338 JsonPathItem elem;
2339 int32 time_precision = -1;
2340
2341 if (!(jb = getScalar(jb, jbvString)))
2342 RETURN_ERROR(ereport(ERROR,
2343 (errcode(ERRCODE_INVALID_ARGUMENT_FOR_SQL_JSON_DATETIME_FUNCTION),
2344 errmsg("jsonpath item method .%s() can only be applied to a string",
2345 jspOperationName(jsp->type)))));
2346
2347 datetime = cstring_to_text_with_len(jb->val.string.val,
2348 jb->val.string.len);
2349
2350 /*
2351 * At some point we might wish to have callers supply the collation to
2352 * use, but right now it's unclear that they'd be able to do better than
2353 * DEFAULT_COLLATION_OID anyway.
2354 */
2355 collid = DEFAULT_COLLATION_OID;
2356
2357 /*
2358 * .datetime(template) has an argument, the rest of the methods don't have
2359 * an argument. So we handle that separately.
2360 */
2361 if (jsp->type == jpiDatetime && jsp->content.arg)
2362 {
2363 text *template;
2364 char *template_str;
2365 int template_len;
2366 ErrorSaveContext escontext = {T_ErrorSaveContext};
2367
2368 jspGetArg(jsp, &elem);
2369
2370 if (elem.type != jpiString)
2371 elog(ERROR, "invalid jsonpath item type for .datetime() argument");
2372
2373 template_str = jspGetString(&elem, &template_len);
2374
2375 template = cstring_to_text_with_len(template_str,
2376 template_len);
2377
2378 value = parse_datetime(datetime, template, collid, true,
2379 &typid, &typmod, &tz,
2380 jspThrowErrors(cxt) ? NULL : (Node *) &escontext);
2381
2382 if (escontext.error_occurred)
2383 res = jperError;
2384 else
2385 res = jperOk;
2386 }
2387 else
2388 {
2389 /*
2390 * According to SQL/JSON standard enumerate ISO formats for: date,
2391 * timetz, time, timestamptz, timestamp.
2392 *
2393 * We also support ISO 8601 format (with "T") for timestamps, because
2394 * to_json[b]() functions use this format.
2395 */
2396 static const char *fmt_str[] =
2397 {
2398 "yyyy-mm-dd", /* date */
2399 "HH24:MI:SS.USTZ", /* timetz */
2400 "HH24:MI:SSTZ",
2401 "HH24:MI:SS.US", /* time without tz */
2402 "HH24:MI:SS",
2403 "yyyy-mm-dd HH24:MI:SS.USTZ", /* timestamptz */
2404 "yyyy-mm-dd HH24:MI:SSTZ",
2405 "yyyy-mm-dd\"T\"HH24:MI:SS.USTZ",
2406 "yyyy-mm-dd\"T\"HH24:MI:SSTZ",
2407 "yyyy-mm-dd HH24:MI:SS.US", /* timestamp without tz */
2408 "yyyy-mm-dd HH24:MI:SS",
2409 "yyyy-mm-dd\"T\"HH24:MI:SS.US",
2410 "yyyy-mm-dd\"T\"HH24:MI:SS"
2411 };
2412
2413 /* cache for format texts */
2414 static text *fmt_txt[lengthof(fmt_str)] = {0};
2415 int i;
2416
2417 /*
2418 * Check for optional precision for methods other than .datetime() and
2419 * .date()
2420 */
2421 if (jsp->type != jpiDatetime && jsp->type != jpiDate &&
2422 jsp->content.arg)
2423 {
2424 bool have_error;
2425
2426 jspGetArg(jsp, &elem);
2427
2428 if (elem.type != jpiNumeric)
2429 elog(ERROR, "invalid jsonpath item type for %s argument",
2430 jspOperationName(jsp->type));
2431
2432 time_precision = numeric_int4_opt_error(jspGetNumeric(&elem),
2433 &have_error);
2434 if (have_error)
2435 RETURN_ERROR(ereport(ERROR,
2436 (errcode(ERRCODE_INVALID_ARGUMENT_FOR_SQL_JSON_DATETIME_FUNCTION),
2437 errmsg("time precision of jsonpath item method .%s() is out of range for type integer",
2438 jspOperationName(jsp->type)))));
2439 }
2440
2441 /* loop until datetime format fits */
2442 for (i = 0; i < lengthof(fmt_str); i++)
2443 {
2444 ErrorSaveContext escontext = {T_ErrorSaveContext};
2445
2446 if (!fmt_txt[i])
2447 {
2448 MemoryContext oldcxt =
2449 MemoryContextSwitchTo(TopMemoryContext);
2450
2451 fmt_txt[i] = cstring_to_text(fmt_str[i]);
2452 MemoryContextSwitchTo(oldcxt);
2453 }
2454
2455 value = parse_datetime(datetime, fmt_txt[i], collid, true,
2456 &typid, &typmod, &tz,
2457 (Node *) &escontext);
2458
2459 if (!escontext.error_occurred)
2460 {
2461 res = jperOk;
2462 break;
2463 }
2464 }
2465
2466 if (res == jperNotFound)
2467 {
2468 if (jsp->type == jpiDatetime)
2469 RETURN_ERROR(ereport(ERROR,
2470 (errcode(ERRCODE_INVALID_ARGUMENT_FOR_SQL_JSON_DATETIME_FUNCTION),
2471 errmsg("%s format is not recognized: \"%s\"",
2472 "datetime", text_to_cstring(datetime)),
2473 errhint("Use a datetime template argument to specify the input data format."))));
2474 else
2475 RETURN_ERROR(ereport(ERROR,
2476 (errcode(ERRCODE_INVALID_ARGUMENT_FOR_SQL_JSON_DATETIME_FUNCTION),
2477 errmsg("%s format is not recognized: \"%s\"",
2478 jspOperationName(jsp->type), text_to_cstring(datetime)))));
2479
2480 }
2481 }
2482
2483 /*
2484 * parse_datetime() processes the entire input string per the template or
2485 * ISO format and returns the Datum in best fitted datetime type. So, if
2486 * this call is for a specific datatype, then we do the conversion here.
2487 * Throw an error for incompatible types.
2488 */
2489 switch (jsp->type)
2490 {
2491 case jpiDatetime: /* Nothing to do for DATETIME */
2492 break;
2493 case jpiDate:
2494 {
2495 /* Convert result type to date */
2496 switch (typid)
2497 {
2498 case DATEOID: /* Nothing to do for DATE */
2499 break;
2500 case TIMEOID:
2501 case TIMETZOID:
2502 RETURN_ERROR(ereport(ERROR,
2503 (errcode(ERRCODE_INVALID_ARGUMENT_FOR_SQL_JSON_DATETIME_FUNCTION),
2504 errmsg("%s format is not recognized: \"%s\"",
2505 "date", text_to_cstring(datetime)))));
2506 break;
2507 case TIMESTAMPOID:
2508 value = DirectFunctionCall1(timestamp_date,
2509 value);
2510 break;
2511 case TIMESTAMPTZOID:
2512 checkTimezoneIsUsedForCast(cxt->useTz,
2513 "timestamptz", "date");
2514 value = DirectFunctionCall1(timestamptz_date,
2515 value);
2516 break;
2517 default:
2518 elog(ERROR, "type with oid %u not supported", typid);
2519 }
2520
2521 typid = DATEOID;
2522 }
2523 break;
2524 case jpiTime:
2525 {
2526 /* Convert result type to time without time zone */
2527 switch (typid)
2528 {
2529 case DATEOID:
2530 RETURN_ERROR(ereport(ERROR,
2531 (errcode(ERRCODE_INVALID_ARGUMENT_FOR_SQL_JSON_DATETIME_FUNCTION),
2532 errmsg("%s format is not recognized: \"%s\"",
2533 "time", text_to_cstring(datetime)))));
2534 break;
2535 case TIMEOID: /* Nothing to do for TIME */
2536 break;
2537 case TIMETZOID:
2538 checkTimezoneIsUsedForCast(cxt->useTz,
2539 "timetz", "time");
2540 value = DirectFunctionCall1(timetz_time,
2541 value);
2542 break;
2543 case TIMESTAMPOID:
2544 value = DirectFunctionCall1(timestamp_time,
2545 value);
2546 break;
2547 case TIMESTAMPTZOID:
2548 checkTimezoneIsUsedForCast(cxt->useTz,
2549 "timestamptz", "time");
2550 value = DirectFunctionCall1(timestamptz_time,
2551 value);
2552 break;
2553 default:
2554 elog(ERROR, "type with oid %u not supported", typid);
2555 }
2556
2557 /* Force the user-given time precision, if any */
2558 if (time_precision != -1)
2559 {
2560 TimeADT result;
2561
2562 /* Get a warning when precision is reduced */
2563 time_precision = anytime_typmod_check(false,
2564 time_precision);
2565 result = DatumGetTimeADT(value);
2566 AdjustTimeForTypmod(&result, time_precision);
2567 value = TimeADTGetDatum(result);
2568
2569 /* Update the typmod value with the user-given precision */
2570 typmod = time_precision;
2571 }
2572
2573 typid = TIMEOID;
2574 }
2575 break;
2576 case jpiTimeTz:
2577 {
2578 /* Convert result type to time with time zone */
2579 switch (typid)
2580 {
2581 case DATEOID:
2582 case TIMESTAMPOID:
2583 RETURN_ERROR(ereport(ERROR,
2584 (errcode(ERRCODE_INVALID_ARGUMENT_FOR_SQL_JSON_DATETIME_FUNCTION),
2585 errmsg("%s format is not recognized: \"%s\"",
2586 "time_tz", text_to_cstring(datetime)))));
2587 break;
2588 case TIMEOID:
2589 checkTimezoneIsUsedForCast(cxt->useTz,
2590 "time", "timetz");
2591 value = DirectFunctionCall1(time_timetz,
2592 value);
2593 break;
2594 case TIMETZOID: /* Nothing to do for TIMETZ */
2595 break;
2596 case TIMESTAMPTZOID:
2597 value = DirectFunctionCall1(timestamptz_timetz,
2598 value);
2599 break;
2600 default:
2601 elog(ERROR, "type with oid %u not supported", typid);
2602 }
2603
2604 /* Force the user-given time precision, if any */
2605 if (time_precision != -1)
2606 {
2607 TimeTzADT *result;
2608
2609 /* Get a warning when precision is reduced */
2610 time_precision = anytime_typmod_check(true,
2611 time_precision);
2612 result = DatumGetTimeTzADTP(value);
2613 AdjustTimeForTypmod(&result->time, time_precision);
2614 value = TimeTzADTPGetDatum(result);
2615
2616 /* Update the typmod value with the user-given precision */
2617 typmod = time_precision;
2618 }
2619
2620 typid = TIMETZOID;
2621 }
2622 break;
2623 case jpiTimestamp:
2624 {
2625 /* Convert result type to timestamp without time zone */
2626 switch (typid)
2627 {
2628 case DATEOID:
2629 value = DirectFunctionCall1(date_timestamp,
2630 value);
2631 break;
2632 case TIMEOID:
2633 case TIMETZOID:
2634 RETURN_ERROR(ereport(ERROR,
2635 (errcode(ERRCODE_INVALID_ARGUMENT_FOR_SQL_JSON_DATETIME_FUNCTION),
2636 errmsg("%s format is not recognized: \"%s\"",
2637 "timestamp", text_to_cstring(datetime)))));
2638 break;
2639 case TIMESTAMPOID: /* Nothing to do for TIMESTAMP */
2640 break;
2641 case TIMESTAMPTZOID:
2642 checkTimezoneIsUsedForCast(cxt->useTz,
2643 "timestamptz", "timestamp");
2644 value = DirectFunctionCall1(timestamptz_timestamp,
2645 value);
2646 break;
2647 default:
2648 elog(ERROR, "type with oid %u not supported", typid);
2649 }
2650
2651 /* Force the user-given time precision, if any */
2652 if (time_precision != -1)
2653 {
2654 Timestamp result;
2655 ErrorSaveContext escontext = {T_ErrorSaveContext};
2656
2657 /* Get a warning when precision is reduced */
2658 time_precision = anytimestamp_typmod_check(false,
2659 time_precision);
2660 result = DatumGetTimestamp(value);
2661 AdjustTimestampForTypmod(&result, time_precision,
2662 (Node *) &escontext);
2663 if (escontext.error_occurred) /* should not happen */
2664 RETURN_ERROR(ereport(ERROR,
2665 (errcode(ERRCODE_INVALID_ARGUMENT_FOR_SQL_JSON_DATETIME_FUNCTION),
2666 errmsg("time precision of jsonpath item method .%s() is invalid",
2667 jspOperationName(jsp->type)))));
2668 value = TimestampGetDatum(result);
2669
2670 /* Update the typmod value with the user-given precision */
2671 typmod = time_precision;
2672 }
2673
2674 typid = TIMESTAMPOID;
2675 }
2676 break;
2677 case jpiTimestampTz:
2678 {
2679 struct pg_tm tm;
2680 fsec_t fsec;
2681
2682 /* Convert result type to timestamp with time zone */
2683 switch (typid)
2684 {
2685 case DATEOID:
2686 checkTimezoneIsUsedForCast(cxt->useTz,
2687 "date", "timestamptz");
2688
2689 /*
2690 * Get the timezone value explicitly since JsonbValue
2691 * keeps that separate.
2692 */
2693 j2date(DatumGetDateADT(value) + POSTGRES_EPOCH_JDATE,
2694 &(tm.tm_year), &(tm.tm_mon), &(tm.tm_mday));
2695 tm.tm_hour = 0;
2696 tm.tm_min = 0;
2697 tm.tm_sec = 0;
2698 tz = DetermineTimeZoneOffset(&tm, session_timezone);
2699
2700 value = DirectFunctionCall1(date_timestamptz,
2701 value);
2702 break;
2703 case TIMEOID:
2704 case TIMETZOID:
2705 RETURN_ERROR(ereport(ERROR,
2706 (errcode(ERRCODE_INVALID_ARGUMENT_FOR_SQL_JSON_DATETIME_FUNCTION),
2707 errmsg("%s format is not recognized: \"%s\"",
2708 "timestamp_tz", text_to_cstring(datetime)))));
2709 break;
2710 case TIMESTAMPOID:
2711 checkTimezoneIsUsedForCast(cxt->useTz,
2712 "timestamp", "timestamptz");
2713
2714 /*
2715 * Get the timezone value explicitly since JsonbValue
2716 * keeps that separate.
2717 */
2718 if (timestamp2tm(DatumGetTimestamp(value), NULL, &tm,
2719 &fsec, NULL, NULL) == 0)
2720 tz = DetermineTimeZoneOffset(&tm,
2721 session_timezone);
2722
2723 value = DirectFunctionCall1(timestamp_timestamptz,
2724 value);
2725 break;
2726 case TIMESTAMPTZOID: /* Nothing to do for TIMESTAMPTZ */
2727 break;
2728 default:
2729 elog(ERROR, "type with oid %u not supported", typid);
2730 }
2731
2732 /* Force the user-given time precision, if any */
2733 if (time_precision != -1)
2734 {
2735 Timestamp result;
2736 ErrorSaveContext escontext = {T_ErrorSaveContext};
2737
2738 /* Get a warning when precision is reduced */
2739 time_precision = anytimestamp_typmod_check(true,
2740 time_precision);
2741 result = DatumGetTimestampTz(value);
2742 AdjustTimestampForTypmod(&result, time_precision,
2743 (Node *) &escontext);
2744 if (escontext.error_occurred) /* should not happen */
2745 RETURN_ERROR(ereport(ERROR,
2746 (errcode(ERRCODE_INVALID_ARGUMENT_FOR_SQL_JSON_DATETIME_FUNCTION),
2747 errmsg("time precision of jsonpath item method .%s() is invalid",
2748 jspOperationName(jsp->type)))));
2749 value = TimestampTzGetDatum(result);
2750
2751 /* Update the typmod value with the user-given precision */
2752 typmod = time_precision;
2753 }
2754
2755 typid = TIMESTAMPTZOID;
2756 }
2757 break;
2758 default:
2759 elog(ERROR, "unrecognized jsonpath item type: %d", jsp->type);
2760 }
2761
2762 pfree(datetime);
2763
2764 if (jperIsError(res))
2765 return res;
2766
2767 hasNext = jspGetNext(jsp, &elem);
2768
2769 if (!hasNext && !found)
2770 return res;
2771
2772 jb = hasNext ? &jbvbuf : palloc(sizeof(*jb));
2773
2774 jb->type = jbvDatetime;
2775 jb->val.datetime.value = value;
2776 jb->val.datetime.typid = typid;
2777 jb->val.datetime.typmod = typmod;
2778 jb->val.datetime.tz = tz;
2779
2780 return executeNextItem(cxt, jsp, &elem, jb, found, hasNext);
2781 }
2782
2783 /*
2784 * Implementation of .keyvalue() method.
2785 *
2786 * .keyvalue() method returns a sequence of object's key-value pairs in the
2787 * following format: '{ "key": key, "value": value, "id": id }'.
2788 *
2789 * "id" field is an object identifier which is constructed from the two parts:
2790 * base object id and its binary offset in base object's jsonb:
2791 * id = 10000000000 * base_object_id + obj_offset_in_base_object
2792 *
2793 * 10000000000 (10^10) -- is a first round decimal number greater than 2^32
2794 * (maximal offset in jsonb). Decimal multiplier is used here to improve the
2795 * readability of identifiers.
2796 *
2797 * Base object is usually a root object of the path: context item '$' or path
2798 * variable '$var', literals can't produce objects for now. But if the path
2799 * contains generated objects (.keyvalue() itself, for example), then they
2800 * become base object for the subsequent .keyvalue().
2801 *
2802 * Id of '$' is 0. Id of '$var' is its ordinal (positive) number in the list
2803 * of variables (see getJsonPathVariable()). Ids for generated objects
2804 * are assigned using global counter JsonPathExecContext.lastGeneratedObjectId.
2805 */
2806 static JsonPathExecResult
2807 executeKeyValueMethod(JsonPathExecContext *cxt, JsonPathItem *jsp,
2808 JsonbValue *jb, JsonValueList *found)
2809 {
2810 JsonPathExecResult res = jperNotFound;
2811 JsonPathItem next;
2812 JsonbContainer *jbc;
2813 JsonbValue key;
2814 JsonbValue val;
2815 JsonbValue idval;
2816 JsonbValue keystr;
2817 JsonbValue valstr;
2818 JsonbValue idstr;
2819 JsonbIterator *it;
2820 JsonbIteratorToken tok;
2821 int64 id;
2822 bool hasNext;
2823
2824 if (JsonbType(jb) != jbvObject || jb->type != jbvBinary)
2825 RETURN_ERROR(ereport(ERROR,
2826 (errcode(ERRCODE_SQL_JSON_OBJECT_NOT_FOUND),
2827 errmsg("jsonpath item method .%s() can only be applied to an object",
2828 jspOperationName(jsp->type)))));
2829
2830 jbc = jb->val.binary.data;
2831
2832 if (!JsonContainerSize(jbc))
2833 return jperNotFound; /* no key-value pairs */
2834
2835 hasNext = jspGetNext(jsp, &next);
2836
2837 keystr.type = jbvString;
2838 keystr.val.string.val = "key";
2839 keystr.val.string.len = 3;
2840
2841 valstr.type = jbvString;
2842 valstr.val.string.val = "value";
2843 valstr.val.string.len = 5;
2844
2845 idstr.type = jbvString;
2846 idstr.val.string.val = "id";
2847 idstr.val.string.len = 2;
2848
2849 /* construct object id from its base object and offset inside that */
2850 id = jb->type != jbvBinary ? 0 :
2851 (int64) ((char *) jbc - (char *) cxt->baseObject.jbc);
2852 id += (int64) cxt->baseObject.id * INT64CONST(10000000000);
2853
2854 idval.type = jbvNumeric;
2855 idval.val.numeric = int64_to_numeric(id);
2856
2857 it = JsonbIteratorInit(jbc);
2858
2859 while ((tok = JsonbIteratorNext(&it, &key, true)) != WJB_DONE)
2860 {
2861 JsonBaseObjectInfo baseObject;
2862 JsonbValue obj;
2863 JsonbParseState *ps;
2864 JsonbValue *keyval;
2865 Jsonb *jsonb;
2866
2867 if (tok != WJB_KEY)
2868 continue;
2869
2870 res = jperOk;
2871
2872 if (!hasNext && !found)
2873 break;
2874
2875 tok = JsonbIteratorNext(&it, &val, true);
2876 Assert(tok == WJB_VALUE);
2877
2878 ps = NULL;
2879 pushJsonbValue(&ps, WJB_BEGIN_OBJECT, NULL);
2880
2881 pushJsonbValue(&ps, WJB_KEY, &keystr);
2882 pushJsonbValue(&ps, WJB_VALUE, &key);
2883
2884 pushJsonbValue(&ps, WJB_KEY, &valstr);
2885 pushJsonbValue(&ps, WJB_VALUE, &val);
2886
2887 pushJsonbValue(&ps, WJB_KEY, &idstr);
2888 pushJsonbValue(&ps, WJB_VALUE, &idval);
2889
2890 keyval = pushJsonbValue(&ps, WJB_END_OBJECT, NULL);
2891
2892 jsonb = JsonbValueToJsonb(keyval);
2893
2894 JsonbInitBinary(&obj, jsonb);
2895
2896 baseObject = setBaseObject(cxt, &obj, cxt->lastGeneratedObjectId++);
2897
2898 res = executeNextItem(cxt, jsp, &next, &obj, found, true);
2899
2900 cxt->baseObject = baseObject;
2901
2902 if (jperIsError(res))
2903 return res;
2904
2905 if (res == jperOk && !found)
2906 break;
2907 }
2908
2909 return res;
2910 }
2911
2912 /*
2913 * Convert boolean execution status 'res' to a boolean JSON item and execute
2914 * next jsonpath.
2915 */
2916 static JsonPathExecResult
2917 appendBoolResult(JsonPathExecContext *cxt, JsonPathItem *jsp,
2918 JsonValueList *found, JsonPathBool res)
2919 {
2920 JsonPathItem next;
2921 JsonbValue jbv;
2922
2923 if (!jspGetNext(jsp, &next) && !found)
2924 return jperOk; /* found singleton boolean value */
2925
2926 if (res == jpbUnknown)
2927 {
2928 jbv.type = jbvNull;
2929 }
2930 else
2931 {
2932 jbv.type = jbvBool;
2933 jbv.val.boolean = res == jpbTrue;
2934 }
2935
2936 return executeNextItem(cxt, jsp, &next, &jbv, found, true);
2937 }
2938
2939 /*
2940 * Convert jsonpath's scalar or variable node to actual jsonb value.
2941 *
2942 * If node is a variable then its id returned, otherwise 0 returned.
2943 */
2944 static void
2945 getJsonPathItem(JsonPathExecContext *cxt, JsonPathItem *item,
2946 JsonbValue *value)
2947 {
2948 switch (item->type)
2949 {
2950 case jpiNull:
2951 value->type = jbvNull;
2952 break;
2953 case jpiBool:
2954 value->type = jbvBool;
2955 value->val.boolean = jspGetBool(item);
2956 break;
2957 case jpiNumeric:
2958 value->type = jbvNumeric;
2959 value->val.numeric = jspGetNumeric(item);
2960 break;
2961 case jpiString:
2962 value->type = jbvString;
2963 value->val.string.val = jspGetString(item,
2964 &value->val.string.len);
2965 break;
2966 case jpiVariable:
2967 getJsonPathVariable(cxt, item, value);
2968 return;
2969 default:
2970 elog(ERROR, "unexpected jsonpath item type");
2971 }
2972 }
2973
2974 /*
2975 * Returns the computed value of a JSON path variable with given name.
2976 */
2977 static JsonbValue *
2978 GetJsonPathVar(void *cxt, char *varName, int varNameLen,
2979 JsonbValue *baseObject, int *baseObjectId)
2980 {
2981 JsonPathVariable *var = NULL;
2982 List *vars = cxt;
2983 ListCell *lc;
2984 JsonbValue *result;
2985 int id = 1;
2986
2987 foreach(lc, vars)
2988 {
2989 JsonPathVariable *curvar = lfirst(lc);
2990
2991 if (curvar->namelen == varNameLen &&
2992 strncmp(curvar->name, varName, varNameLen) == 0)
2993 {
2994 var = curvar;
2995 break;
2996 }
2997
2998 id++;
2999 }
3000
3001 if (var == NULL)
3002 {
3003 *baseObjectId = -1;
3004 return NULL;
3005 }
3006
3007 result = palloc(sizeof(JsonbValue));
3008 if (var->isnull)
3009 {
3010 *baseObjectId = 0;
3011 result->type = jbvNull;
3012 }
3013 else
3014 JsonItemFromDatum(var->value, var->typid, var->typmod, result);
3015
3016 *baseObject = *result;
3017 *baseObjectId = id;
3018
3019 return result;
3020 }
3021
3022 static int
3023 CountJsonPathVars(void *cxt)
3024 {
3025 List *vars = (List *) cxt;
3026
3027 return list_length(vars);
3028 }
3029
3030
3031 /*
3032 * Initialize JsonbValue to pass to jsonpath executor from given
3033 * datum value of the specified type.
3034 */
3035 static void
3036 JsonItemFromDatum(Datum val, Oid typid, int32 typmod, JsonbValue *res)
3037 {
3038 switch (typid)
3039 {
3040 case BOOLOID:
3041 res->type = jbvBool;
3042 res->val.boolean = DatumGetBool(val);
3043 break;
3044 case NUMERICOID:
3045 JsonbValueInitNumericDatum(res, val);
3046 break;
3047 case INT2OID:
3048 JsonbValueInitNumericDatum(res, DirectFunctionCall1(int2_numeric, val));
3049 break;
3050 case INT4OID:
3051 JsonbValueInitNumericDatum(res, DirectFunctionCall1(int4_numeric, val));
3052 break;
3053 case INT8OID:
3054 JsonbValueInitNumericDatum(res, DirectFunctionCall1(int8_numeric, val));
3055 break;
3056 case FLOAT4OID:
3057 JsonbValueInitNumericDatum(res, DirectFunctionCall1(float4_numeric, val));
3058 break;
3059 case FLOAT8OID:
3060 JsonbValueInitNumericDatum(res, DirectFunctionCall1(float8_numeric, val));
3061 break;
3062 case TEXTOID:
3063 case VARCHAROID:
3064 res->type = jbvString;
3065 res->val.string.val = VARDATA_ANY(val);
3066 res->val.string.len = VARSIZE_ANY_EXHDR(val);
3067 break;
3068 case DATEOID:
3069 case TIMEOID:
3070 case TIMETZOID:
3071 case TIMESTAMPOID:
3072 case TIMESTAMPTZOID:
3073 res->type = jbvDatetime;
3074 res->val.datetime.value = val;
3075 res->val.datetime.typid = typid;
3076 res->val.datetime.typmod = typmod;
3077 res->val.datetime.tz = 0;
3078 break;
3079 case JSONBOID:
3080 {
3081 JsonbValue *jbv = res;
3082 Jsonb *jb = DatumGetJsonbP(val);
3083
3084 if (JsonContainerIsScalar(&jb->root))
3085 {
3086 bool result PG_USED_FOR_ASSERTS_ONLY;
3087
3088 result = JsonbExtractScalar(&jb->root, jbv);
3089 Assert(result);
3090 }
3091 else
3092 JsonbInitBinary(jbv, jb);
3093 break;
3094 }
3095 case JSONOID:
3096 {
3097 text *txt = DatumGetTextP(val);
3098 char *str = text_to_cstring(txt);
3099 Jsonb *jb;
3100
3101 jb = DatumGetJsonbP(DirectFunctionCall1(jsonb_in,
3102 CStringGetDatum(str)));
3103 pfree(str);
3104
3105 JsonItemFromDatum(JsonbPGetDatum(jb), JSONBOID, -1, res);
3106 break;
3107 }
3108 default:
3109 ereport(ERROR,
3110 errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3111 errmsg("could not convert value of type %s to jsonpath",
3112 format_type_be(typid)));
3113 }
3114 }
3115
3116 /* Initialize numeric value from the given datum */
3117 static void
3118 JsonbValueInitNumericDatum(JsonbValue *jbv, Datum num)
3119 {
3120 jbv->type = jbvNumeric;
3121 jbv->val.numeric = DatumGetNumeric(num);
3122 }
3123
3124 /*
3125 * Get the value of variable passed to jsonpath executor
3126 */
3127 static void
3128 getJsonPathVariable(JsonPathExecContext *cxt, JsonPathItem *variable,
3129 JsonbValue *value)
3130 {
3131 char *varName;
3132 int varNameLength;
3133 JsonbValue baseObject;
3134 int baseObjectId;
3135 JsonbValue *v;
3136
3137 Assert(variable->type == jpiVariable);
3138 varName = jspGetString(variable, &varNameLength);
3139
3140 if (cxt->vars == NULL ||
3141 (v = cxt->getVar(cxt->vars, varName, varNameLength,
3142 &baseObject, &baseObjectId)) == NULL)
3143 ereport(ERROR,
3144 (errcode(ERRCODE_UNDEFINED_OBJECT),
3145 errmsg("could not find jsonpath variable \"%s\"",
3146 pnstrdup(varName, varNameLength))));
3147
3148 if (baseObjectId > 0)
3149 {
3150 *value = *v;
3151 setBaseObject(cxt, &baseObject, baseObjectId);
3152 }
3153 }
3154
3155 /*
3156 * Definition of JsonPathGetVarCallback for when JsonPathExecContext.vars
3157 * is specified as a jsonb value.
3158 */
3159 static JsonbValue *
3160 getJsonPathVariableFromJsonb(void *varsJsonb, char *varName, int varNameLength,
3161 JsonbValue *baseObject, int *baseObjectId)
3162 {
3163 Jsonb *vars = varsJsonb;
3164 JsonbValue tmp;
3165 JsonbValue *result;
3166
3167 tmp.type = jbvString;
3168 tmp.val.string.val = varName;
3169 tmp.val.string.len = varNameLength;
3170
3171 result = findJsonbValueFromContainer(&vars->root, JB_FOBJECT, &tmp);
3172
3173 if (result == NULL)
3174 {
3175 *baseObjectId = -1;
3176 return NULL;
3177 }
3178
3179 *baseObjectId = 1;
3180 JsonbInitBinary(baseObject, vars);
3181
3182 return result;
3183 }
3184
3185 /*
3186 * Definition of JsonPathCountVarsCallback for when JsonPathExecContext.vars
3187 * is specified as a jsonb value.
3188 */
3189 static int
3190 countVariablesFromJsonb(void *varsJsonb)
3191 {
3192 Jsonb *vars = varsJsonb;
3193
3194 if (vars && !JsonContainerIsObject(&vars->root))
3195 {
3196 ereport(ERROR,
3197 errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3198 errmsg("\"vars\" argument is not an object"),
3199 errdetail("Jsonpath parameters should be encoded as key-value pairs of \"vars\" object."));
3200 }
3201
3202 /* count of base objects */
3203 return vars != NULL ? 1 : 0;
3204 }
3205
3206 /**************** Support functions for JsonPath execution *****************/
3207
3208 /*
3209 * Returns the size of an array item, or -1 if item is not an array.
3210 */
3211 static int
3212 JsonbArraySize(JsonbValue *jb)
3213 {
3214 Assert(jb->type != jbvArray);
3215
3216 if (jb->type == jbvBinary)
3217 {
3218 JsonbContainer *jbc = jb->val.binary.data;
3219
3220 if (JsonContainerIsArray(jbc) && !JsonContainerIsScalar(jbc))
3221 return JsonContainerSize(jbc);
3222 }
3223
3224 return -1;
3225 }
3226
3227 /* Comparison predicate callback. */
3228 static JsonPathBool
3229 executeComparison(JsonPathItem *cmp, JsonbValue *lv, JsonbValue *rv, void *p)
3230 {
3231 JsonPathExecContext *cxt = (JsonPathExecContext *) p;
3232
3233 return compareItems(cmp->type, lv, rv, cxt->useTz);
3234 }
3235
3236 /*
3237 * Perform per-byte comparison of two strings.
3238 */
3239 static int
3240 binaryCompareStrings(const char *s1, int len1,
3241 const char *s2, int len2)
3242 {
3243 int cmp;
3244
3245 cmp = memcmp(s1, s2, Min(len1, len2));
3246
3247 if (cmp != 0)
3248 return cmp;
3249
3250 if (len1 == len2)
3251 return 0;
3252
3253 return len1 < len2 ? -1 : 1;
3254 }
3255
3256 /*
3257 * Compare two strings in the current server encoding using Unicode codepoint
3258 * collation.
3259 */
3260 static int
3261 compareStrings(const char *mbstr1, int mblen1,
3262 const char *mbstr2, int mblen2)
3263 {
3264 if (GetDatabaseEncoding() == PG_SQL_ASCII ||
3265 GetDatabaseEncoding() == PG_UTF8)
3266 {
3267 /*
3268 * It's known property of UTF-8 strings that their per-byte comparison
3269 * result matches codepoints comparison result. ASCII can be
3270 * considered as special case of UTF-8.
3271 */
3272 return binaryCompareStrings(mbstr1, mblen1, mbstr2, mblen2);
3273 }
3274 else
3275 {
3276 char *utf8str1,
3277 *utf8str2;
3278 int cmp,
3279 utf8len1,
3280 utf8len2;
3281
3282 /*
3283 * We have to convert other encodings to UTF-8 first, then compare.
3284 * Input strings may be not null-terminated and pg_server_to_any() may
3285 * return them "as is". So, use strlen() only if there is real
3286 * conversion.
3287 */
3288 utf8str1 = pg_server_to_any(mbstr1, mblen1, PG_UTF8);
3289 utf8str2 = pg_server_to_any(mbstr2, mblen2, PG_UTF8);
3290 utf8len1 = (mbstr1 == utf8str1) ? mblen1 : strlen(utf8str1);
3291 utf8len2 = (mbstr2 == utf8str2) ? mblen2 : strlen(utf8str2);
3292
3293 cmp = binaryCompareStrings(utf8str1, utf8len1, utf8str2, utf8len2);
3294
3295 /*
3296 * If pg_server_to_any() did no real conversion, then we actually
3297 * compared original strings. So, we already done.
3298 */
3299 if (mbstr1 == utf8str1 && mbstr2 == utf8str2)
3300 return cmp;
3301
3302 /* Free memory if needed */
3303 if (mbstr1 != utf8str1)
3304 pfree(utf8str1);
3305 if (mbstr2 != utf8str2)
3306 pfree(utf8str2);
3307
3308 /*
3309 * When all Unicode codepoints are equal, return result of binary
3310 * comparison. In some edge cases, same characters may have different
3311 * representations in encoding. Then our behavior could diverge from
3312 * standard. However, that allow us to do simple binary comparison
3313 * for "==" operator, which is performance critical in typical cases.
3314 * In future to implement strict standard conformance, we can do
3315 * normalization of input JSON strings.
3316 */
3317 if (cmp == 0)
3318 return binaryCompareStrings(mbstr1, mblen1, mbstr2, mblen2);
3319 else
3320 return cmp;
3321 }
3322 }
3323
3324 /*
3325 * Compare two SQL/JSON items using comparison operation 'op'.
3326 */
3327 static JsonPathBool
3328 compareItems(int32 op, JsonbValue *jb1, JsonbValue *jb2, bool useTz)
3329 {
3330 int cmp;
3331 bool res;
3332
3333 if (jb1->type != jb2->type)
3334 {
3335 if (jb1->type == jbvNull || jb2->type == jbvNull)
3336
3337 /*
3338 * Equality and order comparison of nulls to non-nulls returns
3339 * always false, but inequality comparison returns true.
3340 */
3341 return op == jpiNotEqual ? jpbTrue : jpbFalse;
3342
3343 /* Non-null items of different types are not comparable. */
3344 return jpbUnknown;
3345 }
3346
3347 switch (jb1->type)
3348 {
3349 case jbvNull:
3350 cmp = 0;
3351 break;
3352 case jbvBool:
3353 cmp = jb1->val.boolean == jb2->val.boolean ? 0 :
3354 jb1->val.boolean ? 1 : -1;
3355 break;
3356 case jbvNumeric:
3357 cmp = compareNumeric(jb1->val.numeric, jb2->val.numeric);
3358 break;
3359 case jbvString:
3360 if (op == jpiEqual)
3361 return jb1->val.string.len != jb2->val.string.len ||
3362 memcmp(jb1->val.string.val,
3363 jb2->val.string.val,
3364 jb1->val.string.len) ? jpbFalse : jpbTrue;
3365
3366 cmp = compareStrings(jb1->val.string.val, jb1->val.string.len,
3367 jb2->val.string.val, jb2->val.string.len);
3368 break;
3369 case jbvDatetime:
3370 {
3371 bool cast_error;
3372
3373 cmp = compareDatetime(jb1->val.datetime.value,
3374 jb1->val.datetime.typid,
3375 jb2->val.datetime.value,
3376 jb2->val.datetime.typid,
3377 useTz,
3378 &cast_error);
3379
3380 if (cast_error)
3381 return jpbUnknown;
3382 }
3383 break;
3384
3385 case jbvBinary:
3386 case jbvArray:
3387 case jbvObject:
3388 return jpbUnknown; /* non-scalars are not comparable */
3389
3390 default:
3391 elog(ERROR, "invalid jsonb value type %d", jb1->type);
3392 }
3393
3394 switch (op)
3395 {
3396 case jpiEqual:
3397 res = (cmp == 0);
3398 break;
3399 case jpiNotEqual:
3400 res = (cmp != 0);
3401 break;
3402 case jpiLess:
3403 res = (cmp < 0);
3404 break;
3405 case jpiGreater:
3406 res = (cmp > 0);
3407 break;
3408 case jpiLessOrEqual:
3409 res = (cmp <= 0);
3410 break;
3411 case jpiGreaterOrEqual:
3412 res = (cmp >= 0);
3413 break;
3414 default:
3415 elog(ERROR, "unrecognized jsonpath operation: %d", op);
3416 return jpbUnknown;
3417 }
3418
3419 return res ? jpbTrue : jpbFalse;
3420 }
3421
3422 /* Compare two numerics */
3423 static int
3424 compareNumeric(Numeric a, Numeric b)
3425 {
3426 return DatumGetInt32(DirectFunctionCall2(numeric_cmp,
3427 NumericGetDatum(a),
3428 NumericGetDatum(b)));
3429 }
3430
3431 static JsonbValue *
3432 copyJsonbValue(JsonbValue *src)
3433 {
3434 JsonbValue *dst = palloc(sizeof(*dst));
3435
3436 *dst = *src;
3437
3438 return dst;
3439 }
3440
3441 /*
3442 * Execute array subscript expression and convert resulting numeric item to
3443 * the integer type with truncation.
3444 */
3445 static JsonPathExecResult
3446 getArrayIndex(JsonPathExecContext *cxt, JsonPathItem *jsp, JsonbValue *jb,
3447 int32 *index)
3448 {
3449 JsonbValue *jbv;
3450 JsonValueList found = {0};
3451 JsonPathExecResult res = executeItem(cxt, jsp, jb, &found);
3452 Datum numeric_index;
3453 bool have_error = false;
3454
3455 if (jperIsError(res))
3456 return res;
3457
3458 if (JsonValueListLength(&found) != 1 ||
3459 !(jbv = getScalar(JsonValueListHead(&found), jbvNumeric)))
3460 RETURN_ERROR(ereport(ERROR,
3461 (errcode(ERRCODE_INVALID_SQL_JSON_SUBSCRIPT),
3462 errmsg("jsonpath array subscript is not a single numeric value"))));
3463
3464 numeric_index = DirectFunctionCall2(numeric_trunc,
3465 NumericGetDatum(jbv->val.numeric),
3466 Int32GetDatum(0));
3467
3468 *index = numeric_int4_opt_error(DatumGetNumeric(numeric_index),
3469 &have_error);
3470
3471 if (have_error)
3472 RETURN_ERROR(ereport(ERROR,
3473 (errcode(ERRCODE_INVALID_SQL_JSON_SUBSCRIPT),
3474 errmsg("jsonpath array subscript is out of integer range"))));
3475
3476 return jperOk;
3477 }
3478
3479 /* Save base object and its id needed for the execution of .keyvalue(). */
3480 static JsonBaseObjectInfo
3481 setBaseObject(JsonPathExecContext *cxt, JsonbValue *jbv, int32 id)
3482 {
3483 JsonBaseObjectInfo baseObject = cxt->baseObject;
3484
3485 cxt->baseObject.jbc = jbv->type != jbvBinary ? NULL :
3486 (JsonbContainer *) jbv->val.binary.data;
3487 cxt->baseObject.id = id;
3488
3489 return baseObject;
3490 }
3491
3492 static void
3493 JsonValueListClear(JsonValueList *jvl)
3494 {
3495 jvl->singleton = NULL;
3496 jvl->list = NIL;
3497 }
3498
3499 static void
3500 JsonValueListAppend(JsonValueList *jvl, JsonbValue *jbv)
3501 {
3502 if (jvl->singleton)
3503 {
3504 jvl->list = list_make2(jvl->singleton, jbv);
3505 jvl->singleton = NULL;
3506 }
3507 else if (!jvl->list)
3508 jvl->singleton = jbv;
3509 else
3510 jvl->list = lappend(jvl->list, jbv);
3511 }
3512
3513 static int
3514 JsonValueListLength(const JsonValueList *jvl)
3515 {
3516 return jvl->singleton ? 1 : list_length(jvl->list);
3517 }
3518
3519 static bool
3520 JsonValueListIsEmpty(JsonValueList *jvl)
3521 {
3522 return !jvl->singleton && (jvl->list == NIL);
3523 }
3524
3525 static JsonbValue *
3526 JsonValueListHead(JsonValueList *jvl)
3527 {
3528 return jvl->singleton ? jvl->singleton : linitial(jvl->list);
3529 }
3530
3531 static List *
3532 JsonValueListGetList(JsonValueList *jvl)
3533 {
3534 if (jvl->singleton)
3535 return list_make1(jvl->singleton);
3536
3537 return jvl->list;
3538 }
3539
3540 static void
3541 JsonValueListInitIterator(const JsonValueList *jvl, JsonValueListIterator *it)
3542 {
3543 if (jvl->singleton)
3544 {
3545 it->value = jvl->singleton;
3546 it->list = NIL;
3547 it->next = NULL;
3548 }
3549 else if (jvl->list != NIL)
3550 {
3551 it->value = (JsonbValue *) linitial(jvl->list);
3552 it->list = jvl->list;
3553 it->next = list_second_cell(jvl->list);
3554 }
3555 else
3556 {
3557 it->value = NULL;
3558 it->list = NIL;
3559 it->next = NULL;
3560 }
3561 }
3562
3563 /*
3564 * Get the next item from the sequence advancing iterator.
3565 */
3566 static JsonbValue *
3567 JsonValueListNext(const JsonValueList *jvl, JsonValueListIterator *it)
3568 {
3569 JsonbValue *result = it->value;
3570
3571 if (it->next)
3572 {
3573 it->value = lfirst(it->next);
3574 it->next = lnext(it->list, it->next);
3575 }
3576 else
3577 {
3578 it->value = NULL;
3579 }
3580
3581 return result;
3582 }
3583
3584 /*
3585 * Initialize a binary JsonbValue with the given jsonb container.
3586 */
3587 static JsonbValue *
3588 JsonbInitBinary(JsonbValue *jbv, Jsonb *jb)
3589 {
3590 jbv->type = jbvBinary;
3591 jbv->val.binary.data = &jb->root;
3592 jbv->val.binary.len = VARSIZE_ANY_EXHDR(jb);
3593
3594 return jbv;
3595 }
3596
3597 /*
3598 * Returns jbv* type of JsonbValue. Note, it never returns jbvBinary as is.
3599 */
3600 static int
3601 JsonbType(JsonbValue *jb)
3602 {
3603 int type = jb->type;
3604
3605 if (jb->type == jbvBinary)
3606 {
3607 JsonbContainer *jbc = jb->val.binary.data;
3608
3609 /* Scalars should be always extracted during jsonpath execution. */
3610 Assert(!JsonContainerIsScalar(jbc));
3611
3612 if (JsonContainerIsObject(jbc))
3613 type = jbvObject;
3614 else if (JsonContainerIsArray(jbc))
3615 type = jbvArray;
3616 else
3617 elog(ERROR, "invalid jsonb container type: 0x%08x", jbc->header);
3618 }
3619
3620 return type;
3621 }
3622
3623 /* Get scalar of given type or NULL on type mismatch */
3624 static JsonbValue *
3625 getScalar(JsonbValue *scalar, enum jbvType type)
3626 {
3627 /* Scalars should be always extracted during jsonpath execution. */
3628 Assert(scalar->type != jbvBinary ||
3629 !JsonContainerIsScalar(scalar->val.binary.data));
3630
3631 return scalar->type == type ? scalar : NULL;
3632 }
3633
3634 /* Construct a JSON array from the item list */
3635 static JsonbValue *
3636 wrapItemsInArray(const JsonValueList *items)
3637 {
3638 JsonbParseState *ps = NULL;
3639 JsonValueListIterator it;
3640 JsonbValue *jbv;
3641
3642 pushJsonbValue(&ps, WJB_BEGIN_ARRAY, NULL);
3643
3644 JsonValueListInitIterator(items, &it);
3645 while ((jbv = JsonValueListNext(items, &it)))
3646 pushJsonbValue(&ps, WJB_ELEM, jbv);
3647
3648 return pushJsonbValue(&ps, WJB_END_ARRAY, NULL);
3649 }
3650
3651 /* Check if the timezone required for casting from type1 to type2 is used */
3652 static void
3653 checkTimezoneIsUsedForCast(bool useTz, const char *type1, const char *type2)
3654 {
3655 if (!useTz)
3656 ereport(ERROR,
3657 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3658 errmsg("cannot convert value from %s to %s without time zone usage",
3659 type1, type2),
3660 errhint("Use *_tz() function for time zone support.")));
3661 }
3662
3663 /* Convert time datum to timetz datum */
3664 static Datum
3665 castTimeToTimeTz(Datum time, bool useTz)
3666 {
3667 checkTimezoneIsUsedForCast(useTz, "time", "timetz");
3668
3669 return DirectFunctionCall1(time_timetz, time);
3670 }
3671
3672 /*
3673 * Compare date to timestamp.
3674 * Note that this doesn't involve any timezone considerations.
3675 */
3676 static int
3677 cmpDateToTimestamp(DateADT date1, Timestamp ts2, bool useTz)
3678 {
3679 return date_cmp_timestamp_internal(date1, ts2);
3680 }
3681
3682 /*
3683 * Compare date to timestamptz.
3684 */
3685 static int
3686 cmpDateToTimestampTz(DateADT date1, TimestampTz tstz2, bool useTz)
3687 {
3688 checkTimezoneIsUsedForCast(useTz, "date", "timestamptz");
3689
3690 return date_cmp_timestamptz_internal(date1, tstz2);
3691 }
3692
3693 /*
3694 * Compare timestamp to timestamptz.
3695 */
3696 static int
3697 cmpTimestampToTimestampTz(Timestamp ts1, TimestampTz tstz2, bool useTz)
3698 {
3699 checkTimezoneIsUsedForCast(useTz, "timestamp", "timestamptz");
3700
3701 return timestamp_cmp_timestamptz_internal(ts1, tstz2);
3702 }
3703
3704 /*
3705 * Cross-type comparison of two datetime SQL/JSON items. If items are
3706 * uncomparable *cast_error flag is set, otherwise *cast_error is unset.
3707 * If the cast requires timezone and it is not used, then explicit error is thrown.
3708 */
3709 static int
3710 compareDatetime(Datum val1, Oid typid1, Datum val2, Oid typid2,
3711 bool useTz, bool *cast_error)
3712 {
3713 PGFunction cmpfunc;
3714
3715 *cast_error = false;
3716
3717 switch (typid1)
3718 {
3719 case DATEOID:
3720 switch (typid2)
3721 {
3722 case DATEOID:
3723 cmpfunc = date_cmp;
3724
3725 break;
3726
3727 case TIMESTAMPOID:
3728 return cmpDateToTimestamp(DatumGetDateADT(val1),
3729 DatumGetTimestamp(val2),
3730 useTz);
3731
3732 case TIMESTAMPTZOID:
3733 return cmpDateToTimestampTz(DatumGetDateADT(val1),
3734 DatumGetTimestampTz(val2),
3735 useTz);
3736
3737 case TIMEOID:
3738 case TIMETZOID:
3739 *cast_error = true; /* uncomparable types */
3740 return 0;
3741
3742 default:
3743 elog(ERROR, "unrecognized SQL/JSON datetime type oid: %u",
3744 typid2);
3745 }
3746 break;
3747
3748 case TIMEOID:
3749 switch (typid2)
3750 {
3751 case TIMEOID:
3752 cmpfunc = time_cmp;
3753
3754 break;
3755
3756 case TIMETZOID:
3757 val1 = castTimeToTimeTz(val1, useTz);
3758 cmpfunc = timetz_cmp;
3759
3760 break;
3761
3762 case DATEOID:
3763 case TIMESTAMPOID:
3764 case TIMESTAMPTZOID:
3765 *cast_error = true; /* uncomparable types */
3766 return 0;
3767
3768 default:
3769 elog(ERROR, "unrecognized SQL/JSON datetime type oid: %u",
3770 typid2);
3771 }
3772 break;
3773
3774 case TIMETZOID:
3775 switch (typid2)
3776 {
3777 case TIMEOID:
3778 val2 = castTimeToTimeTz(val2, useTz);
3779 cmpfunc = timetz_cmp;
3780
3781 break;
3782
3783 case TIMETZOID:
3784 cmpfunc = timetz_cmp;
3785
3786 break;
3787
3788 case DATEOID:
3789 case TIMESTAMPOID:
3790 case TIMESTAMPTZOID:
3791 *cast_error = true; /* uncomparable types */
3792 return 0;
3793
3794 default:
3795 elog(ERROR, "unrecognized SQL/JSON datetime type oid: %u",
3796 typid2);
3797 }
3798 break;
3799
3800 case TIMESTAMPOID:
3801 switch (typid2)
3802 {
3803 case DATEOID:
3804 return -cmpDateToTimestamp(DatumGetDateADT(val2),
3805 DatumGetTimestamp(val1),
3806 useTz);
3807
3808 case TIMESTAMPOID:
3809 cmpfunc = timestamp_cmp;
3810
3811 break;
3812
3813 case TIMESTAMPTZOID:
3814 return cmpTimestampToTimestampTz(DatumGetTimestamp(val1),
3815 DatumGetTimestampTz(val2),
3816 useTz);
3817
3818 case TIMEOID:
3819 case TIMETZOID:
3820 *cast_error = true; /* uncomparable types */
3821 return 0;
3822
3823 default:
3824 elog(ERROR, "unrecognized SQL/JSON datetime type oid: %u",
3825 typid2);
3826 }
3827 break;
3828
3829 case TIMESTAMPTZOID:
3830 switch (typid2)
3831 {
3832 case DATEOID:
3833 return -cmpDateToTimestampTz(DatumGetDateADT(val2),
3834 DatumGetTimestampTz(val1),
3835 useTz);
3836
3837 case TIMESTAMPOID:
3838 return -cmpTimestampToTimestampTz(DatumGetTimestamp(val2),
3839 DatumGetTimestampTz(val1),
3840 useTz);
3841
3842 case TIMESTAMPTZOID:
3843 cmpfunc = timestamp_cmp;
3844
3845 break;
3846
3847 case TIMEOID:
3848 case TIMETZOID:
3849 *cast_error = true; /* uncomparable types */
3850 return 0;
3851
3852 default:
3853 elog(ERROR, "unrecognized SQL/JSON datetime type oid: %u",
3854 typid2);
3855 }
3856 break;
3857
3858 default:
3859 elog(ERROR, "unrecognized SQL/JSON datetime type oid: %u", typid1);
3860 }
3861
3862 if (*cast_error)
3863 return 0; /* cast error */
3864
3865 return DatumGetInt32(DirectFunctionCall2(cmpfunc, val1, val2));
3866 }
3867
3868 /*
3869 * Executor-callable JSON_EXISTS implementation
3870 *
3871 * Returns NULL instead of throwing errors if 'error' is not NULL, setting
3872 * *error to true.
3873 */
3874 bool
3875 JsonPathExists(Datum jb, JsonPath *jp, bool *error, List *vars)
3876 {
3877 JsonPathExecResult res;
3878
3879 res = executeJsonPath(jp, vars,
3880 GetJsonPathVar, CountJsonPathVars,
3881 DatumGetJsonbP(jb), !error, NULL, true);
3882
3883 Assert(error || !jperIsError(res));
3884
3885 if (error && jperIsError(res))
3886 *error = true;
3887
3888 return res == jperOk;
3889 }
3890
3891 /*
3892 * Executor-callable JSON_QUERY implementation
3893 *
3894 * Returns NULL instead of throwing errors if 'error' is not NULL, setting
3895 * *error to true. *empty is set to true if no match is found.
3896 */
3897 Datum
3898 JsonPathQuery(Datum jb, JsonPath *jp, JsonWrapper wrapper, bool *empty,
3899 bool *error, List *vars,
3900 const char *column_name)
3901 {
3902 JsonbValue *singleton;
3903 bool wrap;
3904 JsonValueList found = {0};
3905 JsonPathExecResult res;
3906 int count;
3907
3908 res = executeJsonPath(jp, vars,
3909 GetJsonPathVar, CountJsonPathVars,
3910 DatumGetJsonbP(jb), !error, &found, true);
3911 Assert(error || !jperIsError(res));
3912 if (error && jperIsError(res))
3913 {
3914 *error = true;
3915 *empty = false;
3916 return (Datum) 0;
3917 }
3918
3919 /*
3920 * Determine whether to wrap the result in a JSON array or not.
3921 *
3922 * First, count the number of SQL/JSON items in the returned
3923 * JsonValueList. If the list is empty (singleton == NULL), no wrapping is
3924 * necessary.
3925 *
3926 * If the wrapper mode is JSW_NONE or JSW_UNSPEC, wrapping is explicitly
3927 * disabled. This enforces a WITHOUT WRAPPER clause, which is also the
3928 * default when no WRAPPER clause is specified.
3929 *
3930 * If the mode is JSW_UNCONDITIONAL, wrapping is enforced regardless of
3931 * the number of SQL/JSON items, enforcing a WITH WRAPPER or WITH
3932 * UNCONDITIONAL WRAPPER clause.
3933 *
3934 * For JSW_CONDITIONAL, wrapping occurs only if there is more than one
3935 * SQL/JSON item in the list, enforcing a WITH CONDITIONAL WRAPPER clause.
3936 */
3937 count = JsonValueListLength(&found);
3938 singleton = count > 0 ? JsonValueListHead(&found) : NULL;
3939 if (singleton == NULL)
3940 wrap = false;
3941 else if (wrapper == JSW_NONE || wrapper == JSW_UNSPEC)
3942 wrap = false;
3943 else if (wrapper == JSW_UNCONDITIONAL)
3944 wrap = true;
3945 else if (wrapper == JSW_CONDITIONAL)
3946 wrap = count > 1;
3947 else
3948 {
3949 elog(ERROR, "unrecognized json wrapper %d", (int) wrapper);
3950 wrap = false;
3951 }
3952
3953 if (wrap)
3954 return JsonbPGetDatum(JsonbValueToJsonb(wrapItemsInArray(&found)));
3955
3956 /* No wrapping means only one item is expected. */
3957 if (count > 1)
3958 {
3959 if (error)
3960 {
3961 *error = true;
3962 return (Datum) 0;
3963 }
3964
3965 if (column_name)
3966 ereport(ERROR,
3967 (errcode(ERRCODE_MORE_THAN_ONE_SQL_JSON_ITEM),
3968 errmsg("JSON path expression for column \"%s\" must return single item when no wrapper is requested",
3969 column_name),
3970 errhint("Use the WITH WRAPPER clause to wrap SQL/JSON items into an array.")));
3971 else
3972 ereport(ERROR,
3973 (errcode(ERRCODE_MORE_THAN_ONE_SQL_JSON_ITEM),
3974 errmsg("JSON path expression in JSON_QUERY must return single item when no wrapper is requested"),
3975 errhint("Use the WITH WRAPPER clause to wrap SQL/JSON items into an array.")));
3976 }
3977
3978 if (singleton)
3979 return JsonbPGetDatum(JsonbValueToJsonb(singleton));
3980
3981 *empty = true;
3982 return PointerGetDatum(NULL);
3983 }
3984
3985 /*
3986 * Executor-callable JSON_VALUE implementation
3987 *
3988 * Returns NULL instead of throwing errors if 'error' is not NULL, setting
3989 * *error to true. *empty is set to true if no match is found.
3990 */
3991 JsonbValue *
3992 JsonPathValue(Datum jb, JsonPath *jp, bool *empty, bool *error, List *vars,
3993 const char *column_name)
3994 {
3995 JsonbValue *res;
3996 JsonValueList found = {0};
3997 JsonPathExecResult jper PG_USED_FOR_ASSERTS_ONLY;
3998 int count;
3999
4000 jper = executeJsonPath(jp, vars, GetJsonPathVar, CountJsonPathVars,
4001 DatumGetJsonbP(jb),
4002 !error, &found, true);
4003
4004 Assert(error || !jperIsError(jper));
4005
4006 if (error && jperIsError(jper))
4007 {
4008 *error = true;
4009 *empty = false;
4010 return NULL;
4011 }
4012
4013 count = JsonValueListLength(&found);
4014
4015 *empty = (count == 0);
4016
4017 if (*empty)
4018 return NULL;
4019
4020 /* JSON_VALUE expects to get only singletons. */
4021 if (count > 1)
4022 {
4023 if (error)
4024 {
4025 *error = true;
4026 return NULL;
4027 }
4028
4029 if (column_name)
4030 ereport(ERROR,
4031 (errcode(ERRCODE_MORE_THAN_ONE_SQL_JSON_ITEM),
4032 errmsg("JSON path expression for column \"%s\" must return single scalar item",
4033 column_name)));
4034 else
4035 ereport(ERROR,
4036 (errcode(ERRCODE_MORE_THAN_ONE_SQL_JSON_ITEM),
4037 errmsg("JSON path expression in JSON_VALUE must return single scalar item")));
4038 }
4039
4040 res = JsonValueListHead(&found);
4041 if (res->type == jbvBinary && JsonContainerIsScalar(res->val.binary.data))
4042 JsonbExtractScalar(res->val.binary.data, res);
4043
4044 /* JSON_VALUE expects to get only scalars. */
4045 if (!IsAJsonbScalar(res))
4046 {
4047 if (error)
4048 {
4049 *error = true;
4050 return NULL;
4051 }
4052
4053 if (column_name)
4054 ereport(ERROR,
4055 (errcode(ERRCODE_SQL_JSON_SCALAR_REQUIRED),
4056 errmsg("JSON path expression for column \"%s\" must return single scalar item",
4057 column_name)));
4058 else
4059 ereport(ERROR,
4060 (errcode(ERRCODE_SQL_JSON_SCALAR_REQUIRED),
4061 errmsg("JSON path expression in JSON_VALUE must return single scalar item")));
4062 }
4063
4064 if (res->type == jbvNull)
4065 return NULL;
4066
4067 return res;
4068 }
4069
4070 /************************ JSON_TABLE functions ***************************/
4071
4072 /*
4073 * Sanity-checks and returns the opaque JsonTableExecContext from the
4074 * given executor state struct.
4075 */
4076 static inline JsonTableExecContext *
4077 GetJsonTableExecContext(TableFuncScanState *state, const char *fname)
4078 {
4079 JsonTableExecContext *result;
4080
4081 if (!IsA(state, TableFuncScanState))
4082 elog(ERROR, "%s called with invalid TableFuncScanState", fname);
4083 result = (JsonTableExecContext *) state->opaque;
4084 if (result->magic != JSON_TABLE_EXEC_CONTEXT_MAGIC)
4085 elog(ERROR, "%s called with invalid TableFuncScanState", fname);
4086
4087 return result;
4088 }
4089
4090 /*
4091 * JsonTableInitOpaque
4092 * Fill in TableFuncScanState->opaque for processing JSON_TABLE
4093 *
4094 * This initializes the PASSING arguments and the JsonTablePlanState for
4095 * JsonTablePlan given in TableFunc.
4096 */
4097 static void
4098 JsonTableInitOpaque(TableFuncScanState *state, int natts)
4099 {
4100 JsonTableExecContext *cxt;
4101 PlanState *ps = &state->ss.ps;
4102 TableFuncScan *tfs = castNode(TableFuncScan, ps->plan);
4103 TableFunc *tf = tfs->tablefunc;
4104 JsonTablePlan *rootplan = (JsonTablePlan *) tf->plan;
4105 JsonExpr *je = castNode(JsonExpr, tf->docexpr);
4106 List *args = NIL;
4107
4108 cxt = palloc0(sizeof(JsonTableExecContext));
4109 cxt->magic = JSON_TABLE_EXEC_CONTEXT_MAGIC;
4110
4111 /*
4112 * Evaluate JSON_TABLE() PASSING arguments to be passed to the jsonpath
4113 * executor via JsonPathVariables.
4114 */
4115 if (state->passingvalexprs)
4116 {
4117 ListCell *exprlc;
4118 ListCell *namelc;
4119
4120 Assert(list_length(state->passingvalexprs) ==
4121 list_length(je->passing_names));
4122 forboth(exprlc, state->passingvalexprs,
4123 namelc, je->passing_names)
4124 {
4125 ExprState *state = lfirst_node(ExprState, exprlc);
4126 String *name = lfirst_node(String, namelc);
4127 JsonPathVariable *var = palloc(sizeof(*var));
4128
4129 var->name = pstrdup(name->sval);
4130 var->namelen = strlen(var->name);
4131 var->typid = exprType((Node *) state->expr);
4132 var->typmod = exprTypmod((Node *) state->expr);
4133
4134 /*
4135 * Evaluate the expression and save the value to be returned by
4136 * GetJsonPathVar().
4137 */
4138 var->value = ExecEvalExpr(state, ps->ps_ExprContext,
4139 &var->isnull);
4140
4141 args = lappend(args, var);
4142 }
4143 }
4144
4145 cxt->colplanstates = palloc(sizeof(JsonTablePlanState *) *
4146 list_length(tf->colvalexprs));
4147
4148 /*
4149 * Initialize plan for the root path and, recursively, also any child
4150 * plans that compute the NESTED paths.
4151 */
4152 cxt->rootplanstate = JsonTableInitPlan(cxt, rootplan, NULL, args,
4153 CurrentMemoryContext);
4154
4155 state->opaque = cxt;
4156 }
4157
4158 /*
4159 * JsonTableDestroyOpaque
4160 * Resets state->opaque
4161 */
4162 static void
4163 JsonTableDestroyOpaque(TableFuncScanState *state)
4164 {
4165 JsonTableExecContext *cxt =
4166 GetJsonTableExecContext(state, "JsonTableDestroyOpaque");
4167
4168 /* not valid anymore */
4169 cxt->magic = 0;
4170
4171 state->opaque = NULL;
4172 }
4173
4174 /*
4175 * JsonTableInitPlan
4176 * Initialize information for evaluating jsonpath in the given
4177 * JsonTablePlan and, recursively, in any child plans
4178 */
4179 static JsonTablePlanState *
4180 JsonTableInitPlan(JsonTableExecContext *cxt, JsonTablePlan *plan,
4181 JsonTablePlanState *parentstate,
4182 List *args, MemoryContext mcxt)
4183 {
4184 JsonTablePlanState *planstate = palloc0(sizeof(*planstate));
4185
4186 planstate->plan = plan;
4187 planstate->parent = parentstate;
4188
4189 if (IsA(plan, JsonTablePathScan))
4190 {
4191 JsonTablePathScan *scan = (JsonTablePathScan *) plan;
4192 int i;
4193
4194 planstate->path = DatumGetJsonPathP(scan->path->value->constvalue);
4195 planstate->args = args;
4196 planstate->mcxt = AllocSetContextCreate(mcxt, "JsonTableExecContext",
4197 ALLOCSET_DEFAULT_SIZES);
4198
4199 /* No row pattern evaluated yet. */
4200 planstate->current.value = PointerGetDatum(NULL);
4201 planstate->current.isnull = true;
4202
4203 for (i = scan->colMin; i >= 0 && i <= scan->colMax; i++)
4204 cxt->colplanstates[i] = planstate;
4205
4206 planstate->nested = scan->child ?
4207 JsonTableInitPlan(cxt, scan->child, planstate, args, mcxt) : NULL;
4208 }
4209 else if (IsA(plan, JsonTableSiblingJoin))
4210 {
4211 JsonTableSiblingJoin *join = (JsonTableSiblingJoin *) plan;
4212
4213 planstate->left = JsonTableInitPlan(cxt, join->lplan, parentstate,
4214 args, mcxt);
4215 planstate->right = JsonTableInitPlan(cxt, join->rplan, parentstate,
4216 args, mcxt);
4217 }
4218
4219 return planstate;
4220 }
4221
4222 /*
4223 * JsonTableSetDocument
4224 * Install the input document and evaluate the row pattern
4225 */
4226 static void
4227 JsonTableSetDocument(TableFuncScanState *state, Datum value)
4228 {
4229 JsonTableExecContext *cxt =
4230 GetJsonTableExecContext(state, "JsonTableSetDocument");
4231
4232 JsonTableResetRowPattern(cxt->rootplanstate, value);
4233 }
4234
4235 /*
4236 * Evaluate a JsonTablePlan's jsonpath to get a new row pattern from
4237 * the given context item
4238 */
4239 static void
4240 JsonTableResetRowPattern(JsonTablePlanState *planstate, Datum item)
4241 {
4242 JsonTablePathScan *scan = castNode(JsonTablePathScan, planstate->plan);
4243 MemoryContext oldcxt;
4244 JsonPathExecResult res;
4245 Jsonb *js = (Jsonb *) DatumGetJsonbP(item);
4246
4247 JsonValueListClear(&planstate->found);
4248
4249 MemoryContextResetOnly(planstate->mcxt);
4250
4251 oldcxt = MemoryContextSwitchTo(planstate->mcxt);
4252
4253 res = executeJsonPath(planstate->path, planstate->args,
4254 GetJsonPathVar, CountJsonPathVars,
4255 js, scan->errorOnError,
4256 &planstate->found,
4257 true);
4258
4259 MemoryContextSwitchTo(oldcxt);
4260
4261 if (jperIsError(res))
4262 {
4263 Assert(!scan->errorOnError);
4264 JsonValueListClear(&planstate->found);
4265 }
4266
4267 /* Reset plan iterator to the beginning of the item list */
4268 JsonValueListInitIterator(&planstate->found, &planstate->iter);
4269 planstate->current.value = PointerGetDatum(NULL);
4270 planstate->current.isnull = true;
4271 planstate->ordinal = 0;
4272 }
4273
4274 /*
4275 * Fetch next row from a JsonTablePlan.
4276 *
4277 * Returns false if the plan has run out of rows, true otherwise.
4278 */
4279 static bool
4280 JsonTablePlanNextRow(JsonTablePlanState *planstate)
4281 {
4282 if (IsA(planstate->plan, JsonTablePathScan))
4283 return JsonTablePlanScanNextRow(planstate);
4284 else if (IsA(planstate->plan, JsonTableSiblingJoin))
4285 return JsonTablePlanJoinNextRow(planstate);
4286 else
4287 elog(ERROR, "invalid JsonTablePlan %d", (int) planstate->plan->type);
4288
4289 Assert(false);
4290 /* Appease compiler */
4291 return false;
4292 }
4293
4294 /*
4295 * Fetch next row from a JsonTablePlan's path evaluation result and from
4296 * any child nested path(s).
4297 *
4298 * Returns true if any of the paths (this or the nested) has more rows to
4299 * return.
4300 *
4301 * By fetching the nested path(s)'s rows based on the parent row at each
4302 * level, this essentially joins the rows of different levels. If a nested
4303 * path at a given level has no matching rows, the columns of that level will
4304 * compute to NULL, making it an OUTER join.
4305 */
4306 static bool
4307 JsonTablePlanScanNextRow(JsonTablePlanState *planstate)
4308 {
4309 JsonbValue *jbv;
4310 MemoryContext oldcxt;
4311
4312 /*
4313 * If planstate already has an active row and there is a nested plan,
4314 * check if it has an active row to join with the former.
4315 */
4316 if (!planstate->current.isnull)
4317 {
4318 if (planstate->nested && JsonTablePlanNextRow(planstate->nested))
4319 return true;
4320 }
4321
4322 /* Fetch new row from the list of found values to set as active. */
4323 jbv = JsonValueListNext(&planstate->found, &planstate->iter);
4324
4325 /* End of list? */
4326 if (jbv == NULL)
4327 {
4328 planstate->current.value = PointerGetDatum(NULL);
4329 planstate->current.isnull = true;
4330 return false;
4331 }
4332
4333 /*
4334 * Set current row item for subsequent JsonTableGetValue() calls for
4335 * evaluating individual columns.
4336 */
4337 oldcxt = MemoryContextSwitchTo(planstate->mcxt);
4338 planstate->current.value = JsonbPGetDatum(JsonbValueToJsonb(jbv));
4339 planstate->current.isnull = false;
4340 MemoryContextSwitchTo(oldcxt);
4341
4342 /* Next row! */
4343 planstate->ordinal++;
4344
4345 /* Process nested plan(s), if any. */
4346 if (planstate->nested)
4347 {
4348 /* Re-evaluate the nested path using the above parent row. */
4349 JsonTableResetNestedPlan(planstate->nested);
4350
4351 /*
4352 * Now fetch the nested plan's current row to be joined against the
4353 * parent row. Any further nested plans' paths will be re-evaluated
4354 * recursively, level at a time, after setting each nested plan's
4355 * current row.
4356 */
4357 (void) JsonTablePlanNextRow(planstate->nested);
4358 }
4359
4360 /* There are more rows. */
4361 return true;
4362 }
4363
4364 /*
4365 * Re-evaluate the row pattern of a nested plan using the new parent row
4366 * pattern.
4367 */
4368 static void
4369 JsonTableResetNestedPlan(JsonTablePlanState *planstate)
4370 {
4371 /* This better be a child plan. */
4372 Assert(planstate->parent != NULL);
4373 if (IsA(planstate->plan, JsonTablePathScan))
4374 {
4375 JsonTablePlanState *parent = planstate->parent;
4376
4377 if (!parent->current.isnull)
4378 JsonTableResetRowPattern(planstate, parent->current.value);
4379
4380 /*
4381 * If this plan itself has a child nested plan, it will be reset when
4382 * the caller calls JsonTablePlanNextRow() on this plan.
4383 */
4384 }
4385 else if (IsA(planstate->plan, JsonTableSiblingJoin))
4386 {
4387 JsonTableResetNestedPlan(planstate->left);
4388 JsonTableResetNestedPlan(planstate->right);
4389 }
4390 }
4391
4392 /*
4393 * Fetch the next row from a JsonTableSiblingJoin.
4394 *
4395 * This is essentially a UNION between the rows from left and right siblings.
4396 */
4397 static bool
4398 JsonTablePlanJoinNextRow(JsonTablePlanState *planstate)
4399 {
4400
4401 /* Fetch row from left sibling. */
4402 if (!JsonTablePlanNextRow(planstate->left))
4403 {
4404 /*
4405 * Left sibling ran out of rows, so start fetching from the right
4406 * sibling.
4407 */
4408 if (!JsonTablePlanNextRow(planstate->right))
4409 {
4410 /* Right sibling ran out of rows too, so there are no more rows. */
4411 return false;
4412 }
4413 }
4414
4415 return true;
4416 }
4417
4418 /*
4419 * JsonTableFetchRow
4420 * Prepare the next "current" row for upcoming GetValue calls.
4421 *
4422 * Returns false if no more rows can be returned.
4423 */
4424 static bool
4425 JsonTableFetchRow(TableFuncScanState *state)
4426 {
4427 JsonTableExecContext *cxt =
4428 GetJsonTableExecContext(state, "JsonTableFetchRow");
4429
4430 return JsonTablePlanNextRow(cxt->rootplanstate);
4431 }
4432
4433 /*
4434 * JsonTableGetValue
4435 * Return the value for column number 'colnum' for the current row.
4436 *
4437 * This leaks memory, so be sure to reset often the context in which it's
4438 * called.
4439 */
4440 static Datum
4441 JsonTableGetValue(TableFuncScanState *state, int colnum,
4442 Oid typid, int32 typmod, bool *isnull)
4443 {
4444 JsonTableExecContext *cxt =
4445 GetJsonTableExecContext(state, "JsonTableGetValue");
4446 ExprContext *econtext = state->ss.ps.ps_ExprContext;
4447 ExprState *estate = list_nth(state->colvalexprs, colnum);
4448 JsonTablePlanState *planstate = cxt->colplanstates[colnum];
4449 JsonTablePlanRowSource *current = &planstate->current;
4450 Datum result;
4451
4452 /* Row pattern value is NULL */
4453 if (current->isnull)
4454 {
4455 result = (Datum) 0;
4456 *isnull = true;
4457 }
4458 /* Evaluate JsonExpr. */
4459 else if (estate)
4460 {
4461 Datum saved_caseValue = econtext->caseValue_datum;
4462 bool saved_caseIsNull = econtext->caseValue_isNull;
4463
4464 /* Pass the row pattern value via CaseTestExpr. */
4465 econtext->caseValue_datum = current->value;
4466 econtext->caseValue_isNull = false;
4467
4468 result = ExecEvalExpr(estate, econtext, isnull);
4469
4470 econtext->caseValue_datum = saved_caseValue;
4471 econtext->caseValue_isNull = saved_caseIsNull;
4472 }
4473 /* ORDINAL column */
4474 else
4475 {
4476 result = Int32GetDatum(planstate->ordinal);
4477 *isnull = false;
4478 }
4479
4480 return result;
4481 }