LCOV - code coverage report
Current view: top level - src/backend/utils/adt - jsonpath_exec.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 92.4 % 1810 1673
Test Date: 2026-11-23 10:16:17 Functions: 95.5 % 88 84
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 77.1 % 1268 977

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

Generated by: LCOV version 2.0-1