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