LCOV - differential code coverage report
Current view: top level - src/backend/utils/adt - jsonb.c (source / functions) Coverage Total Hit UNC UBC GNC CBC DCB
Current: 4b3c9325757dfd8f2312e9f1a8decf4431f344ae vs e87b024bfb8dd55e3049b1b6e6ab4e810cf1abc8 Lines: 88.9 % 839 746 93 1 745 1
Current Date: 2026-11-28 16:48:44 +0900 Functions: 93.0 % 57 53 4 1 52
Baseline: lcov-20261128-baseline Branches: 70.1 % 499 350 1 148 1 349
Baseline Date: 2026-11-28 16:48:48 +0900 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(7,30] days: 22.2 % 18 4 14 4
(30,360] days: 86.3 % 131 113 18 1 112
(360..) days: 91.2 % 690 629 61 629
Function coverage date bins:
(30,360] days: 100.0 % 1 1 1
(360..) days: 92.9 % 56 52 4 52
Branch coverage date bins:
(7,30] days: 10.0 % 10 1 9 1
(30,360] days: 69.7 % 33 23 1 9 1 22
(360..) days: 71.5 % 456 326 130 326

 Age         Owner                    Branch data    TLA  Line data    Source code
                                  1                 :                : /*-------------------------------------------------------------------------
                                  2                 :                :  *
                                  3                 :                :  * jsonb.c
                                  4                 :                :  *      I/O routines for jsonb type
                                  5                 :                :  *
                                  6                 :                :  * Copyright (c) 2014-2026, PostgreSQL Global Development Group
                                  7                 :                :  *
                                  8                 :                :  * IDENTIFICATION
                                  9                 :                :  *    src/backend/utils/adt/jsonb.c
                                 10                 :                :  *
                                 11                 :                :  *-------------------------------------------------------------------------
                                 12                 :                :  */
                                 13                 :                : #include "postgres.h"
                                 14                 :                : 
                                 15                 :                : #include "access/htup_details.h"
                                 16                 :                : #include "catalog/objectaccess.h"
                                 17                 :                : #include "catalog/pg_proc.h"
                                 18                 :                : #include "catalog/pg_type.h"
                                 19                 :                : #include "funcapi.h"
                                 20                 :                : #include "libpq/pqformat.h"
                                 21                 :                : #include "miscadmin.h"
                                 22                 :                : #include "utils/acl.h"
                                 23                 :                : #include "utils/builtins.h"
                                 24                 :                : #include "utils/fmgroids.h"
                                 25                 :                : #include "utils/json.h"
                                 26                 :                : #include "utils/jsonb.h"
                                 27                 :                : #include "utils/jsonfuncs.h"
                                 28                 :                : #include "utils/lsyscache.h"
                                 29                 :                : #include "utils/typcache.h"
                                 30                 :                : 
                                 31                 :                : typedef struct JsonbAggState
                                 32                 :                : {
                                 33                 :                :     JsonbInState pstate;
                                 34                 :                :     JsonTypeCategory key_category;
                                 35                 :                :     Oid         key_output_func;
                                 36                 :                :     JsonTypeCategory val_category;
                                 37                 :                :     Oid         val_output_func;
                                 38                 :                : } JsonbAggState;
                                 39                 :                : 
                                 40                 :                : static inline Datum jsonb_from_cstring(char *json, int len, bool unique_keys,
                                 41                 :                :                                        Node *escontext);
                                 42                 :                : static bool checkStringLen(size_t len, Node *escontext);
                                 43                 :                : static JsonParseErrorType jsonb_in_object_start(void *pstate);
                                 44                 :                : static JsonParseErrorType jsonb_in_object_end(void *pstate);
                                 45                 :                : static JsonParseErrorType jsonb_in_array_start(void *pstate);
                                 46                 :                : static JsonParseErrorType jsonb_in_array_end(void *pstate);
                                 47                 :                : static JsonParseErrorType jsonb_in_object_field_start(void *pstate, char *fname, bool isnull);
                                 48                 :                : static void jsonb_put_escaped_value(StringInfo out, JsonbValue *scalarVal);
                                 49                 :                : static JsonParseErrorType jsonb_in_scalar(void *pstate, char *token, JsonTokenType tokentype);
                                 50                 :                : static void composite_to_jsonb(Datum composite, JsonbInState *result);
                                 51                 :                : static void array_dim_to_jsonb(JsonbInState *result, int dim, int ndims, int *dims,
                                 52                 :                :                                const Datum *vals, const bool *nulls, int *valcount,
                                 53                 :                :                                JsonTypeCategory tcategory, Oid outfuncoid);
                                 54                 :                : static void array_to_jsonb_internal(Datum array, JsonbInState *result);
                                 55                 :                : static void datum_to_jsonb_internal(Datum val, bool is_null, JsonbInState *result,
                                 56                 :                :                                     JsonTypeCategory tcategory, Oid outfuncoid,
                                 57                 :                :                                     bool key_scalar);
                                 58                 :                : static void add_jsonb(Datum val, bool is_null, JsonbInState *result,
                                 59                 :                :                       Oid val_type, bool key_scalar);
                                 60                 :                : static char *JsonbToCStringWorker(StringInfo out, JsonbContainer *in, int estimated_len, bool indent);
                                 61                 :                : static void add_indent(StringInfo out, bool indent, int level);
                                 62                 :                : 
                                 63                 :                : /*
                                 64                 :                :  * jsonb type input function
                                 65                 :                :  */
                                 66                 :                : Datum
 4633 andrew@dunslane.net        67                 :CBC       17749 : jsonb_in(PG_FUNCTION_ARGS)
                                 68                 :                : {
                                 69                 :          17749 :     char       *json = PG_GETARG_CSTRING(0);
                                 70                 :                : 
 1227 amitlan@postgresql.o       71                 :          17749 :     return jsonb_from_cstring(json, strlen(json), false, fcinfo->context);
                                 72                 :                : }
                                 73                 :                : 
                                 74                 :                : /*
                                 75                 :                :  * jsonb type recv function
                                 76                 :                :  *
                                 77                 :                :  * The type is sent as text in binary mode, so this is almost the same
                                 78                 :                :  * as the input function, but it's prefixed with a version number so we
                                 79                 :                :  * can change the binary format sent in future if necessary. For now,
                                 80                 :                :  * only version 1 is supported.
                                 81                 :                :  */
                                 82                 :                : Datum
 4633 andrew@dunslane.net        83                 :UBC           0 : jsonb_recv(PG_FUNCTION_ARGS)
                                 84                 :                : {
                                 85                 :              0 :     StringInfo  buf = (StringInfo) PG_GETARG_POINTER(0);
                                 86                 :              0 :     int         version = pq_getmsgint(buf, 1);
                                 87                 :                :     char       *str;
                                 88                 :                :     int         nbytes;
                                 89                 :                : 
                                 90         [ #  # ]:              0 :     if (version == 1)
                                 91                 :              0 :         str = pq_getmsgtext(buf, buf->len - buf->cursor, &nbytes);
                                 92                 :                :     else
 4588 heikki.linnakangas@i       93         [ #  # ]:              0 :         elog(ERROR, "unsupported jsonb version number %d", version);
                                 94                 :                : 
 1227 amitlan@postgresql.o       95                 :              0 :     return jsonb_from_cstring(str, nbytes, false, NULL);
                                 96                 :                : }
                                 97                 :                : 
                                 98                 :                : /*
                                 99                 :                :  * jsonb type output function
                                100                 :                :  */
                                101                 :                : Datum
 4633 andrew@dunslane.net       102                 :CBC       14235 : jsonb_out(PG_FUNCTION_ARGS)
                                103                 :                : {
 3358 tgl@sss.pgh.pa.us         104                 :          14235 :     Jsonb      *jb = PG_GETARG_JSONB_P(0);
                                105                 :                :     char       *out;
                                106                 :                : 
 4588 heikki.linnakangas@i      107                 :          14235 :     out = JsonbToCString(NULL, &jb->root, VARSIZE(jb));
                                108                 :                : 
 4633 andrew@dunslane.net       109                 :          14235 :     PG_RETURN_CSTRING(out);
                                110                 :                : }
                                111                 :                : 
                                112                 :                : /*
                                113                 :                :  * jsonb type send function
                                114                 :                :  *
                                115                 :                :  * Just send jsonb as a version number, then a string of text
                                116                 :                :  */
                                117                 :                : Datum
 4633 andrew@dunslane.net       118                 :UBC           0 : jsonb_send(PG_FUNCTION_ARGS)
                                119                 :                : {
 3358 tgl@sss.pgh.pa.us         120                 :              0 :     Jsonb      *jb = PG_GETARG_JSONB_P(0);
                                121                 :                :     StringInfoData buf;
                                122                 :                :     StringInfoData jtext;
 4633 andrew@dunslane.net       123                 :              0 :     int         version = 1;
                                124                 :                : 
  387 drowley@postgresql.o      125                 :              0 :     initStringInfo(&jtext);
                                126                 :              0 :     (void) JsonbToCString(&jtext, &jb->root, VARSIZE(jb));
                                127                 :                : 
 4633 andrew@dunslane.net       128                 :              0 :     pq_begintypsend(&buf);
 3335 andres@anarazel.de        129                 :              0 :     pq_sendint8(&buf, version);
  387 drowley@postgresql.o      130                 :              0 :     pq_sendtext(&buf, jtext.data, jtext.len);
                                131                 :              0 :     pfree(jtext.data);
                                132                 :                : 
 4633 andrew@dunslane.net       133                 :              0 :     PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
                                134                 :                : }
                                135                 :                : 
                                136                 :                : /*
                                137                 :                :  * jsonb_from_text
                                138                 :                :  *
                                139                 :                :  * Turns json text string into a jsonb Datum.
                                140                 :                :  */
                                141                 :                : Datum
 1227 amitlan@postgresql.o      142                 :              0 : jsonb_from_text(text *js, bool unique_keys)
                                143                 :                : {
 1226                           144                 :              0 :     return jsonb_from_cstring(VARDATA_ANY(js),
                                145                 :              0 :                               VARSIZE_ANY_EXHDR(js),
                                146                 :                :                               unique_keys,
                                147                 :                :                               NULL);
                                148                 :                : }
                                149                 :                : 
                                150                 :                : /*
                                151                 :                :  * Get the type name of a jsonb container.
                                152                 :                :  */
                                153                 :                : static const char *
 2814 akorotkov@postgresql      154                 :CBC         229 : JsonbContainerTypeName(JsonbContainer *jbc)
                                155                 :                : {
                                156                 :                :     JsonbValue  scalar;
                                157                 :                : 
                                158         [ +  + ]:            229 :     if (JsonbExtractScalar(jbc, &scalar))
                                159                 :             55 :         return JsonbTypeName(&scalar);
                                160         [ +  + ]:            174 :     else if (JsonContainerIsArray(jbc))
                                161                 :             70 :         return "array";
                                162         [ +  - ]:            104 :     else if (JsonContainerIsObject(jbc))
                                163                 :            104 :         return "object";
                                164                 :                :     else
                                165                 :                :     {
 2814 akorotkov@postgresql      166         [ #  # ]:UBC           0 :         elog(ERROR, "invalid jsonb container type: 0x%08x", jbc->header);
                                167                 :                :         return "unknown";
                                168                 :                :     }
                                169                 :                : }
                                170                 :                : 
                                171                 :                : /*
                                172                 :                :  * Get the type name of a jsonb value.
                                173                 :                :  */
                                174                 :                : const char *
 1530 pg@bowt.ie                175                 :CBC         291 : JsonbTypeName(JsonbValue *val)
                                176                 :                : {
                                177   [ +  -  -  +  :            291 :     switch (val->type)
                                        +  +  +  +  
                                                 - ]
                                178                 :                :     {
 2814 akorotkov@postgresql      179                 :             16 :         case jbvBinary:
 1530 pg@bowt.ie                180                 :             16 :             return JsonbContainerTypeName(val->val.binary.data);
 2814 akorotkov@postgresql      181                 :UBC           0 :         case jbvObject:
                                182                 :              0 :             return "object";
                                183                 :              0 :         case jbvArray:
                                184                 :              0 :             return "array";
 2814 akorotkov@postgresql      185                 :CBC          65 :         case jbvNumeric:
                                186                 :             65 :             return "number";
                                187                 :             87 :         case jbvString:
                                188                 :             87 :             return "string";
                                189                 :             38 :         case jbvBool:
                                190                 :             38 :             return "boolean";
                                191                 :             17 :         case jbvNull:
                                192                 :             17 :             return "null";
 2621                           193                 :             68 :         case jbvDatetime:
 1530 pg@bowt.ie                194   [ +  +  +  +  :             68 :             switch (val->val.datetime.typid)
                                              +  - ]
                                195                 :                :             {
 2621 akorotkov@postgresql      196                 :             12 :                 case DATEOID:
                                197                 :             12 :                     return "date";
                                198                 :             12 :                 case TIMEOID:
                                199                 :             12 :                     return "time without time zone";
                                200                 :             16 :                 case TIMETZOID:
                                201                 :             16 :                     return "time with time zone";
                                202                 :             12 :                 case TIMESTAMPOID:
                                203                 :             12 :                     return "timestamp without time zone";
                                204                 :             16 :                 case TIMESTAMPTZOID:
                                205                 :             16 :                     return "timestamp with time zone";
 2621 akorotkov@postgresql      206                 :UBC           0 :                 default:
                                207         [ #  # ]:              0 :                     elog(ERROR, "unrecognized jsonb value datetime type: %d",
                                208                 :                :                          val->val.datetime.typid);
                                209                 :                :             }
                                210                 :                :             return "unknown";
 2814                           211                 :              0 :         default:
 1530 pg@bowt.ie                212         [ #  # ]:              0 :             elog(ERROR, "unrecognized jsonb value type: %d", val->type);
                                213                 :                :             return "unknown";
                                214                 :                :     }
                                215                 :                : }
                                216                 :                : 
                                217                 :                : /*
                                218                 :                :  * SQL function jsonb_typeof(jsonb) -> text
                                219                 :                :  *
                                220                 :                :  * This function is here because the analog json function is in json.c, since
                                221                 :                :  * it uses the json parser internals not exposed elsewhere.
                                222                 :                :  */
                                223                 :                : Datum
 4633 andrew@dunslane.net       224                 :CBC         213 : jsonb_typeof(PG_FUNCTION_ARGS)
                                225                 :                : {
 3358 tgl@sss.pgh.pa.us         226                 :            213 :     Jsonb      *in = PG_GETARG_JSONB_P(0);
 2814 akorotkov@postgresql      227                 :            213 :     const char *result = JsonbContainerTypeName(&in->root);
                                228                 :                : 
 4633 andrew@dunslane.net       229                 :            213 :     PG_RETURN_TEXT_P(cstring_to_text(result));
                                230                 :                : }
                                231                 :                : 
                                232                 :                : /*
                                233                 :                :  * jsonb_from_cstring
                                234                 :                :  *
                                235                 :                :  * Turns json string into a jsonb Datum.
                                236                 :                :  *
                                237                 :                :  * Uses the json parser (with hooks) to construct a jsonb.
                                238                 :                :  *
                                239                 :                :  * If escontext points to an ErrorSaveContext, errors are reported there
                                240                 :                :  * instead of being thrown.
                                241                 :                :  */
                                242                 :                : static inline Datum
 1227 amitlan@postgresql.o      243                 :          17749 : jsonb_from_cstring(char *json, int len, bool unique_keys, Node *escontext)
                                244                 :                : {
                                245                 :                :     JsonLexContext lex;
                                246                 :                :     JsonbInState state;
                                247                 :                :     JsonSemAction sem;
                                248                 :                : 
 4633 andrew@dunslane.net       249                 :          17749 :     memset(&state, 0, sizeof(state));
                                250                 :          17749 :     memset(&sem, 0, sizeof(sem));
 1150 alvherre@alvh.no-ip.      251                 :          17749 :     makeJsonLexContextCstringLen(&lex, json, len, GetDatabaseEncoding(), true);
                                252                 :                : 
 1227 amitlan@postgresql.o      253                 :          17749 :     state.unique_keys = unique_keys;
 1448 tgl@sss.pgh.pa.us         254                 :          17749 :     state.escontext = escontext;
  730 peter@eisentraut.org      255                 :          17749 :     sem.semstate = &state;
                                256                 :                : 
 4633 andrew@dunslane.net       257                 :          17749 :     sem.object_start = jsonb_in_object_start;
                                258                 :          17749 :     sem.array_start = jsonb_in_array_start;
                                259                 :          17749 :     sem.object_end = jsonb_in_object_end;
                                260                 :          17749 :     sem.array_end = jsonb_in_array_end;
                                261                 :          17749 :     sem.scalar = jsonb_in_scalar;
                                262                 :          17749 :     sem.object_field_start = jsonb_in_object_field_start;
                                263                 :                : 
 1150 alvherre@alvh.no-ip.      264         [ +  + ]:          17749 :     if (!pg_parse_json_or_errsave(&lex, &sem, escontext))
 1448 tgl@sss.pgh.pa.us         265                 :             28 :         return (Datum) 0;
                                266                 :                : 
                                267                 :                :     /* after parsing, the result field has the composed jsonb structure */
  356                           268                 :          17562 :     PG_RETURN_POINTER(JsonbValueToJsonb(state.result));
                                269                 :                : }
                                270                 :                : 
                                271                 :                : static bool
 1448                           272                 :          58018 : checkStringLen(size_t len, Node *escontext)
                                273                 :                : {
 4443                           274         [ -  + ]:          58018 :     if (len > JENTRY_OFFLENMASK)
 1448 tgl@sss.pgh.pa.us         275         [ #  # ]:UBC           0 :         ereturn(escontext, false,
                                276                 :                :                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
                                277                 :                :                  errmsg("string too long to represent as jsonb string"),
                                278                 :                :                  errdetail("Due to an implementation restriction, jsonb strings cannot exceed %d bytes.",
                                279                 :                :                            JENTRY_OFFLENMASK)));
                                280                 :                : 
 1448 tgl@sss.pgh.pa.us         281                 :CBC       58018 :     return true;
                                282                 :                : }
                                283                 :                : 
                                284                 :                : static JsonParseErrorType
 4633 andrew@dunslane.net       285                 :          15421 : jsonb_in_object_start(void *pstate)
                                286                 :                : {
                                287                 :          15421 :     JsonbInState *_state = (JsonbInState *) pstate;
                                288                 :                : 
  356 tgl@sss.pgh.pa.us         289                 :          15421 :     pushJsonbValue(_state, WJB_BEGIN_OBJECT, NULL);
 1227 amitlan@postgresql.o      290                 :          15421 :     _state->parseState->unique_keys = _state->unique_keys;
                                291                 :                : 
 1448 tgl@sss.pgh.pa.us         292                 :          15421 :     return JSON_SUCCESS;
                                293                 :                : }
                                294                 :                : 
                                295                 :                : static JsonParseErrorType
 4633 andrew@dunslane.net       296                 :          13074 : jsonb_in_object_end(void *pstate)
                                297                 :                : {
                                298                 :          13074 :     JsonbInState *_state = (JsonbInState *) pstate;
                                299                 :                : 
  356 tgl@sss.pgh.pa.us         300                 :          13074 :     pushJsonbValue(_state, WJB_END_OBJECT, NULL);
                                301                 :                : 
 1448                           302                 :          13074 :     return JSON_SUCCESS;
                                303                 :                : }
                                304                 :                : 
                                305                 :                : static JsonParseErrorType
 4633 andrew@dunslane.net       306                 :           9900 : jsonb_in_array_start(void *pstate)
                                307                 :                : {
                                308                 :           9900 :     JsonbInState *_state = (JsonbInState *) pstate;
                                309                 :                : 
  356 tgl@sss.pgh.pa.us         310                 :           9900 :     pushJsonbValue(_state, WJB_BEGIN_ARRAY, NULL);
                                311                 :                : 
 1448                           312                 :           9900 :     return JSON_SUCCESS;
                                313                 :                : }
                                314                 :                : 
                                315                 :                : static JsonParseErrorType
 4633 andrew@dunslane.net       316                 :           7048 : jsonb_in_array_end(void *pstate)
                                317                 :                : {
                                318                 :           7048 :     JsonbInState *_state = (JsonbInState *) pstate;
                                319                 :                : 
  356 tgl@sss.pgh.pa.us         320                 :           7048 :     pushJsonbValue(_state, WJB_END_ARRAY, NULL);
                                321                 :                : 
 1448                           322                 :           7048 :     return JSON_SUCCESS;
                                323                 :                : }
                                324                 :                : 
                                325                 :                : static JsonParseErrorType
 4633 andrew@dunslane.net       326                 :          36264 : jsonb_in_object_field_start(void *pstate, char *fname, bool isnull)
                                327                 :                : {
                                328                 :          36264 :     JsonbInState *_state = (JsonbInState *) pstate;
                                329                 :                :     JsonbValue  v;
                                330                 :                : 
 4589 bruce@momjian.us          331         [ -  + ]:          36264 :     Assert(fname != NULL);
 4633 andrew@dunslane.net       332                 :          36264 :     v.type = jbvString;
 1448 tgl@sss.pgh.pa.us         333                 :          36264 :     v.val.string.len = strlen(fname);
                                334         [ -  + ]:          36264 :     if (!checkStringLen(v.val.string.len, _state->escontext))
 1448 tgl@sss.pgh.pa.us         335                 :UBC           0 :         return JSON_SEM_ACTION_FAILED;
 4586 heikki.linnakangas@i      336                 :CBC       36264 :     v.val.string.val = fname;
                                337                 :                : 
  356 tgl@sss.pgh.pa.us         338                 :          36264 :     pushJsonbValue(_state, WJB_KEY, &v);
                                339                 :                : 
 1448                           340                 :          36264 :     return JSON_SUCCESS;
                                341                 :                : }
                                342                 :                : 
                                343                 :                : static void
 4589 bruce@momjian.us          344                 :          63678 : jsonb_put_escaped_value(StringInfo out, JsonbValue *scalarVal)
                                345                 :                : {
 4633 andrew@dunslane.net       346   [ +  +  +  +  :          63678 :     switch (scalarVal->type)
                                                 - ]
                                347                 :                :     {
                                348                 :           1070 :         case jbvNull:
                                349                 :           1070 :             appendBinaryStringInfo(out, "null", 4);
                                350                 :           1070 :             break;
                                351                 :          41928 :         case jbvString:
  854 drowley@postgresql.o      352                 :          41928 :             escape_json_with_len(out, scalarVal->val.string.val, scalarVal->val.string.len);
 4633 andrew@dunslane.net       353                 :          41928 :             break;
                                354                 :          13082 :         case jbvNumeric:
                                355                 :          13082 :             appendStringInfoString(out,
 3447 tgl@sss.pgh.pa.us         356                 :          13082 :                                    DatumGetCString(DirectFunctionCall1(numeric_out,
                                357                 :                :                                                                        PointerGetDatum(scalarVal->val.numeric))));
 4633 andrew@dunslane.net       358                 :          13082 :             break;
                                359                 :           7598 :         case jbvBool:
 4623 tgl@sss.pgh.pa.us         360         [ +  + ]:           7598 :             if (scalarVal->val.boolean)
 4633 andrew@dunslane.net       361                 :           3580 :                 appendBinaryStringInfo(out, "true", 4);
                                362                 :                :             else
                                363                 :           4018 :                 appendBinaryStringInfo(out, "false", 5);
                                364                 :           7598 :             break;
 4633 andrew@dunslane.net       365                 :UBC           0 :         default:
                                366         [ #  # ]:              0 :             elog(ERROR, "unknown jsonb scalar type");
                                367                 :                :     }
 4633 andrew@dunslane.net       368                 :CBC       63678 : }
                                369                 :                : 
                                370                 :                : /*
                                371                 :                :  * For jsonb we always want the de-escaped value - that's what's in token
                                372                 :                :  */
                                373                 :                : static JsonParseErrorType
                                374                 :          46999 : jsonb_in_scalar(void *pstate, char *token, JsonTokenType tokentype)
                                375                 :                : {
                                376                 :          46999 :     JsonbInState *_state = (JsonbInState *) pstate;
                                377                 :                :     JsonbValue  v;
                                378                 :                :     Datum       numd;
                                379                 :                : 
                                380   [ +  +  +  +  :          46999 :     switch (tokentype)
                                              +  - ]
                                381                 :                :     {
                                382                 :                : 
                                383                 :          19984 :         case JSON_TOKEN_STRING:
 4589 bruce@momjian.us          384         [ -  + ]:          19984 :             Assert(token != NULL);
 4633 andrew@dunslane.net       385                 :          19984 :             v.type = jbvString;
 1448 tgl@sss.pgh.pa.us         386                 :          19984 :             v.val.string.len = strlen(token);
                                387         [ -  + ]:          19984 :             if (!checkStringLen(v.val.string.len, _state->escontext))
 1448 tgl@sss.pgh.pa.us         388                 :UBC           0 :                 return JSON_SEM_ACTION_FAILED;
 4586 heikki.linnakangas@i      389                 :CBC       19984 :             v.val.string.val = token;
 4633 andrew@dunslane.net       390                 :          19984 :             break;
                                391                 :          20207 :         case JSON_TOKEN_NUMBER:
                                392                 :                : 
                                393                 :                :             /*
                                394                 :                :              * No need to check size of numeric values, because maximum
                                395                 :                :              * numeric size is well below the JsonbValue restriction
                                396                 :                :              */
 4589 bruce@momjian.us          397         [ -  + ]:          20207 :             Assert(token != NULL);
 4633 andrew@dunslane.net       398                 :          20207 :             v.type = jbvNumeric;
 1448 tgl@sss.pgh.pa.us         399         [ +  + ]:          20207 :             if (!DirectInputFunctionCallSafe(numeric_in, token,
                                400                 :                :                                              InvalidOid, -1,
                                401                 :          20207 :                                              _state->escontext,
                                402                 :                :                                              &numd))
                                403                 :              4 :                 return JSON_SEM_ACTION_FAILED;
 3132                           404                 :          20203 :             v.val.numeric = DatumGetNumeric(numd);
 4633 andrew@dunslane.net       405                 :          20203 :             break;
                                406                 :           2406 :         case JSON_TOKEN_TRUE:
                                407                 :           2406 :             v.type = jbvBool;
 4623 tgl@sss.pgh.pa.us         408                 :           2406 :             v.val.boolean = true;
 4633 andrew@dunslane.net       409                 :           2406 :             break;
                                410                 :           2456 :         case JSON_TOKEN_FALSE:
                                411                 :           2456 :             v.type = jbvBool;
 4623 tgl@sss.pgh.pa.us         412                 :           2456 :             v.val.boolean = false;
 4633 andrew@dunslane.net       413                 :           2456 :             break;
                                414                 :           1946 :         case JSON_TOKEN_NULL:
                                415                 :           1946 :             v.type = jbvNull;
                                416                 :           1946 :             break;
 4633 andrew@dunslane.net       417                 :UBC           0 :         default:
                                418                 :                :             /* should not be possible */
                                419         [ #  # ]:              0 :             elog(ERROR, "invalid json token type");
                                420                 :                :             break;
                                421                 :                :     }
                                422                 :                : 
 4633 andrew@dunslane.net       423         [ +  + ]:CBC       46995 :     if (_state->parseState == NULL)
                                424                 :                :     {
                                425                 :                :         /* single scalar */
                                426                 :                :         JsonbValue  va;
                                427                 :                : 
                                428                 :           4567 :         va.type = jbvArray;
 4623 tgl@sss.pgh.pa.us         429                 :           4567 :         va.val.array.rawScalar = true;
                                430                 :           4567 :         va.val.array.nElems = 1;
                                431                 :                : 
  356                           432                 :           4567 :         pushJsonbValue(_state, WJB_BEGIN_ARRAY, &va);
                                433                 :           4567 :         pushJsonbValue(_state, WJB_ELEM, &v);
                                434                 :           4567 :         pushJsonbValue(_state, WJB_END_ARRAY, NULL);
                                435                 :                :     }
                                436                 :                :     else
                                437                 :                :     {
 4633 andrew@dunslane.net       438                 :          42428 :         JsonbValue *o = &_state->parseState->contVal;
                                439                 :                : 
                                440      [ +  +  - ]:          42428 :         switch (o->type)
                                441                 :                :         {
                                442                 :          11682 :             case jbvArray:
  356 tgl@sss.pgh.pa.us         443                 :          11682 :                 pushJsonbValue(_state, WJB_ELEM, &v);
 4633 andrew@dunslane.net       444                 :          11682 :                 break;
                                445                 :          30746 :             case jbvObject:
  356 tgl@sss.pgh.pa.us         446                 :          30746 :                 pushJsonbValue(_state, WJB_VALUE, &v);
 4633 andrew@dunslane.net       447                 :          30746 :                 break;
 4633 andrew@dunslane.net       448                 :UBC           0 :             default:
                                449         [ #  # ]:              0 :                 elog(ERROR, "unexpected parent of nested structure");
                                450                 :                :         }
                                451                 :                :     }
                                452                 :                : 
 1448 tgl@sss.pgh.pa.us         453                 :CBC       46995 :     return JSON_SUCCESS;
                                454                 :                : }
                                455                 :                : 
                                456                 :                : /*
                                457                 :                :  * JsonbToCString
                                458                 :                :  *     Converts jsonb value to a C-string.
                                459                 :                :  *
                                460                 :                :  * If 'out' argument is non-null, the resulting C-string is stored inside the
                                461                 :                :  * StringBuffer.  The resulting string is always returned.
                                462                 :                :  *
                                463                 :                :  * A typical case for passing the StringInfo in rather than NULL is where the
                                464                 :                :  * caller wants access to the len attribute without having to call strlen, e.g.
                                465                 :                :  * if they are converting it to a text* object.
                                466                 :                :  */
                                467                 :                : char *
 4588 heikki.linnakangas@i      468                 :          15830 : JsonbToCString(StringInfo out, JsonbContainer *in, int estimated_len)
                                469                 :                : {
 4218 andrew@dunslane.net       470                 :          15830 :     return JsonbToCStringWorker(out, in, estimated_len, false);
                                471                 :                : }
                                472                 :                : 
                                473                 :                : /*
                                474                 :                :  * same thing but with indentation turned on
                                475                 :                :  */
                                476                 :                : char *
                                477                 :             63 : JsonbToCStringIndent(StringInfo out, JsonbContainer *in, int estimated_len)
                                478                 :                : {
                                479                 :             63 :     return JsonbToCStringWorker(out, in, estimated_len, true);
                                480                 :                : }
                                481                 :                : 
                                482                 :                : /*
                                483                 :                :  * common worker for above two functions
                                484                 :                :  */
                                485                 :                : static char *
                                486                 :          15893 : JsonbToCStringWorker(StringInfo out, JsonbContainer *in, int estimated_len, bool indent)
                                487                 :                : {
 4633                           488                 :          15893 :     bool        first = true;
                                489                 :                :     JsonbIterator *it;
                                490                 :                :     JsonbValue  v;
 4066 noah@leadboat.com         491                 :          15893 :     JsonbIteratorToken type = WJB_DONE;
 4633 andrew@dunslane.net       492                 :          15893 :     int         level = 0;
                                493                 :          15893 :     bool        redo_switch = false;
                                494                 :                : 
                                495                 :                :     /* If we are indenting, don't add a space after a comma */
 4218                           496         [ +  + ]:          15893 :     int         ispaces = indent ? 1 : 2;
                                497                 :                : 
                                498                 :                :     /*
                                499                 :                :      * Don't indent the very first item. This gets set to the indent flag at
                                500                 :                :      * the bottom of the loop.
                                501                 :                :      */
 4207 bruce@momjian.us          502                 :          15893 :     bool        use_indent = false;
                                503                 :          15893 :     bool        raw_scalar = false;
                                504                 :          15893 :     bool        last_was_key = false;
                                505                 :                : 
 4633 andrew@dunslane.net       506         [ +  + ]:          15893 :     if (out == NULL)
                                507                 :          15741 :         out = makeStringInfo();
                                508                 :                : 
                                509         [ +  - ]:          15893 :     enlargeStringInfo(out, (estimated_len >= 0) ? estimated_len : 64);
                                510                 :                : 
                                511                 :          15893 :     it = JsonbIteratorInit(in);
                                512                 :                : 
                                513   [ +  +  +  + ]:         179467 :     while (redo_switch ||
                                514                 :          89176 :            ((type = JsonbIteratorNext(&it, &v, false)) != WJB_DONE))
                                515                 :                :     {
                                516                 :          74398 :         redo_switch = false;
                                517   [ +  +  +  +  :          74398 :         switch (type)
                                           +  +  - ]
                                518                 :                :         {
                                519                 :          10003 :             case WJB_BEGIN_ARRAY:
                                520         [ +  + ]:          10003 :                 if (!first)
 4218                           521                 :             93 :                     appendBinaryStringInfo(out, ", ", ispaces);
                                522                 :                : 
 4623 tgl@sss.pgh.pa.us         523         [ +  + ]:          10003 :                 if (!v.val.array.rawScalar)
                                524                 :                :                 {
 4218 andrew@dunslane.net       525   [ +  +  +  + ]:           2531 :                     add_indent(out, use_indent && !last_was_key, level);
                                526         [ -  + ]:           2531 :                     appendStringInfoCharMacro(out, '[');
                                527                 :                :                 }
                                528                 :                :                 else
                                529                 :           7472 :                     raw_scalar = true;
                                530                 :                : 
                                531                 :          10003 :                 first = true;
 4633                           532                 :          10003 :                 level++;
                                533                 :          10003 :                 break;
                                534                 :           8049 :             case WJB_BEGIN_OBJECT:
                                535         [ +  + ]:           8049 :                 if (!first)
 4218                           536                 :            262 :                     appendBinaryStringInfo(out, ", ", ispaces);
                                537                 :                : 
                                538   [ +  +  +  + ]:           8049 :                 add_indent(out, use_indent && !last_was_key, level);
 4633                           539         [ -  + ]:           8049 :                 appendStringInfoCharMacro(out, '{');
                                540                 :                : 
 4218                           541                 :           8049 :                 first = true;
 4633                           542                 :           8049 :                 level++;
                                543                 :           8049 :                 break;
                                544                 :          26499 :             case WJB_KEY:
                                545         [ +  + ]:          26499 :                 if (!first)
 4218                           546                 :          19189 :                     appendBinaryStringInfo(out, ", ", ispaces);
 4633                           547                 :          26499 :                 first = true;
                                548                 :                : 
 4218                           549                 :          26499 :                 add_indent(out, use_indent, level);
                                550                 :                : 
                                551                 :                :                 /* json rules guarantee this is a string */
 4633                           552                 :          26499 :                 jsonb_put_escaped_value(out, &v);
                                553                 :          26499 :                 appendBinaryStringInfo(out, ": ", 2);
                                554                 :                : 
                                555                 :          26499 :                 type = JsonbIteratorNext(&it, &v, false);
                                556         [ +  + ]:          26499 :                 if (type == WJB_VALUE)
                                557                 :                :                 {
                                558                 :          25384 :                     first = false;
                                559                 :          25384 :                     jsonb_put_escaped_value(out, &v);
                                560                 :                :                 }
                                561                 :                :                 else
                                562                 :                :                 {
                                563   [ +  +  -  + ]:           1115 :                     Assert(type == WJB_BEGIN_OBJECT || type == WJB_BEGIN_ARRAY);
                                564                 :                : 
                                565                 :                :                     /*
                                566                 :                :                      * We need to rerun the current switch() since we need to
                                567                 :                :                      * output the object which we just got from the iterator
                                568                 :                :                      * before calling the iterator again.
                                569                 :                :                      */
                                570                 :           1115 :                     redo_switch = true;
                                571                 :                :                 }
                                572                 :          26499 :                 break;
                                573                 :          11795 :             case WJB_ELEM:
                                574         [ +  + ]:          11795 :                 if (!first)
 4218                           575                 :           2634 :                     appendBinaryStringInfo(out, ", ", ispaces);
                                576                 :          11795 :                 first = false;
                                577                 :                : 
 4207 bruce@momjian.us          578         [ +  + ]:          11795 :                 if (!raw_scalar)
 4218 andrew@dunslane.net       579                 :           4323 :                     add_indent(out, use_indent, level);
 4633                           580                 :          11795 :                 jsonb_put_escaped_value(out, &v);
                                581                 :          11795 :                 break;
                                582                 :          10003 :             case WJB_END_ARRAY:
                                583                 :          10003 :                 level--;
 4207 bruce@momjian.us          584         [ +  + ]:          10003 :                 if (!raw_scalar)
                                585                 :                :                 {
 4218 andrew@dunslane.net       586                 :           2531 :                     add_indent(out, use_indent, level);
                                587         [ -  + ]:           2531 :                     appendStringInfoCharMacro(out, ']');
                                588                 :                :                 }
 4633                           589                 :          10003 :                 first = false;
                                590                 :          10003 :                 break;
                                591                 :           8049 :             case WJB_END_OBJECT:
                                592                 :           8049 :                 level--;
 4218                           593                 :           8049 :                 add_indent(out, use_indent, level);
 4633                           594         [ -  + ]:           8049 :                 appendStringInfoCharMacro(out, '}');
                                595                 :           8049 :                 first = false;
                                596                 :           8049 :                 break;
 4633 andrew@dunslane.net       597                 :UBC           0 :             default:
 4292 alvherre@alvh.no-ip.      598         [ #  # ]:              0 :                 elog(ERROR, "unknown jsonb iterator token type");
                                599                 :                :         }
 4218 andrew@dunslane.net       600                 :CBC       74398 :         use_indent = indent;
                                601                 :          74398 :         last_was_key = redo_switch;
                                602                 :                :     }
                                603                 :                : 
 4633                           604         [ -  + ]:          15893 :     Assert(level == 0);
                                605                 :                : 
                                606                 :          15893 :     return out->data;
                                607                 :                : }
                                608                 :                : 
                                609                 :                : static void
 4218                           610                 :          51982 : add_indent(StringInfo out, bool indent, int level)
                                611                 :                : {
                                612         [ +  + ]:          51982 :     if (indent)
                                613                 :                :     {
                                614         [ -  + ]:           1444 :         appendStringInfoCharMacro(out, '\n');
 1408 drowley@postgresql.o      615                 :           1444 :         appendStringInfoSpaces(out, level * 4);
                                616                 :                :     }
 4218 andrew@dunslane.net       617                 :          51982 : }
                                618                 :                : 
                                619                 :                : 
                                620                 :                : /*
                                621                 :                :  * Turn a Datum into jsonb, adding it to the result JsonbInState.
                                622                 :                :  *
                                623                 :                :  * tcategory and outfuncoid are from a previous call to json_categorize_type,
                                624                 :                :  * except that if is_null is true then they can be invalid.
                                625                 :                :  *
                                626                 :                :  * If key_scalar is true, the value is stored as a key, so insist
                                627                 :                :  * it's of an acceptable type, and force it to be a jbvString.
                                628                 :                :  *
                                629                 :                :  * Note: currently, we assume that result->escontext is NULL and errors
                                630                 :                :  * will be thrown.
                                631                 :                :  */
                                632                 :                : static void
 1226 amitlan@postgresql.o      633                 :           5780 : datum_to_jsonb_internal(Datum val, bool is_null, JsonbInState *result,
                                634                 :                :                         JsonTypeCategory tcategory, Oid outfuncoid,
                                635                 :                :                         bool key_scalar)
                                636                 :                : {
                                637                 :                :     char       *outputstr;
                                638                 :                :     Numeric     numeric_val;
                                639                 :                :     bool        numeric_to_string;
                                640                 :                :     JsonbValue  jb;
 4369 andrew@dunslane.net       641                 :           5780 :     bool        scalar_jsonb = false;
                                642                 :                :     AclResult   aclresult;
                                643                 :                : 
 4072 noah@leadboat.com         644                 :           5780 :     check_stack_depth();
                                645                 :                : 
                                646                 :                :     /* Convert val to a JsonbValue in jb (in most cases) */
 4369 andrew@dunslane.net       647         [ +  + ]:           5780 :     if (is_null)
                                648                 :                :     {
 4145                           649         [ -  + ]:            574 :         Assert(!key_scalar);
 4369                           650                 :            574 :         jb.type = jbvNull;
                                651                 :                :     }
                                652   [ +  +  +  + ]:           5206 :     else if (key_scalar &&
 1227 amitlan@postgresql.o      653         [ +  + ]:           2155 :              (tcategory == JSONTYPE_ARRAY ||
                                654         [ +  + ]:           2151 :               tcategory == JSONTYPE_COMPOSITE ||
                                655         [ +  - ]:           2147 :               tcategory == JSONTYPE_JSON ||
                                656         [ +  + ]:           2147 :               tcategory == JSONTYPE_JSONB ||
                                657                 :                :               tcategory == JSONTYPE_CAST))
                                658                 :                :     {
 4369 andrew@dunslane.net       659         [ +  - ]:             20 :         ereport(ERROR,
                                660                 :                :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                                661                 :                :                  errmsg("key value must be scalar, not array, composite, or json")));
                                662                 :                :     }
                                663                 :                :     else
                                664                 :                :     {
                                665   [ +  +  +  +  :           5186 :         switch (tcategory)
                                     +  +  +  +  +  
                                              +  + ]
                                666                 :                :         {
 1227 amitlan@postgresql.o      667                 :            200 :             case JSONTYPE_ARRAY:
 4369 andrew@dunslane.net       668                 :            200 :                 array_to_jsonb_internal(val, result);
                                669                 :            200 :                 break;
 1227 amitlan@postgresql.o      670                 :            132 :             case JSONTYPE_COMPOSITE:
 4369 andrew@dunslane.net       671                 :            132 :                 composite_to_jsonb(val, result);
                                672                 :            132 :                 break;
 1227 amitlan@postgresql.o      673                 :             48 :             case JSONTYPE_BOOL:
 4369 andrew@dunslane.net       674         [ -  + ]:             48 :                 if (key_scalar)
                                675                 :                :                 {
 4369 andrew@dunslane.net       676         [ #  # ]:UBC           0 :                     outputstr = DatumGetBool(val) ? "true" : "false";
                                677                 :              0 :                     jb.type = jbvString;
                                678                 :              0 :                     jb.val.string.len = strlen(outputstr);
                                679                 :              0 :                     jb.val.string.val = outputstr;
                                680                 :                :                 }
                                681                 :                :                 else
                                682                 :                :                 {
 4369 andrew@dunslane.net       683                 :CBC          48 :                     jb.type = jbvBool;
                                684                 :             48 :                     jb.val.boolean = DatumGetBool(val);
                                685                 :                :                 }
                                686                 :             48 :                 break;
 1227 amitlan@postgresql.o      687                 :           2670 :             case JSONTYPE_NUMERIC:
 4369 andrew@dunslane.net       688         [ +  + ]:           2670 :                 if (key_scalar)
                                689                 :                :                 {
                                690                 :                :                     /* always stringify keys */
  356 tgl@sss.pgh.pa.us         691                 :           1069 :                     numeric_to_string = true;
                                692                 :           1069 :                     numeric_val = NULL; /* pacify stupider compilers */
                                693                 :                :                 }
                                694                 :                :                 else
                                695                 :                :                 {
                                696                 :                :                     Datum       numd;
                                697                 :                : 
                                698   [ +  -  +  +  :           1601 :                     switch (outfuncoid)
                                                 - ]
                                699                 :                :                     {
                                700                 :              8 :                         case F_NUMERIC_OUT:
                                701                 :              8 :                             numeric_val = DatumGetNumeric(val);
                                702                 :              8 :                             break;
  356 tgl@sss.pgh.pa.us         703                 :UBC           0 :                         case F_INT2OUT:
                                704                 :              0 :                             numeric_val = int64_to_numeric(DatumGetInt16(val));
                                705                 :              0 :                             break;
  356 tgl@sss.pgh.pa.us         706                 :CBC        1557 :                         case F_INT4OUT:
                                707                 :           1557 :                             numeric_val = int64_to_numeric(DatumGetInt32(val));
                                708                 :           1557 :                             break;
                                709                 :             36 :                         case F_INT8OUT:
                                710                 :             36 :                             numeric_val = int64_to_numeric(DatumGetInt64(val));
                                711                 :             36 :                             break;
                                712                 :                : #ifdef NOT_USED
                                713                 :                : 
                                714                 :                :                             /*
                                715                 :                :                              * Ideally we'd short-circuit these two cases
                                716                 :                :                              * using float[48]_numeric.  However, those
                                717                 :                :                              * functions are currently slower than the generic
                                718                 :                :                              * coerce-via-I/O approach.  And they may round
                                719                 :                :                              * off differently.  Until/unless that gets fixed,
                                720                 :                :                              * continue to use coerce-via-I/O for floats.
                                721                 :                :                              */
                                722                 :                :                         case F_FLOAT4OUT:
                                723                 :                :                             numd = DirectFunctionCall1(float4_numeric, val);
                                724                 :                :                             numeric_val = DatumGetNumeric(numd);
                                725                 :                :                             break;
                                726                 :                :                         case F_FLOAT8OUT:
                                727                 :                :                             numd = DirectFunctionCall1(float8_numeric, val);
                                728                 :                :                             numeric_val = DatumGetNumeric(numd);
                                729                 :                :                             break;
                                730                 :                : #endif
  356 tgl@sss.pgh.pa.us         731                 :UBC           0 :                         default:
                                732                 :              0 :                             outputstr = OidOutputFunctionCall(outfuncoid, val);
                                733                 :              0 :                             numd = DirectFunctionCall3(numeric_in,
                                734                 :                :                                                        CStringGetDatum(outputstr),
                                735                 :                :                                                        ObjectIdGetDatum(InvalidOid),
                                736                 :                :                                                        Int32GetDatum(-1));
                                737                 :              0 :                             numeric_val = DatumGetNumeric(numd);
                                738                 :              0 :                             break;
                                739                 :                :                     }
                                740                 :                :                     /* Must convert to string if it's Inf or NaN */
  356 tgl@sss.pgh.pa.us         741   [ +  -  -  + ]:CBC        3202 :                     numeric_to_string = (numeric_is_inf(numeric_val) ||
                                742                 :           1601 :                                          numeric_is_nan(numeric_val));
                                743                 :                :                 }
                                744         [ +  + ]:           2670 :                 if (numeric_to_string)
                                745                 :                :                 {
                                746                 :           1069 :                     outputstr = OidOutputFunctionCall(outfuncoid, val);
 4369 andrew@dunslane.net       747                 :           1069 :                     jb.type = jbvString;
                                748                 :           1069 :                     jb.val.string.len = strlen(outputstr);
                                749                 :           1069 :                     jb.val.string.val = outputstr;
                                750                 :                :                 }
                                751                 :                :                 else
                                752                 :                :                 {
  356 tgl@sss.pgh.pa.us         753                 :           1601 :                     jb.type = jbvNumeric;
                                754                 :           1601 :                     jb.val.numeric = numeric_val;
                                755                 :                :                 }
 4369 andrew@dunslane.net       756                 :           2670 :                 break;
 1227 amitlan@postgresql.o      757                 :             12 :             case JSONTYPE_DATE:
 3238 andrew@dunslane.net       758                 :             12 :                 jb.type = jbvString;
 2621 akorotkov@postgresql      759                 :             12 :                 jb.val.string.val = JsonEncodeDateTime(NULL, val,
                                760                 :                :                                                        DATEOID, NULL);
 3238 andrew@dunslane.net       761                 :             12 :                 jb.val.string.len = strlen(jb.val.string.val);
 4207 bruce@momjian.us          762                 :             12 :                 break;
 1227 amitlan@postgresql.o      763                 :             12 :             case JSONTYPE_TIMESTAMP:
 3238 andrew@dunslane.net       764                 :             12 :                 jb.type = jbvString;
 2621 akorotkov@postgresql      765                 :             12 :                 jb.val.string.val = JsonEncodeDateTime(NULL, val,
                                766                 :                :                                                        TIMESTAMPOID, NULL);
 3238 andrew@dunslane.net       767                 :             12 :                 jb.val.string.len = strlen(jb.val.string.val);
 4369                           768                 :             12 :                 break;
 1227 amitlan@postgresql.o      769                 :             16 :             case JSONTYPE_TIMESTAMPTZ:
 3238 andrew@dunslane.net       770                 :             16 :                 jb.type = jbvString;
 2621 akorotkov@postgresql      771                 :             16 :                 jb.val.string.val = JsonEncodeDateTime(NULL, val,
                                772                 :                :                                                        TIMESTAMPTZOID, NULL);
 3238 andrew@dunslane.net       773                 :             16 :                 jb.val.string.len = strlen(jb.val.string.val);
 4369                           774                 :             16 :                 break;
 1227 amitlan@postgresql.o      775                 :              4 :             case JSONTYPE_CAST:
                                776                 :                :                 /* cast to JSON, and then process as JSON */
   19 nathan@postgresql.or      777                 :              4 :                 aclresult = object_aclcheck(ProcedureRelationId, outfuncoid,
                                778                 :                :                                             GetUserId(), ACL_EXECUTE);
                                779         [ +  - ]:              4 :                 if (aclresult != ACLCHECK_OK)
                                780                 :              4 :                     aclcheck_error(aclresult, OBJECT_FUNCTION,
                                781                 :              4 :                                    get_func_name(outfuncoid));
   19 nathan@postgresql.or      782         [ #  # ]:UBC           0 :                 InvokeFunctionExecuteHook(outfuncoid);
  356 tgl@sss.pgh.pa.us         783                 :              0 :                 val = OidFunctionCall1(outfuncoid, val);
                                784                 :                :                 pg_fallthrough;
 1227 amitlan@postgresql.o      785                 :CBC          24 :             case JSONTYPE_JSON:
                                786                 :                :                 {
                                787                 :                :                     /* parse the json right into the existing result object */
                                788                 :                :                     JsonLexContext lex;
                                789                 :                :                     JsonSemAction sem;
 3548 noah@leadboat.com         790                 :             24 :                     text       *json = DatumGetTextPP(val);
                                791                 :                : 
 1150 alvherre@alvh.no-ip.      792                 :             24 :                     makeJsonLexContext(&lex, json, true);
                                793                 :                : 
 4369 andrew@dunslane.net       794                 :             24 :                     memset(&sem, 0, sizeof(sem));
                                795                 :                : 
  730 peter@eisentraut.org      796                 :             24 :                     sem.semstate = result;
                                797                 :                : 
 4369 andrew@dunslane.net       798                 :             24 :                     sem.object_start = jsonb_in_object_start;
                                799                 :             24 :                     sem.array_start = jsonb_in_array_start;
                                800                 :             24 :                     sem.object_end = jsonb_in_object_end;
                                801                 :             24 :                     sem.array_end = jsonb_in_array_end;
                                802                 :             24 :                     sem.scalar = jsonb_in_scalar;
                                803                 :             24 :                     sem.object_field_start = jsonb_in_object_field_start;
                                804                 :                : 
 1150 alvherre@alvh.no-ip.      805                 :             24 :                     pg_parse_json_or_ereport(&lex, &sem);
                                806                 :             24 :                     freeJsonLexContext(&lex);
                                807                 :                :                 }
 4369 andrew@dunslane.net       808                 :             24 :                 break;
 1227 amitlan@postgresql.o      809                 :            298 :             case JSONTYPE_JSONB:
                                810                 :                :                 {
 3358 tgl@sss.pgh.pa.us         811                 :            298 :                     Jsonb      *jsonb = DatumGetJsonbP(val);
                                812                 :                :                     JsonbIterator *it;
                                813                 :                : 
 4369 andrew@dunslane.net       814                 :            298 :                     it = JsonbIteratorInit(&jsonb->root);
                                815                 :                : 
                                816         [ +  + ]:            298 :                     if (JB_ROOT_IS_SCALAR(jsonb))
                                817                 :                :                     {
                                818                 :            144 :                         (void) JsonbIteratorNext(&it, &jb, true);
                                819         [ -  + ]:            144 :                         Assert(jb.type == jbvArray);
                                820                 :            144 :                         (void) JsonbIteratorNext(&it, &jb, true);
                                821                 :            144 :                         scalar_jsonb = true;
                                822                 :                :                     }
                                823                 :                :                     else
                                824                 :                :                     {
                                825                 :                :                         JsonbIteratorToken type;
                                826                 :                : 
                                827                 :           5918 :                         while ((type = JsonbIteratorNext(&it, &jb, false))
                                828         [ +  + ]:           5918 :                                != WJB_DONE)
                                829                 :                :                         {
                                830   [ +  +  +  +  :           5764 :                             if (type == WJB_END_ARRAY || type == WJB_END_OBJECT ||
                                              +  + ]
                                831         [ +  + ]:           4782 :                                 type == WJB_BEGIN_ARRAY || type == WJB_BEGIN_OBJECT)
  356 tgl@sss.pgh.pa.us         832                 :           1340 :                                 pushJsonbValue(result, type, NULL);
                                833                 :                :                             else
                                834                 :           4424 :                                 pushJsonbValue(result, type, &jb);
                                835                 :                :                         }
                                836                 :                :                     }
                                837                 :                :                 }
 4369 andrew@dunslane.net       838                 :            298 :                 break;
                                839                 :           1770 :             default:
                                840                 :                :                 /* special-case text types to save useless palloc/memcpy ops */
  356 tgl@sss.pgh.pa.us         841   [ +  +  +  - ]:           1770 :                 if (outfuncoid == F_TEXTOUT ||
                                842         [ +  + ]:             92 :                     outfuncoid == F_VARCHAROUT ||
                                843                 :                :                     outfuncoid == F_BPCHAROUT)
                                844                 :           1682 :                 {
                                845                 :           1682 :                     text       *txt = DatumGetTextPP(val);
                                846                 :                : 
                                847                 :           1682 :                     jb.val.string.len = VARSIZE_ANY_EXHDR(txt);
                                848                 :           1682 :                     jb.val.string.val = VARDATA_ANY(txt);
                                849                 :                :                 }
                                850                 :                :                 else
                                851                 :                :                 {
                                852                 :             88 :                     outputstr = OidOutputFunctionCall(outfuncoid, val);
                                853                 :             88 :                     jb.val.string.len = strlen(outputstr);
                                854                 :             88 :                     jb.val.string.val = outputstr;
                                855                 :                :                 }
 4369 andrew@dunslane.net       856                 :           1770 :                 jb.type = jbvString;
 1448 tgl@sss.pgh.pa.us         857                 :           1770 :                 (void) checkStringLen(jb.val.string.len, NULL);
 4369 andrew@dunslane.net       858                 :           1770 :                 break;
                                859                 :                :         }
                                860                 :                :     }
                                861                 :                : 
                                862                 :                :     /* Now insert jb into result, unless we did it recursively */
 4062 tgl@sss.pgh.pa.us         863   [ +  +  +  +  :           5756 :     if (!is_null && !scalar_jsonb &&
                                              +  + ]
 1227 amitlan@postgresql.o      864         [ +  + ]:           2280 :         tcategory >= JSONTYPE_JSON && tcategory <= JSONTYPE_CAST)
                                865                 :                :     {
                                866                 :                :         /* work has been done recursively */
 4369 andrew@dunslane.net       867                 :            510 :         return;
                                868                 :                :     }
                                869         [ +  + ]:           5246 :     else if (result->parseState == NULL)
                                870                 :                :     {
                                871                 :                :         /* single root scalar */
                                872                 :                :         JsonbValue  va;
                                873                 :                : 
                                874                 :            136 :         va.type = jbvArray;
                                875                 :            136 :         va.val.array.rawScalar = true;
                                876                 :            136 :         va.val.array.nElems = 1;
                                877                 :                : 
  356 tgl@sss.pgh.pa.us         878                 :            136 :         pushJsonbValue(result, WJB_BEGIN_ARRAY, &va);
                                879                 :            136 :         pushJsonbValue(result, WJB_ELEM, &jb);
                                880                 :            136 :         pushJsonbValue(result, WJB_END_ARRAY, NULL);
                                881                 :                :     }
                                882                 :                :     else
                                883                 :                :     {
 4369 andrew@dunslane.net       884                 :           5110 :         JsonbValue *o = &result->parseState->contVal;
                                885                 :                : 
                                886      [ +  +  - ]:           5110 :         switch (o->type)
                                887                 :                :         {
                                888                 :            624 :             case jbvArray:
  356 tgl@sss.pgh.pa.us         889                 :            624 :                 pushJsonbValue(result, WJB_ELEM, &jb);
 4369 andrew@dunslane.net       890                 :            624 :                 break;
                                891                 :           4486 :             case jbvObject:
  356 tgl@sss.pgh.pa.us         892         [ +  + ]:           4486 :                 pushJsonbValue(result,
                                893                 :                :                                key_scalar ? WJB_KEY : WJB_VALUE,
                                894                 :                :                                &jb);
 4369 andrew@dunslane.net       895                 :           4486 :                 break;
 4369 andrew@dunslane.net       896                 :UBC           0 :             default:
                                897         [ #  # ]:              0 :                 elog(ERROR, "unexpected parent of nested structure");
                                898                 :                :         }
                                899                 :                :     }
                                900                 :                : }
                                901                 :                : 
                                902                 :                : /*
                                903                 :                :  * Process a single dimension of an array.
                                904                 :                :  * If it's the innermost dimension, output the values, otherwise call
                                905                 :                :  * ourselves recursively to process the next dimension.
                                906                 :                :  */
                                907                 :                : static void
 1145 peter@eisentraut.org      908                 :CBC         200 : array_dim_to_jsonb(JsonbInState *result, int dim, int ndims, int *dims, const Datum *vals,
                                909                 :                :                    const bool *nulls, int *valcount, JsonTypeCategory tcategory,
                                910                 :                :                    Oid outfuncoid)
                                911                 :                : {
                                912                 :                :     int         i;
                                913                 :                : 
 4369 andrew@dunslane.net       914         [ -  + ]:            200 :     Assert(dim < ndims);
                                915                 :                : 
  356 tgl@sss.pgh.pa.us         916                 :            200 :     pushJsonbValue(result, WJB_BEGIN_ARRAY, NULL);
                                917                 :                : 
 4369 andrew@dunslane.net       918         [ +  + ]:            560 :     for (i = 1; i <= dims[dim]; i++)
                                919                 :                :     {
                                920         [ +  - ]:            360 :         if (dim + 1 == ndims)
                                921                 :                :         {
 1226 amitlan@postgresql.o      922                 :            360 :             datum_to_jsonb_internal(vals[*valcount], nulls[*valcount], result, tcategory,
                                923                 :                :                                     outfuncoid, false);
 4369 andrew@dunslane.net       924                 :            360 :             (*valcount)++;
                                925                 :                :         }
                                926                 :                :         else
                                927                 :                :         {
 4369 andrew@dunslane.net       928                 :UBC           0 :             array_dim_to_jsonb(result, dim + 1, ndims, dims, vals, nulls,
                                929                 :                :                                valcount, tcategory, outfuncoid);
                                930                 :                :         }
                                931                 :                :     }
                                932                 :                : 
  356 tgl@sss.pgh.pa.us         933                 :CBC         200 :     pushJsonbValue(result, WJB_END_ARRAY, NULL);
 4369 andrew@dunslane.net       934                 :            200 : }
                                935                 :                : 
                                936                 :                : /*
                                937                 :                :  * Turn an array into JSON.
                                938                 :                :  */
                                939                 :                : static void
                                940                 :            200 : array_to_jsonb_internal(Datum array, JsonbInState *result)
                                941                 :                : {
                                942                 :            200 :     ArrayType  *v = DatumGetArrayTypeP(array);
                                943                 :            200 :     Oid         element_type = ARR_ELEMTYPE(v);
                                944                 :                :     int        *dim;
                                945                 :                :     int         ndim;
                                946                 :                :     int         nitems;
                                947                 :            200 :     int         count = 0;
                                948                 :                :     Datum      *elements;
                                949                 :                :     bool       *nulls;
                                950                 :                :     int16       typlen;
                                951                 :                :     bool        typbyval;
                                952                 :                :     char        typalign;
                                953                 :                :     JsonTypeCategory tcategory;
                                954                 :                :     Oid         outfuncoid;
                                955                 :                : 
                                956                 :            200 :     ndim = ARR_NDIM(v);
                                957                 :            200 :     dim = ARR_DIMS(v);
                                958                 :            200 :     nitems = ArrayGetNItems(ndim, dim);
                                959                 :                : 
                                960         [ -  + ]:            200 :     if (nitems <= 0)
                                961                 :                :     {
  356 tgl@sss.pgh.pa.us         962                 :UBC           0 :         pushJsonbValue(result, WJB_BEGIN_ARRAY, NULL);
                                963                 :              0 :         pushJsonbValue(result, WJB_END_ARRAY, NULL);
 4369 andrew@dunslane.net       964                 :              0 :         return;
                                965                 :                :     }
                                966                 :                : 
 4369 andrew@dunslane.net       967                 :CBC         200 :     get_typlenbyvalalign(element_type,
                                968                 :                :                          &typlen, &typbyval, &typalign);
                                969                 :                : 
 1227 amitlan@postgresql.o      970                 :            200 :     json_categorize_type(element_type, true,
                                971                 :                :                          &tcategory, &outfuncoid);
                                972                 :                : 
 4369 andrew@dunslane.net       973                 :            200 :     deconstruct_array(v, element_type, typlen, typbyval,
                                974                 :                :                       typalign, &elements, &nulls,
                                975                 :                :                       &nitems);
                                976                 :                : 
                                977                 :            200 :     array_dim_to_jsonb(result, 0, ndim, dim, elements, nulls, &count, tcategory,
                                978                 :                :                        outfuncoid);
                                979                 :                : 
                                980                 :            200 :     pfree(elements);
                                981                 :            200 :     pfree(nulls);
                                982                 :                : }
                                983                 :                : 
                                984                 :                : /*
                                985                 :                :  * Turn a composite / record into JSON.
                                986                 :                :  */
                                987                 :                : static void
                                988                 :            132 : composite_to_jsonb(Datum composite, JsonbInState *result)
                                989                 :                : {
                                990                 :                :     HeapTupleHeader td;
                                991                 :                :     Oid         tupType;
                                992                 :                :     int32       tupTypmod;
                                993                 :                :     TupleDesc   tupdesc;
                                994                 :                :     HeapTupleData tmptup,
                                995                 :                :                *tuple;
                                996                 :                :     int         i;
                                997                 :                : 
                                998                 :            132 :     td = DatumGetHeapTupleHeader(composite);
                                999                 :                : 
                               1000                 :                :     /* Extract rowtype info and find a tupdesc */
                               1001                 :            132 :     tupType = HeapTupleHeaderGetTypeId(td);
                               1002                 :            132 :     tupTypmod = HeapTupleHeaderGetTypMod(td);
                               1003                 :            132 :     tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
                               1004                 :                : 
                               1005                 :                :     /* Build a temporary HeapTuple control structure */
                               1006                 :            132 :     tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
                               1007                 :            132 :     tmptup.t_data = td;
                               1008                 :            132 :     tuple = &tmptup;
                               1009                 :                : 
  356 tgl@sss.pgh.pa.us        1010                 :            132 :     pushJsonbValue(result, WJB_BEGIN_OBJECT, NULL);
                               1011                 :                : 
 4369 andrew@dunslane.net      1012         [ +  + ]:            436 :     for (i = 0; i < tupdesc->natts; i++)
                               1013                 :                :     {
                               1014                 :                :         Datum       val;
                               1015                 :                :         bool        isnull;
                               1016                 :                :         char       *attname;
                               1017                 :                :         JsonTypeCategory tcategory;
                               1018                 :                :         Oid         outfuncoid;
                               1019                 :                :         JsonbValue  v;
 3387 andres@anarazel.de       1020                 :            304 :         Form_pg_attribute att = TupleDescAttr(tupdesc, i);
                               1021                 :                : 
                               1022         [ -  + ]:            304 :         if (att->attisdropped)
 4369 andrew@dunslane.net      1023                 :UBC           0 :             continue;
                               1024                 :                : 
 3387 andres@anarazel.de       1025                 :CBC         304 :         attname = NameStr(att->attname);
                               1026                 :                : 
 4369 andrew@dunslane.net      1027                 :            304 :         v.type = jbvString;
                               1028                 :                :         /* don't need checkStringLen here - can't exceed maximum name length */
                               1029                 :            304 :         v.val.string.len = strlen(attname);
                               1030                 :            304 :         v.val.string.val = attname;
                               1031                 :                : 
  356 tgl@sss.pgh.pa.us        1032                 :            304 :         pushJsonbValue(result, WJB_KEY, &v);
                               1033                 :                : 
 4369 andrew@dunslane.net      1034                 :            304 :         val = heap_getattr(tuple, i + 1, tupdesc, &isnull);
                               1035                 :                : 
                               1036         [ +  + ]:            304 :         if (isnull)
                               1037                 :                :         {
 1227 amitlan@postgresql.o     1038                 :             20 :             tcategory = JSONTYPE_NULL;
 4369 andrew@dunslane.net      1039                 :             20 :             outfuncoid = InvalidOid;
                               1040                 :                :         }
                               1041                 :                :         else
 1227 amitlan@postgresql.o     1042                 :            284 :             json_categorize_type(att->atttypid, true, &tcategory,
                               1043                 :                :                                  &outfuncoid);
                               1044                 :                : 
 1226                          1045                 :            304 :         datum_to_jsonb_internal(val, isnull, result, tcategory, outfuncoid,
                               1046                 :                :                                 false);
                               1047                 :                :     }
                               1048                 :                : 
  356 tgl@sss.pgh.pa.us        1049                 :            132 :     pushJsonbValue(result, WJB_END_OBJECT, NULL);
 4369 andrew@dunslane.net      1050         [ +  - ]:            132 :     ReleaseTupleDesc(tupdesc);
                               1051                 :            132 : }
                               1052                 :                : 
                               1053                 :                : /*
                               1054                 :                :  * Append JSON text for "val" to "result".
                               1055                 :                :  *
                               1056                 :                :  * This is just a thin wrapper around datum_to_jsonb.  If the same type will be
                               1057                 :                :  * printed many times, avoid using this; better to do the json_categorize_type
                               1058                 :                :  * lookups only once.
                               1059                 :                :  */
                               1060                 :                : 
                               1061                 :                : static void
                               1062                 :           2398 : add_jsonb(Datum val, bool is_null, JsonbInState *result,
                               1063                 :                :           Oid val_type, bool key_scalar)
                               1064                 :                : {
                               1065                 :                :     JsonTypeCategory tcategory;
                               1066                 :                :     Oid         outfuncoid;
                               1067                 :                : 
                               1068         [ -  + ]:           2398 :     if (val_type == InvalidOid)
 4369 andrew@dunslane.net      1069         [ #  # ]:UBC           0 :         ereport(ERROR,
                               1070                 :                :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                               1071                 :                :                  errmsg("could not determine input data type")));
                               1072                 :                : 
 4369 andrew@dunslane.net      1073         [ +  + ]:CBC        2398 :     if (is_null)
                               1074                 :                :     {
 1227 amitlan@postgresql.o     1075                 :            398 :         tcategory = JSONTYPE_NULL;
 4369 andrew@dunslane.net      1076                 :            398 :         outfuncoid = InvalidOid;
                               1077                 :                :     }
                               1078                 :                :     else
 1227 amitlan@postgresql.o     1079                 :           2000 :         json_categorize_type(val_type, true,
                               1080                 :                :                              &tcategory, &outfuncoid);
                               1081                 :                : 
 1226                          1082                 :           2398 :     datum_to_jsonb_internal(val, is_null, result, tcategory, outfuncoid,
                               1083                 :                :                             key_scalar);
 4369 andrew@dunslane.net      1084                 :           2378 : }
                               1085                 :                : 
                               1086                 :                : 
                               1087                 :                : /*
                               1088                 :                :  * Is the given type immutable when coming out of a JSONB context?
                               1089                 :                :  *
                               1090                 :                :  * At present, datetimes are all considered mutable, because they
                               1091                 :                :  * depend on timezone.  XXX we should also drill down into objects and
                               1092                 :                :  * arrays, but do not.
                               1093                 :                :  */
                               1094                 :                : bool
 1340 alvherre@alvh.no-ip.     1095                 :UBC           0 : to_jsonb_is_immutable(Oid typoid)
                               1096                 :                : {
                               1097                 :                :     JsonTypeCategory tcategory;
                               1098                 :                :     Oid         outfuncoid;
                               1099                 :                : 
   22 andrew@dunslane.net      1100                 :              0 :     json_categorize_type(typoid, true, &tcategory, &outfuncoid);
                               1101                 :                : 
                               1102   [ #  #  #  #  :              0 :     switch (tcategory)
                                              #  # ]
                               1103                 :                :     {
                               1104                 :              0 :         case JSONTYPE_NULL:
                               1105                 :                :         case JSONTYPE_BOOL:
                               1106                 :                :         case JSONTYPE_JSON:
                               1107                 :                :         case JSONTYPE_JSONB:
                               1108                 :              0 :             return true;
                               1109                 :                : 
                               1110                 :              0 :         case JSONTYPE_DATE:
                               1111                 :                :         case JSONTYPE_TIMESTAMP:
                               1112                 :                :         case JSONTYPE_TIMESTAMPTZ:
                               1113                 :              0 :             return false;
                               1114                 :                : 
                               1115                 :              0 :         case JSONTYPE_ARRAY:
                               1116                 :              0 :             return false;       /* TODO recurse into elements */
                               1117                 :                : 
                               1118                 :              0 :         case JSONTYPE_COMPOSITE:
                               1119                 :              0 :             return false;       /* TODO recurse into fields */
                               1120                 :                : 
                               1121                 :              0 :         case JSONTYPE_NUMERIC:
                               1122                 :                :         case JSONTYPE_CAST:
                               1123                 :                :         case JSONTYPE_OTHER:
                               1124                 :              0 :             return func_volatile(outfuncoid) == PROVOLATILE_IMMUTABLE;
                               1125                 :                :     }
                               1126                 :                : 
                               1127                 :              0 :     return false;               /* not reached */
                               1128                 :                : }
                               1129                 :                : 
                               1130                 :                : /*
                               1131                 :                :  * SQL function to_jsonb(anyvalue)
                               1132                 :                :  */
                               1133                 :                : Datum
 4369 andrew@dunslane.net      1134                 :CBC         288 : to_jsonb(PG_FUNCTION_ARGS)
                               1135                 :                : {
                               1136                 :            288 :     Datum       val = PG_GETARG_DATUM(0);
                               1137                 :            288 :     Oid         val_type = get_fn_expr_argtype(fcinfo->flinfo, 0);
                               1138                 :                :     JsonTypeCategory tcategory;
                               1139                 :                :     Oid         outfuncoid;
                               1140                 :                : 
                               1141         [ -  + ]:            288 :     if (val_type == InvalidOid)
 4369 andrew@dunslane.net      1142         [ #  # ]:UBC           0 :         ereport(ERROR,
                               1143                 :                :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                               1144                 :                :                  errmsg("could not determine input data type")));
                               1145                 :                : 
 1227 amitlan@postgresql.o     1146                 :CBC         288 :     json_categorize_type(val_type, true,
                               1147                 :                :                          &tcategory, &outfuncoid);
                               1148                 :                : 
 1226                          1149                 :            288 :     PG_RETURN_DATUM(datum_to_jsonb(val, tcategory, outfuncoid));
                               1150                 :                : }
                               1151                 :                : 
                               1152                 :                : /*
                               1153                 :                :  * Turn a Datum into jsonb.
                               1154                 :                :  *
                               1155                 :                :  * tcategory and outfuncoid are from a previous call to json_categorize_type.
                               1156                 :                :  */
                               1157                 :                : Datum
                               1158                 :            288 : datum_to_jsonb(Datum val, JsonTypeCategory tcategory, Oid outfuncoid)
                               1159                 :                : {
                               1160                 :                :     JsonbInState result;
                               1161                 :                : 
 1549 andrew@dunslane.net      1162                 :            288 :     memset(&result, 0, sizeof(JsonbInState));
                               1163                 :                : 
 1226 amitlan@postgresql.o     1164                 :            288 :     datum_to_jsonb_internal(val, false, &result, tcategory, outfuncoid,
                               1165                 :                :                             false);
                               1166                 :                : 
  356 tgl@sss.pgh.pa.us        1167                 :            284 :     return JsonbPGetDatum(JsonbValueToJsonb(result.result));
                               1168                 :                : }
                               1169                 :                : 
                               1170                 :                : Datum
 1145 peter@eisentraut.org     1171                 :            331 : jsonb_build_object_worker(int nargs, const Datum *args, const bool *nulls, const Oid *types,
                               1172                 :                :                           bool absent_on_null, bool unique_keys)
                               1173                 :                : {
                               1174                 :                :     int         i;
                               1175                 :                :     JsonbInState result;
                               1176                 :                : 
 4369 andrew@dunslane.net      1177         [ +  + ]:            331 :     if (nargs % 2 != 0)
                               1178         [ +  - ]:             12 :         ereport(ERROR,
                               1179                 :                :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                               1180                 :                :                  errmsg("argument list must have even number of elements"),
                               1181                 :                :         /* translator: %s is a SQL function name */
                               1182                 :                :                  errhint("The arguments of %s must consist of alternating keys and values.",
                               1183                 :                :                          "jsonb_build_object()")));
                               1184                 :                : 
                               1185                 :            319 :     memset(&result, 0, sizeof(JsonbInState));
                               1186                 :                : 
  356 tgl@sss.pgh.pa.us        1187                 :            319 :     pushJsonbValue(&result, WJB_BEGIN_OBJECT, NULL);
 1340 alvherre@alvh.no-ip.     1188                 :            319 :     result.parseState->unique_keys = unique_keys;
                               1189                 :            319 :     result.parseState->skip_nulls = absent_on_null;
                               1190                 :                : 
 4369 andrew@dunslane.net      1191         [ +  + ]:           1395 :     for (i = 0; i < nargs; i += 2)
                               1192                 :                :     {
                               1193                 :                :         /* process key */
                               1194                 :                :         bool        skip;
                               1195                 :                : 
 3321                          1196         [ +  + ]:           1108 :         if (nulls[i])
 4369                          1197         [ +  - ]:             12 :             ereport(ERROR,
                               1198                 :                :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                               1199                 :                :                      errmsg("argument %d: key must not be null", i + 1)));
                               1200                 :                : 
                               1201                 :                :         /* skip null values if absent_on_null */
 1340 alvherre@alvh.no-ip.     1202   [ +  +  +  + ]:           1096 :         skip = absent_on_null && nulls[i + 1];
                               1203                 :                : 
                               1204                 :                :         /* we need to save skipped keys for the key uniqueness check */
                               1205   [ +  +  +  + ]:           1096 :         if (skip && !unique_keys)
                               1206                 :              5 :             continue;
                               1207                 :                : 
 3321 andrew@dunslane.net      1208                 :           1091 :         add_jsonb(args[i], false, &result, types[i], true);
                               1209                 :                : 
                               1210                 :                :         /* process value */
                               1211                 :           1071 :         add_jsonb(args[i + 1], nulls[i + 1], &result, types[i + 1], false);
                               1212                 :                :     }
                               1213                 :                : 
  356 tgl@sss.pgh.pa.us        1214                 :            287 :     pushJsonbValue(&result, WJB_END_OBJECT, NULL);
                               1215                 :                : 
                               1216                 :            275 :     return JsonbPGetDatum(JsonbValueToJsonb(result.result));
                               1217                 :                : }
                               1218                 :                : 
                               1219                 :                : /*
                               1220                 :                :  * SQL function jsonb_build_object(variadic "any")
                               1221                 :                :  */
                               1222                 :                : Datum
 1340 alvherre@alvh.no-ip.     1223                 :            282 : jsonb_build_object(PG_FUNCTION_ARGS)
                               1224                 :                : {
                               1225                 :                :     Datum      *args;
                               1226                 :                :     bool       *nulls;
                               1227                 :                :     Oid        *types;
                               1228                 :                : 
                               1229                 :                :     /* build argument values to build the object */
                               1230                 :            282 :     int         nargs = extract_variadic_args(fcinfo, 0, true,
                               1231                 :                :                                               &args, &types, &nulls);
                               1232                 :                : 
                               1233         [ +  + ]:            282 :     if (nargs < 0)
                               1234                 :              4 :         PG_RETURN_NULL();
                               1235                 :                : 
                               1236                 :            278 :     PG_RETURN_DATUM(jsonb_build_object_worker(nargs, args, nulls, types, false, false));
                               1237                 :                : }
                               1238                 :                : 
                               1239                 :                : /*
                               1240                 :                :  * degenerate case of jsonb_build_object where it gets 0 arguments.
                               1241                 :                :  */
                               1242                 :                : Datum
 4369 andrew@dunslane.net      1243                 :              4 : jsonb_build_object_noargs(PG_FUNCTION_ARGS)
                               1244                 :                : {
                               1245                 :                :     JsonbInState result;
                               1246                 :                : 
                               1247                 :              4 :     memset(&result, 0, sizeof(JsonbInState));
                               1248                 :                : 
  356 tgl@sss.pgh.pa.us        1249                 :              4 :     pushJsonbValue(&result, WJB_BEGIN_OBJECT, NULL);
                               1250                 :              4 :     pushJsonbValue(&result, WJB_END_OBJECT, NULL);
                               1251                 :                : 
                               1252                 :              4 :     PG_RETURN_POINTER(JsonbValueToJsonb(result.result));
                               1253                 :                : }
                               1254                 :                : 
                               1255                 :                : Datum
 1145 peter@eisentraut.org     1256                 :            117 : jsonb_build_array_worker(int nargs, const Datum *args, const bool *nulls, const Oid *types,
                               1257                 :                :                          bool absent_on_null)
                               1258                 :                : {
                               1259                 :                :     int         i;
                               1260                 :                :     JsonbInState result;
                               1261                 :                : 
 1549 andrew@dunslane.net      1262                 :            117 :     memset(&result, 0, sizeof(JsonbInState));
                               1263                 :                : 
  356 tgl@sss.pgh.pa.us        1264                 :            117 :     pushJsonbValue(&result, WJB_BEGIN_ARRAY, NULL);
                               1265                 :                : 
 1549 andrew@dunslane.net      1266         [ +  + ]:            369 :     for (i = 0; i < nargs; i++)
                               1267                 :                :     {
 1340 alvherre@alvh.no-ip.     1268   [ +  +  +  + ]:            252 :         if (absent_on_null && nulls[i])
                               1269                 :             16 :             continue;
                               1270                 :                : 
 1549 andrew@dunslane.net      1271                 :            236 :         add_jsonb(args[i], nulls[i], &result, types[i], false);
                               1272                 :                :     }
                               1273                 :                : 
  356 tgl@sss.pgh.pa.us        1274                 :            117 :     pushJsonbValue(&result, WJB_END_ARRAY, NULL);
                               1275                 :                : 
                               1276                 :            117 :     return JsonbPGetDatum(JsonbValueToJsonb(result.result));
                               1277                 :                : }
                               1278                 :                : 
                               1279                 :                : /*
                               1280                 :                :  * SQL function jsonb_build_array(variadic "any")
                               1281                 :                :  */
                               1282                 :                : Datum
 1340 alvherre@alvh.no-ip.     1283                 :            100 : jsonb_build_array(PG_FUNCTION_ARGS)
                               1284                 :                : {
                               1285                 :                :     Datum      *args;
                               1286                 :                :     bool       *nulls;
                               1287                 :                :     Oid        *types;
                               1288                 :                : 
                               1289                 :                :     /* build argument values to build the object */
                               1290                 :            100 :     int         nargs = extract_variadic_args(fcinfo, 0, true,
                               1291                 :                :                                               &args, &types, &nulls);
                               1292                 :                : 
                               1293         [ +  + ]:            100 :     if (nargs < 0)
                               1294                 :              4 :         PG_RETURN_NULL();
                               1295                 :                : 
                               1296                 :             96 :     PG_RETURN_DATUM(jsonb_build_array_worker(nargs, args, nulls, types, false));
                               1297                 :                : }
                               1298                 :                : 
                               1299                 :                : 
                               1300                 :                : /*
                               1301                 :                :  * degenerate case of jsonb_build_array where it gets 0 arguments.
                               1302                 :                :  */
                               1303                 :                : Datum
 4369 andrew@dunslane.net      1304                 :              4 : jsonb_build_array_noargs(PG_FUNCTION_ARGS)
                               1305                 :                : {
                               1306                 :                :     JsonbInState result;
                               1307                 :                : 
                               1308                 :              4 :     memset(&result, 0, sizeof(JsonbInState));
                               1309                 :                : 
  356 tgl@sss.pgh.pa.us        1310                 :              4 :     pushJsonbValue(&result, WJB_BEGIN_ARRAY, NULL);
                               1311                 :              4 :     pushJsonbValue(&result, WJB_END_ARRAY, NULL);
                               1312                 :                : 
                               1313                 :              4 :     PG_RETURN_POINTER(JsonbValueToJsonb(result.result));
                               1314                 :                : }
                               1315                 :                : 
                               1316                 :                : 
                               1317                 :                : /*
                               1318                 :                :  * SQL function jsonb_object(text[])
                               1319                 :                :  *
                               1320                 :                :  * take a one or two dimensional array of text as name value pairs
                               1321                 :                :  * for a jsonb object.
                               1322                 :                :  *
                               1323                 :                :  */
                               1324                 :                : Datum
 4369 andrew@dunslane.net      1325                 :             31 : jsonb_object(PG_FUNCTION_ARGS)
                               1326                 :                : {
                               1327                 :             31 :     ArrayType  *in_array = PG_GETARG_ARRAYTYPE_P(0);
                               1328                 :             31 :     int         ndims = ARR_NDIM(in_array);
                               1329                 :                :     Datum      *in_datums;
                               1330                 :                :     bool       *in_nulls;
                               1331                 :                :     int         in_count,
                               1332                 :                :                 count,
                               1333                 :                :                 i;
                               1334                 :                :     JsonbInState result;
                               1335                 :                : 
                               1336                 :             31 :     memset(&result, 0, sizeof(JsonbInState));
                               1337                 :                : 
  356 tgl@sss.pgh.pa.us        1338                 :             31 :     pushJsonbValue(&result, WJB_BEGIN_OBJECT, NULL);
                               1339                 :                : 
 4369 andrew@dunslane.net      1340   [ +  +  +  + ]:             31 :     switch (ndims)
                               1341                 :                :     {
                               1342                 :              5 :         case 0:
                               1343                 :              5 :             goto close_object;
                               1344                 :                :             break;
                               1345                 :                : 
                               1346                 :              9 :         case 1:
                               1347         [ +  + ]:              9 :             if ((ARR_DIMS(in_array)[0]) % 2)
                               1348         [ +  - ]:              4 :                 ereport(ERROR,
                               1349                 :                :                         (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
                               1350                 :                :                          errmsg("array must have even number of elements")));
                               1351                 :              5 :             break;
                               1352                 :                : 
                               1353                 :             13 :         case 2:
                               1354         [ +  + ]:             13 :             if ((ARR_DIMS(in_array)[1]) != 2)
                               1355         [ +  - ]:              8 :                 ereport(ERROR,
                               1356                 :                :                         (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
                               1357                 :                :                          errmsg("array must have two columns")));
                               1358                 :              5 :             break;
                               1359                 :                : 
                               1360                 :              4 :         default:
                               1361         [ +  - ]:              4 :             ereport(ERROR,
                               1362                 :                :                     (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
                               1363                 :                :                      errmsg("wrong number of array subscripts")));
                               1364                 :                :     }
                               1365                 :                : 
 1611 peter@eisentraut.org     1366                 :             10 :     deconstruct_array_builtin(in_array, TEXTOID, &in_datums, &in_nulls, &in_count);
                               1367                 :                : 
 4369 andrew@dunslane.net      1368                 :             10 :     count = in_count / 2;
                               1369                 :                : 
                               1370         [ +  + ]:             50 :     for (i = 0; i < count; ++i)
                               1371                 :                :     {
                               1372                 :                :         JsonbValue  v;
                               1373                 :                :         char       *str;
                               1374                 :                :         int         len;
                               1375                 :                : 
                               1376         [ -  + ]:             40 :         if (in_nulls[i * 2])
 4369 andrew@dunslane.net      1377         [ #  # ]:UBC           0 :             ereport(ERROR,
                               1378                 :                :                     (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
                               1379                 :                :                      errmsg("null value not allowed for object key")));
                               1380                 :                : 
 4369 andrew@dunslane.net      1381                 :CBC          40 :         str = TextDatumGetCString(in_datums[i * 2]);
                               1382                 :             40 :         len = strlen(str);
                               1383                 :                : 
                               1384                 :             40 :         v.type = jbvString;
                               1385                 :                : 
                               1386                 :             40 :         v.val.string.len = len;
                               1387                 :             40 :         v.val.string.val = str;
                               1388                 :                : 
  356 tgl@sss.pgh.pa.us        1389                 :             40 :         pushJsonbValue(&result, WJB_KEY, &v);
                               1390                 :                : 
 4369 andrew@dunslane.net      1391         [ +  + ]:             40 :         if (in_nulls[i * 2 + 1])
                               1392                 :                :         {
                               1393                 :             10 :             v.type = jbvNull;
                               1394                 :                :         }
                               1395                 :                :         else
                               1396                 :                :         {
                               1397                 :             30 :             str = TextDatumGetCString(in_datums[i * 2 + 1]);
                               1398                 :             30 :             len = strlen(str);
                               1399                 :                : 
                               1400                 :             30 :             v.type = jbvString;
                               1401                 :                : 
                               1402                 :             30 :             v.val.string.len = len;
                               1403                 :             30 :             v.val.string.val = str;
                               1404                 :                :         }
                               1405                 :                : 
  356 tgl@sss.pgh.pa.us        1406                 :             40 :         pushJsonbValue(&result, WJB_VALUE, &v);
                               1407                 :                :     }
                               1408                 :                : 
 4369 andrew@dunslane.net      1409                 :             10 :     pfree(in_datums);
                               1410                 :             10 :     pfree(in_nulls);
                               1411                 :                : 
                               1412                 :             15 : close_object:
  356 tgl@sss.pgh.pa.us        1413                 :             15 :     pushJsonbValue(&result, WJB_END_OBJECT, NULL);
                               1414                 :                : 
                               1415                 :             15 :     PG_RETURN_POINTER(JsonbValueToJsonb(result.result));
                               1416                 :                : }
                               1417                 :                : 
                               1418                 :                : /*
                               1419                 :                :  * SQL function jsonb_object(text[], text[])
                               1420                 :                :  *
                               1421                 :                :  * take separate name and value arrays of text to construct a jsonb object
                               1422                 :                :  * pairwise.
                               1423                 :                :  */
                               1424                 :                : Datum
 4369 andrew@dunslane.net      1425                 :             31 : jsonb_object_two_arg(PG_FUNCTION_ARGS)
                               1426                 :                : {
                               1427                 :             31 :     ArrayType  *key_array = PG_GETARG_ARRAYTYPE_P(0);
                               1428                 :             31 :     ArrayType  *val_array = PG_GETARG_ARRAYTYPE_P(1);
                               1429                 :             31 :     int         nkdims = ARR_NDIM(key_array);
                               1430                 :             31 :     int         nvdims = ARR_NDIM(val_array);
                               1431                 :                :     Datum      *key_datums,
                               1432                 :                :                *val_datums;
                               1433                 :                :     bool       *key_nulls,
                               1434                 :                :                *val_nulls;
                               1435                 :                :     int         key_count,
                               1436                 :                :                 val_count,
                               1437                 :                :                 i;
                               1438                 :                :     JsonbInState result;
                               1439                 :                : 
                               1440                 :             31 :     memset(&result, 0, sizeof(JsonbInState));
                               1441                 :                : 
  356 tgl@sss.pgh.pa.us        1442                 :             31 :     pushJsonbValue(&result, WJB_BEGIN_OBJECT, NULL);
                               1443                 :                : 
 4369 andrew@dunslane.net      1444   [ +  +  -  + ]:             31 :     if (nkdims > 1 || nkdims != nvdims)
                               1445         [ +  - ]:              4 :         ereport(ERROR,
                               1446                 :                :                 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
                               1447                 :                :                  errmsg("wrong number of array subscripts")));
                               1448                 :                : 
                               1449         [ +  + ]:             27 :     if (nkdims == 0)
 3933                          1450                 :              5 :         goto close_object;
                               1451                 :                : 
 1611 peter@eisentraut.org     1452                 :             22 :     deconstruct_array_builtin(key_array, TEXTOID, &key_datums, &key_nulls, &key_count);
                               1453                 :             22 :     deconstruct_array_builtin(val_array, TEXTOID, &val_datums, &val_nulls, &val_count);
                               1454                 :                : 
 4369 andrew@dunslane.net      1455         [ +  + ]:             22 :     if (key_count != val_count)
                               1456         [ +  - ]:              8 :         ereport(ERROR,
                               1457                 :                :                 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
                               1458                 :                :                  errmsg("mismatched array dimensions")));
                               1459                 :                : 
                               1460         [ +  + ]:             62 :     for (i = 0; i < key_count; ++i)
                               1461                 :                :     {
                               1462                 :                :         JsonbValue  v;
                               1463                 :                :         char       *str;
                               1464                 :                :         int         len;
                               1465                 :                : 
                               1466         [ +  + ]:             52 :         if (key_nulls[i])
                               1467         [ +  - ]:              4 :             ereport(ERROR,
                               1468                 :                :                     (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
                               1469                 :                :                      errmsg("null value not allowed for object key")));
                               1470                 :                : 
                               1471                 :             48 :         str = TextDatumGetCString(key_datums[i]);
                               1472                 :             48 :         len = strlen(str);
                               1473                 :                : 
                               1474                 :             48 :         v.type = jbvString;
                               1475                 :                : 
                               1476                 :             48 :         v.val.string.len = len;
                               1477                 :             48 :         v.val.string.val = str;
                               1478                 :                : 
  356 tgl@sss.pgh.pa.us        1479                 :             48 :         pushJsonbValue(&result, WJB_KEY, &v);
                               1480                 :                : 
 4369 andrew@dunslane.net      1481         [ -  + ]:             48 :         if (val_nulls[i])
                               1482                 :                :         {
 4369 andrew@dunslane.net      1483                 :UBC           0 :             v.type = jbvNull;
                               1484                 :                :         }
                               1485                 :                :         else
                               1486                 :                :         {
 4369 andrew@dunslane.net      1487                 :CBC          48 :             str = TextDatumGetCString(val_datums[i]);
                               1488                 :             48 :             len = strlen(str);
                               1489                 :                : 
                               1490                 :             48 :             v.type = jbvString;
                               1491                 :                : 
                               1492                 :             48 :             v.val.string.len = len;
                               1493                 :             48 :             v.val.string.val = str;
                               1494                 :                :         }
                               1495                 :                : 
  356 tgl@sss.pgh.pa.us        1496                 :             48 :         pushJsonbValue(&result, WJB_VALUE, &v);
                               1497                 :                :     }
                               1498                 :                : 
 4369 andrew@dunslane.net      1499                 :             10 :     pfree(key_datums);
                               1500                 :             10 :     pfree(key_nulls);
                               1501                 :             10 :     pfree(val_datums);
                               1502                 :             10 :     pfree(val_nulls);
                               1503                 :                : 
 3933                          1504                 :             15 : close_object:
  356 tgl@sss.pgh.pa.us        1505                 :             15 :     pushJsonbValue(&result, WJB_END_OBJECT, NULL);
                               1506                 :                : 
                               1507                 :             15 :     PG_RETURN_POINTER(JsonbValueToJsonb(result.result));
                               1508                 :                : }
                               1509                 :                : 
                               1510                 :                : 
                               1511                 :                : /*
                               1512                 :                :  * Functions for jsonb_agg, jsonb_object_agg, and variants
                               1513                 :                :  */
                               1514                 :                : 
                               1515                 :                : static Datum
 1340 alvherre@alvh.no-ip.     1516                 :            338 : jsonb_agg_transfn_worker(FunctionCallInfo fcinfo, bool absent_on_null)
                               1517                 :                : {
                               1518                 :                :     MemoryContext aggcontext;
                               1519                 :                :     JsonbAggState *state;
                               1520                 :                :     Datum       val;
                               1521                 :                :     JsonbInState *result;
                               1522                 :                : 
 4369 andrew@dunslane.net      1523         [ -  + ]:            338 :     if (!AggCheckCallContext(fcinfo, &aggcontext))
                               1524                 :                :     {
                               1525                 :                :         /* cannot be called directly because of internal-type argument */
 4369 andrew@dunslane.net      1526         [ #  # ]:UBC           0 :         elog(ERROR, "jsonb_agg_transfn called in non-aggregate context");
                               1527                 :                :     }
                               1528                 :                : 
                               1529                 :                :     /* set up the accumulator on the first go round */
                               1530                 :                : 
 4369 andrew@dunslane.net      1531         [ +  + ]:CBC         338 :     if (PG_ARGISNULL(0))
                               1532                 :                :     {
 4062 tgl@sss.pgh.pa.us        1533                 :            116 :         Oid         arg_type = get_fn_expr_argtype(fcinfo->flinfo, 1);
                               1534                 :                : 
 4089 andrew@dunslane.net      1535         [ -  + ]:            116 :         if (arg_type == InvalidOid)
 4089 andrew@dunslane.net      1536         [ #  # ]:UBC           0 :             ereport(ERROR,
                               1537                 :                :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                               1538                 :                :                      errmsg("could not determine input data type")));
                               1539                 :                : 
  356 tgl@sss.pgh.pa.us        1540                 :CBC         116 :         state = MemoryContextAllocZero(aggcontext, sizeof(JsonbAggState));
                               1541                 :            116 :         result = &state->pstate;
                               1542                 :            116 :         result->outcontext = aggcontext;
                               1543                 :            116 :         pushJsonbValue(result, WJB_BEGIN_ARRAY, NULL);
                               1544                 :                : 
 1227 amitlan@postgresql.o     1545                 :            116 :         json_categorize_type(arg_type, true, &state->val_category,
                               1546                 :                :                              &state->val_output_func);
                               1547                 :                :     }
                               1548                 :                :     else
                               1549                 :                :     {
 4089 andrew@dunslane.net      1550                 :            222 :         state = (JsonbAggState *) PG_GETARG_POINTER(0);
  356 tgl@sss.pgh.pa.us        1551                 :            222 :         result = &state->pstate;
                               1552                 :                :     }
                               1553                 :                : 
 1340 alvherre@alvh.no-ip.     1554   [ +  +  +  + ]:            338 :     if (absent_on_null && PG_ARGISNULL(1))
                               1555                 :             52 :         PG_RETURN_POINTER(state);
                               1556                 :                : 
                               1557                 :                :     /*
                               1558                 :                :      * We run this code in the normal function context, so that we don't leak
                               1559                 :                :      * any cruft from datatype output functions and such into the aggcontext.
                               1560                 :                :      * But the "result" JsonbValue will be constructed in aggcontext, so that
                               1561                 :                :      * it remains available across calls.
                               1562                 :                :      */
 4089 andrew@dunslane.net      1563         [ +  + ]:            286 :     val = PG_ARGISNULL(1) ? (Datum) 0 : PG_GETARG_DATUM(1);
                               1564                 :                : 
  356 tgl@sss.pgh.pa.us        1565                 :            286 :     datum_to_jsonb_internal(val, PG_ARGISNULL(1), result, state->val_category,
                               1566                 :                :                             state->val_output_func, false);
                               1567                 :                : 
 4089 andrew@dunslane.net      1568                 :            286 :     PG_RETURN_POINTER(state);
                               1569                 :                : }
                               1570                 :                : 
                               1571                 :                : /*
                               1572                 :                :  * jsonb_agg aggregate function
                               1573                 :                :  */
                               1574                 :                : Datum
 1340 alvherre@alvh.no-ip.     1575                 :            170 : jsonb_agg_transfn(PG_FUNCTION_ARGS)
                               1576                 :                : {
                               1577                 :            170 :     return jsonb_agg_transfn_worker(fcinfo, false);
                               1578                 :                : }
                               1579                 :                : 
                               1580                 :                : /*
                               1581                 :                :  * jsonb_agg_strict aggregate function
                               1582                 :                :  */
                               1583                 :                : Datum
                               1584                 :            168 : jsonb_agg_strict_transfn(PG_FUNCTION_ARGS)
                               1585                 :                : {
                               1586                 :            168 :     return jsonb_agg_transfn_worker(fcinfo, true);
                               1587                 :                : }
                               1588                 :                : 
                               1589                 :                : Datum
 4369 andrew@dunslane.net      1590                 :            141 : jsonb_agg_finalfn(PG_FUNCTION_ARGS)
                               1591                 :                : {
                               1592                 :                :     JsonbAggState *arg;
                               1593                 :                :     JsonbInState result;
                               1594                 :                :     Jsonb      *out;
                               1595                 :                : 
                               1596                 :                :     /* cannot be called directly because of internal-type argument */
                               1597         [ -  + ]:            141 :     Assert(AggCheckCallContext(fcinfo, NULL));
                               1598                 :                : 
                               1599         [ +  + ]:            141 :     if (PG_ARGISNULL(0))
                               1600                 :             17 :         PG_RETURN_NULL();       /* returns null iff no input values */
                               1601                 :                : 
 4089                          1602                 :            124 :     arg = (JsonbAggState *) PG_GETARG_POINTER(0);
                               1603                 :                : 
                               1604                 :                :     /*
                               1605                 :                :      * The final function can be called more than once, so we must not change
                               1606                 :                :      * the stored JsonbValue data structure.  Fortunately, the WJB_END_ARRAY
                               1607                 :                :      * action will only change fields in the JsonbInState struct itself, so we
                               1608                 :                :      * can simply invoke pushJsonbValue on a local copy of that.
                               1609                 :                :      */
  356 tgl@sss.pgh.pa.us        1610                 :            124 :     result = arg->pstate;
                               1611                 :                : 
                               1612                 :            124 :     pushJsonbValue(&result, WJB_END_ARRAY, NULL);
                               1613                 :                : 
                               1614                 :                :     /* We expect result.parseState == NULL after closing the array */
                               1615         [ -  + ]:            124 :     Assert(result.parseState == NULL);
                               1616                 :                : 
                               1617                 :            124 :     out = JsonbValueToJsonb(result.result);
                               1618                 :                : 
 4369 andrew@dunslane.net      1619                 :            124 :     PG_RETURN_POINTER(out);
                               1620                 :                : }
                               1621                 :                : 
                               1622                 :                : static Datum
 1340 alvherre@alvh.no-ip.     1623                 :           1092 : jsonb_object_agg_transfn_worker(FunctionCallInfo fcinfo,
                               1624                 :                :                                 bool absent_on_null, bool unique_keys)
                               1625                 :                : {
                               1626                 :                :     MemoryContext aggcontext;
                               1627                 :                :     JsonbAggState *state;
                               1628                 :                :     Datum       val;
                               1629                 :                :     JsonbInState *result;
                               1630                 :                :     bool        skip;
                               1631                 :                : 
 4369 andrew@dunslane.net      1632         [ -  + ]:           1092 :     if (!AggCheckCallContext(fcinfo, &aggcontext))
                               1633                 :                :     {
                               1634                 :                :         /* cannot be called directly because of internal-type argument */
 4369 andrew@dunslane.net      1635         [ #  # ]:UBC           0 :         elog(ERROR, "jsonb_object_agg_transfn called in non-aggregate context");
                               1636                 :                :     }
                               1637                 :                : 
                               1638                 :                :     /* set up the accumulator on the first go round */
                               1639                 :                : 
 4089 andrew@dunslane.net      1640         [ +  + ]:CBC        1092 :     if (PG_ARGISNULL(0))
                               1641                 :                :     {
                               1642                 :                :         Oid         arg_type;
                               1643                 :                : 
  356 tgl@sss.pgh.pa.us        1644                 :             88 :         state = MemoryContextAllocZero(aggcontext, sizeof(JsonbAggState));
                               1645                 :             88 :         result = &state->pstate;
                               1646                 :             88 :         result->outcontext = aggcontext;
                               1647                 :             88 :         pushJsonbValue(result, WJB_BEGIN_OBJECT, NULL);
 1340 alvherre@alvh.no-ip.     1648                 :             88 :         result->parseState->unique_keys = unique_keys;
                               1649                 :             88 :         result->parseState->skip_nulls = absent_on_null;
                               1650                 :                : 
 4089 andrew@dunslane.net      1651                 :             88 :         arg_type = get_fn_expr_argtype(fcinfo->flinfo, 1);
                               1652                 :                : 
                               1653         [ -  + ]:             88 :         if (arg_type == InvalidOid)
 4089 andrew@dunslane.net      1654         [ #  # ]:UBC           0 :             ereport(ERROR,
                               1655                 :                :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                               1656                 :                :                      errmsg("could not determine input data type")));
                               1657                 :                : 
 1227 amitlan@postgresql.o     1658                 :CBC          88 :         json_categorize_type(arg_type, true, &state->key_category,
                               1659                 :                :                              &state->key_output_func);
                               1660                 :                : 
 4089 andrew@dunslane.net      1661                 :             88 :         arg_type = get_fn_expr_argtype(fcinfo->flinfo, 2);
                               1662                 :                : 
                               1663         [ -  + ]:             88 :         if (arg_type == InvalidOid)
 4089 andrew@dunslane.net      1664         [ #  # ]:UBC           0 :             ereport(ERROR,
                               1665                 :                :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                               1666                 :                :                      errmsg("could not determine input data type")));
                               1667                 :                : 
 1227 amitlan@postgresql.o     1668                 :CBC          88 :         json_categorize_type(arg_type, true, &state->val_category,
                               1669                 :                :                              &state->val_output_func);
                               1670                 :                :     }
                               1671                 :                :     else
                               1672                 :                :     {
 4089 andrew@dunslane.net      1673                 :           1004 :         state = (JsonbAggState *) PG_GETARG_POINTER(0);
  356 tgl@sss.pgh.pa.us        1674                 :           1004 :         result = &state->pstate;
                               1675                 :                :     }
                               1676                 :                : 
 4145 andrew@dunslane.net      1677         [ +  + ]:           1092 :     if (PG_ARGISNULL(1))
                               1678         [ +  - ]:             12 :         ereport(ERROR,
                               1679                 :                :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                               1680                 :                :                  errmsg("field name must not be null")));
                               1681                 :                : 
                               1682                 :                :     /*
                               1683                 :                :      * Skip null values if absent_on_null unless key uniqueness check is
                               1684                 :                :      * needed (because we must save keys in this case).
                               1685                 :                :      */
 1340 alvherre@alvh.no-ip.     1686   [ +  +  +  + ]:           1080 :     skip = absent_on_null && PG_ARGISNULL(2);
                               1687                 :                : 
                               1688   [ +  +  +  + ]:           1080 :     if (skip && !unique_keys)
                               1689                 :              8 :         PG_RETURN_POINTER(state);
                               1690                 :                : 
                               1691                 :                :     /*
                               1692                 :                :      * We run this code in the normal function context, so that we don't leak
                               1693                 :                :      * any cruft from datatype output functions and such into the aggcontext.
                               1694                 :                :      * But the "result" JsonbValue will be constructed in aggcontext, so that
                               1695                 :                :      * it remains available across calls.
                               1696                 :                :      */
 4145 andrew@dunslane.net      1697                 :           1072 :     val = PG_GETARG_DATUM(1);
                               1698                 :                : 
  356 tgl@sss.pgh.pa.us        1699                 :           1072 :     datum_to_jsonb_internal(val, false, result, state->key_category,
                               1700                 :                :                             state->key_output_func, true);
                               1701                 :                : 
 4369 andrew@dunslane.net      1702         [ +  + ]:           1072 :     val = PG_ARGISNULL(2) ? (Datum) 0 : PG_GETARG_DATUM(2);
                               1703                 :                : 
  356 tgl@sss.pgh.pa.us        1704                 :           1072 :     datum_to_jsonb_internal(val, PG_ARGISNULL(2), result, state->val_category,
                               1705                 :                :                             state->val_output_func, false);
                               1706                 :                : 
 4089 andrew@dunslane.net      1707                 :           1072 :     PG_RETURN_POINTER(state);
                               1708                 :                : }
                               1709                 :                : 
                               1710                 :                : /*
                               1711                 :                :  * jsonb_object_agg aggregate function
                               1712                 :                :  */
                               1713                 :                : Datum
 1340 alvherre@alvh.no-ip.     1714                 :            116 : jsonb_object_agg_transfn(PG_FUNCTION_ARGS)
                               1715                 :                : {
                               1716                 :            116 :     return jsonb_object_agg_transfn_worker(fcinfo, false, false);
                               1717                 :                : }
                               1718                 :                : 
                               1719                 :                : 
                               1720                 :                : /*
                               1721                 :                :  * jsonb_object_agg_strict aggregate function
                               1722                 :                :  */
                               1723                 :                : Datum
                               1724                 :             28 : jsonb_object_agg_strict_transfn(PG_FUNCTION_ARGS)
                               1725                 :                : {
                               1726                 :             28 :     return jsonb_object_agg_transfn_worker(fcinfo, true, false);
                               1727                 :                : }
                               1728                 :                : 
                               1729                 :                : /*
                               1730                 :                :  * jsonb_object_agg_unique aggregate function
                               1731                 :                :  */
                               1732                 :                : Datum
                               1733                 :            864 : jsonb_object_agg_unique_transfn(PG_FUNCTION_ARGS)
                               1734                 :                : {
                               1735                 :            864 :     return jsonb_object_agg_transfn_worker(fcinfo, false, true);
                               1736                 :                : }
                               1737                 :                : 
                               1738                 :                : /*
                               1739                 :                :  * jsonb_object_agg_unique_strict aggregate function
                               1740                 :                :  */
                               1741                 :                : Datum
                               1742                 :             84 : jsonb_object_agg_unique_strict_transfn(PG_FUNCTION_ARGS)
                               1743                 :                : {
                               1744                 :             84 :     return jsonb_object_agg_transfn_worker(fcinfo, true, true);
                               1745                 :                : }
                               1746                 :                : 
                               1747                 :                : Datum
 4369 andrew@dunslane.net      1748                 :            165 : jsonb_object_agg_finalfn(PG_FUNCTION_ARGS)
                               1749                 :                : {
                               1750                 :                :     JsonbAggState *arg;
                               1751                 :                :     JsonbInState result;
                               1752                 :                :     JsonbParseState copyps;
                               1753                 :                :     Jsonb      *out;
                               1754                 :                : 
                               1755                 :                :     /* cannot be called directly because of internal-type argument */
                               1756         [ -  + ]:            165 :     Assert(AggCheckCallContext(fcinfo, NULL));
                               1757                 :                : 
                               1758         [ +  + ]:            165 :     if (PG_ARGISNULL(0))
                               1759                 :              5 :         PG_RETURN_NULL();       /* returns null iff no input values */
                               1760                 :                : 
 4089                          1761                 :            160 :     arg = (JsonbAggState *) PG_GETARG_POINTER(0);
                               1762                 :                : 
                               1763                 :                :     /*
                               1764                 :                :      * The final function can be called more than once, so we must not change
                               1765                 :                :      * the stored JsonbValue data structure.  Fortunately, the WJB_END_OBJECT
                               1766                 :                :      * action will only destructively change fields in the JsonbInState struct
                               1767                 :                :      * itself, so we can simply invoke pushJsonbValue on a local copy of that.
                               1768                 :                :      * Note that this will run uniqueifyJsonbObject each time; that's hard to
                               1769                 :                :      * avoid, since duplicate pairs may have been added since the previous
                               1770                 :                :      * finalization.  uniqueifyJsonbObject can be applied repeatedly (with the
                               1771                 :                :      * same unique_keys/skip_nulls options) without breaking the data
                               1772                 :                :      * structure invariants, except that it removes null values if told to.
                               1773                 :                :      * That's problematic when unique_keys is also set, since that might
                               1774                 :                :      * prevent detection of a later-added key that duplicates an existing one
                               1775                 :                :      * with null value.  Therefore, when both options are set, make a copy of
                               1776                 :                :      * the pairs array and uniqueify that, keeping the original unmodified.
                               1777                 :                :      */
  356 tgl@sss.pgh.pa.us        1778                 :            160 :     result = arg->pstate;
   45                          1779   [ +  +  +  + ]:            160 :     if (result.parseState->unique_keys && result.parseState->skip_nulls)
                               1780                 :                :     {
                               1781                 :             56 :         JsonbParseState *oldps = result.parseState;
                               1782                 :             56 :         int         npairs = oldps->contVal.val.object.nPairs;
                               1783                 :                : 
                               1784         [ -  + ]:             56 :         Assert(oldps->next == NULL);
                               1785                 :             56 :         copyps = *oldps;
                               1786                 :             56 :         copyps.contVal.val.object.pairs = palloc_array(JsonbPair, npairs);
                               1787                 :             56 :         memcpy(copyps.contVal.val.object.pairs,
                               1788                 :             56 :                oldps->contVal.val.object.pairs,
                               1789                 :                :                npairs * sizeof(JsonbPair));
                               1790                 :             56 :         result.parseState = &copyps;
                               1791                 :                :     }
                               1792                 :                : 
  356                          1793                 :            160 :     pushJsonbValue(&result, WJB_END_OBJECT, NULL);
                               1794                 :                : 
                               1795                 :                :     /* We expect result.parseState == NULL after closing the object */
                               1796         [ -  + ]:            144 :     Assert(result.parseState == NULL);
                               1797                 :                : 
                               1798                 :            144 :     out = JsonbValueToJsonb(result.result);
                               1799                 :                : 
 4369 andrew@dunslane.net      1800                 :            144 :     PG_RETURN_POINTER(out);
                               1801                 :                : }
                               1802                 :                : 
                               1803                 :                : 
                               1804                 :                : /*
                               1805                 :                :  * Extract scalar value from raw-scalar pseudo-array jsonb.
                               1806                 :                :  */
                               1807                 :                : bool
 3166 teodor@sigaev.ru         1808                 :         156180 : JsonbExtractScalar(JsonbContainer *jbc, JsonbValue *res)
                               1809                 :                : {
                               1810                 :                :     JsonbIterator *it;
                               1811                 :                :     JsonbIteratorToken tok PG_USED_FOR_ASSERTS_ONLY;
                               1812                 :                :     JsonbValue  tmp;
                               1813                 :                : 
                               1814   [ +  +  +  + ]:         156180 :     if (!JsonContainerIsArray(jbc) || !JsonContainerIsScalar(jbc))
                               1815                 :                :     {
                               1816                 :                :         /* inform caller about actual type of container */
 3125                          1817         [ +  + ]:         150476 :         res->type = (JsonContainerIsArray(jbc)) ? jbvArray : jbvObject;
                               1818                 :         150476 :         return false;
                               1819                 :                :     }
                               1820                 :                : 
                               1821                 :                :     /*
                               1822                 :                :      * A root scalar is stored as an array of one element, so we get the array
                               1823                 :                :      * and then its first (and only) member.
                               1824                 :                :      */
 3166                          1825                 :           5704 :     it = JsonbIteratorInit(jbc);
                               1826                 :                : 
                               1827                 :           5704 :     tok = JsonbIteratorNext(&it, &tmp, true);
                               1828         [ -  + ]:           5704 :     Assert(tok == WJB_BEGIN_ARRAY);
                               1829   [ +  -  -  + ]:           5704 :     Assert(tmp.val.array.nElems == 1 && tmp.val.array.rawScalar);
                               1830                 :                : 
                               1831                 :           5704 :     tok = JsonbIteratorNext(&it, res, true);
 3138 tgl@sss.pgh.pa.us        1832         [ -  + ]:           5704 :     Assert(tok == WJB_ELEM);
 3166 teodor@sigaev.ru         1833   [ -  +  -  - ]:           5704 :     Assert(IsAJsonbScalar(res));
                               1834                 :                : 
                               1835                 :           5704 :     tok = JsonbIteratorNext(&it, &tmp, true);
 3138 tgl@sss.pgh.pa.us        1836         [ -  + ]:           5704 :     Assert(tok == WJB_END_ARRAY);
                               1837                 :                : 
 3166 teodor@sigaev.ru         1838                 :           5704 :     tok = JsonbIteratorNext(&it, &tmp, true);
                               1839         [ -  + ]:           5704 :     Assert(tok == WJB_DONE);
                               1840                 :                : 
 3125                          1841                 :           5704 :     return true;
                               1842                 :                : }
                               1843                 :                : 
                               1844                 :                : /*
                               1845                 :                :  * Emit correct, translatable cast error message
                               1846                 :                :  */
                               1847                 :                : static Datum
  245 peter@eisentraut.org     1848                 :             28 : cannotCastJsonbValue(enum jbvType type, const char *sqltype, Node *escontext)
                               1849                 :                : {
                               1850                 :                :     static const struct
                               1851                 :                :     {
                               1852                 :                :         enum jbvType type;
                               1853                 :                :         const char *msg;
                               1854                 :                :     }
                               1855                 :                :                 messages[] =
                               1856                 :                :     {
                               1857                 :                :         {jbvNull, gettext_noop("cannot cast jsonb null to type %s")},
                               1858                 :                :         {jbvString, gettext_noop("cannot cast jsonb string to type %s")},
                               1859                 :                :         {jbvNumeric, gettext_noop("cannot cast jsonb numeric to type %s")},
                               1860                 :                :         {jbvBool, gettext_noop("cannot cast jsonb boolean to type %s")},
                               1861                 :                :         {jbvArray, gettext_noop("cannot cast jsonb array to type %s")},
                               1862                 :                :         {jbvObject, gettext_noop("cannot cast jsonb object to type %s")},
                               1863                 :                :         {jbvBinary, gettext_noop("cannot cast jsonb array or object to type %s")}
                               1864                 :                :     };
                               1865                 :                : 
  140 peter@eisentraut.org     1866         [ +  - ]:GNC         108 :     for (size_t i = 0; i < lengthof(messages); i++)
 3125 teodor@sigaev.ru         1867         [ +  + ]:CBC         108 :         if (messages[i].type == type)
  245 peter@eisentraut.org     1868         [ +  - ]:             28 :             ereturn(escontext, (Datum) 0,
                               1869                 :                :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                               1870                 :                :                      errmsg(messages[i].msg, sqltype)));
                               1871                 :                : 
                               1872                 :                :     /* should be unreachable */
 3073 andrew@dunslane.net      1873         [ #  # ]:UBC           0 :     elog(ERROR, "unknown jsonb type: %d", (int) type);
                               1874                 :                :     return (Datum) 0;
                               1875                 :                : }
                               1876                 :                : 
                               1877                 :                : Datum
 3166 teodor@sigaev.ru         1878                 :CBC          24 : jsonb_bool(PG_FUNCTION_ARGS)
                               1879                 :                : {
                               1880                 :             24 :     Jsonb      *in = PG_GETARG_JSONB_P(0);
                               1881                 :                :     JsonbValue  v;
                               1882                 :                : 
  673 tgl@sss.pgh.pa.us        1883         [ +  + ]:             24 :     if (!JsonbExtractScalar(&in->root, &v))
  245 peter@eisentraut.org     1884                 :              4 :         return cannotCastJsonbValue(v.type, "boolean", fcinfo->context);
                               1885                 :                : 
  673 tgl@sss.pgh.pa.us        1886         [ +  + ]:             20 :     if (v.type == jbvNull)
                               1887                 :                :     {
                               1888         [ -  + ]:              5 :         PG_FREE_IF_COPY(in, 0);
                               1889                 :              5 :         PG_RETURN_NULL();
                               1890                 :                :     }
                               1891                 :                : 
                               1892         [ -  + ]:             15 :     if (v.type != jbvBool)
  245 peter@eisentraut.org     1893                 :UBC           0 :         return cannotCastJsonbValue(v.type, "boolean", fcinfo->context);
                               1894                 :                : 
 3166 teodor@sigaev.ru         1895         [ -  + ]:CBC          15 :     PG_FREE_IF_COPY(in, 0);
                               1896                 :                : 
                               1897                 :             15 :     PG_RETURN_BOOL(v.val.boolean);
                               1898                 :                : }
                               1899                 :                : 
                               1900                 :                : Datum
                               1901                 :             34 : jsonb_numeric(PG_FUNCTION_ARGS)
                               1902                 :                : {
                               1903                 :             34 :     Jsonb      *in = PG_GETARG_JSONB_P(0);
                               1904                 :                :     JsonbValue  v;
                               1905                 :                :     Numeric     retValue;
                               1906                 :                : 
  673 tgl@sss.pgh.pa.us        1907         [ +  + ]:             34 :     if (!JsonbExtractScalar(&in->root, &v))
  245 peter@eisentraut.org     1908                 :              4 :         return cannotCastJsonbValue(v.type, "numeric", fcinfo->context);
                               1909                 :                : 
  673 tgl@sss.pgh.pa.us        1910         [ +  + ]:             30 :     if (v.type == jbvNull)
                               1911                 :                :     {
                               1912         [ -  + ]:              5 :         PG_FREE_IF_COPY(in, 0);
                               1913                 :              5 :         PG_RETURN_NULL();
                               1914                 :                :     }
                               1915                 :                : 
                               1916         [ -  + ]:             25 :     if (v.type != jbvNumeric)
  245 peter@eisentraut.org     1917                 :UBC           0 :         return cannotCastJsonbValue(v.type, "numeric", fcinfo->context);
                               1918                 :                : 
                               1919                 :                :     /*
                               1920                 :                :      * v.val.numeric points into jsonb body, so we need to make a copy to
                               1921                 :                :      * return
                               1922                 :                :      */
 3166 teodor@sigaev.ru         1923                 :CBC          25 :     retValue = DatumGetNumericCopy(NumericGetDatum(v.val.numeric));
                               1924                 :                : 
                               1925         [ -  + ]:             25 :     PG_FREE_IF_COPY(in, 0);
                               1926                 :                : 
                               1927                 :             25 :     PG_RETURN_NUMERIC(retValue);
                               1928                 :                : }
                               1929                 :                : 
                               1930                 :                : Datum
                               1931                 :             24 : jsonb_int2(PG_FUNCTION_ARGS)
                               1932                 :                : {
                               1933                 :             24 :     Jsonb      *in = PG_GETARG_JSONB_P(0);
                               1934                 :                :     JsonbValue  v;
                               1935                 :                :     Datum       retValue;
                               1936                 :                : 
  673 tgl@sss.pgh.pa.us        1937         [ -  + ]:             24 :     if (!JsonbExtractScalar(&in->root, &v))
  245 peter@eisentraut.org     1938                 :UBC           0 :         return cannotCastJsonbValue(v.type, "smallint", fcinfo->context);
                               1939                 :                : 
  673 tgl@sss.pgh.pa.us        1940         [ +  + ]:CBC          24 :     if (v.type == jbvNull)
                               1941                 :                :     {
                               1942         [ -  + ]:              5 :         PG_FREE_IF_COPY(in, 0);
                               1943                 :              5 :         PG_RETURN_NULL();
                               1944                 :                :     }
                               1945                 :                : 
                               1946         [ +  + ]:             19 :     if (v.type != jbvNumeric)
  245 peter@eisentraut.org     1947                 :              4 :         return cannotCastJsonbValue(v.type, "smallint", fcinfo->context);
                               1948                 :                : 
 3166 teodor@sigaev.ru         1949                 :             15 :     retValue = DirectFunctionCall1(numeric_int2,
                               1950                 :                :                                    NumericGetDatum(v.val.numeric));
                               1951                 :                : 
                               1952         [ -  + ]:             15 :     PG_FREE_IF_COPY(in, 0);
                               1953                 :                : 
                               1954                 :             15 :     PG_RETURN_DATUM(retValue);
                               1955                 :                : }
                               1956                 :                : 
                               1957                 :                : Datum
                               1958                 :             24 : jsonb_int4(PG_FUNCTION_ARGS)
                               1959                 :                : {
                               1960                 :             24 :     Jsonb      *in = PG_GETARG_JSONB_P(0);
                               1961                 :                :     JsonbValue  v;
                               1962                 :                :     Datum       retValue;
                               1963                 :                : 
  673 tgl@sss.pgh.pa.us        1964         [ -  + ]:             24 :     if (!JsonbExtractScalar(&in->root, &v))
  245 peter@eisentraut.org     1965                 :UBC           0 :         return cannotCastJsonbValue(v.type, "integer", fcinfo->context);
                               1966                 :                : 
  673 tgl@sss.pgh.pa.us        1967         [ +  + ]:CBC          24 :     if (v.type == jbvNull)
                               1968                 :                :     {
                               1969         [ -  + ]:              5 :         PG_FREE_IF_COPY(in, 0);
                               1970                 :              5 :         PG_RETURN_NULL();
                               1971                 :                :     }
                               1972                 :                : 
                               1973         [ +  + ]:             19 :     if (v.type != jbvNumeric)
  245 peter@eisentraut.org     1974                 :              4 :         return cannotCastJsonbValue(v.type, "integer", fcinfo->context);
                               1975                 :                : 
 3166 teodor@sigaev.ru         1976                 :             15 :     retValue = DirectFunctionCall1(numeric_int4,
                               1977                 :                :                                    NumericGetDatum(v.val.numeric));
                               1978                 :                : 
                               1979         [ -  + ]:             15 :     PG_FREE_IF_COPY(in, 0);
                               1980                 :                : 
                               1981                 :             15 :     PG_RETURN_DATUM(retValue);
                               1982                 :                : }
                               1983                 :                : 
                               1984                 :                : Datum
                               1985                 :             48 : jsonb_int8(PG_FUNCTION_ARGS)
                               1986                 :                : {
                               1987                 :             48 :     Jsonb      *in = PG_GETARG_JSONB_P(0);
                               1988                 :                :     JsonbValue  v;
                               1989                 :                :     Datum       retValue;
                               1990                 :                : 
  673 tgl@sss.pgh.pa.us        1991         [ -  + ]:             48 :     if (!JsonbExtractScalar(&in->root, &v))
  245 peter@eisentraut.org     1992                 :UBC           0 :         return cannotCastJsonbValue(v.type, "bigint", fcinfo->context);
                               1993                 :                : 
  673 tgl@sss.pgh.pa.us        1994         [ +  + ]:CBC          48 :     if (v.type == jbvNull)
                               1995                 :                :     {
                               1996         [ -  + ]:              5 :         PG_FREE_IF_COPY(in, 0);
                               1997                 :              5 :         PG_RETURN_NULL();
                               1998                 :                :     }
                               1999                 :                : 
                               2000         [ +  + ]:             43 :     if (v.type != jbvNumeric)
  245 peter@eisentraut.org     2001                 :              4 :         return cannotCastJsonbValue(v.type, "bigint", fcinfo->context);
                               2002                 :                : 
 3166 teodor@sigaev.ru         2003                 :             39 :     retValue = DirectFunctionCall1(numeric_int8,
                               2004                 :                :                                    NumericGetDatum(v.val.numeric));
                               2005                 :                : 
                               2006         [ -  + ]:             39 :     PG_FREE_IF_COPY(in, 0);
                               2007                 :                : 
                               2008                 :             39 :     PG_RETURN_DATUM(retValue);
                               2009                 :                : }
                               2010                 :                : 
                               2011                 :                : Datum
                               2012                 :             24 : jsonb_float4(PG_FUNCTION_ARGS)
                               2013                 :                : {
                               2014                 :             24 :     Jsonb      *in = PG_GETARG_JSONB_P(0);
                               2015                 :                :     JsonbValue  v;
                               2016                 :                :     Datum       retValue;
                               2017                 :                : 
  673 tgl@sss.pgh.pa.us        2018         [ +  + ]:             24 :     if (!JsonbExtractScalar(&in->root, &v))
  245 peter@eisentraut.org     2019                 :              4 :         return cannotCastJsonbValue(v.type, "real", fcinfo->context);
                               2020                 :                : 
  673 tgl@sss.pgh.pa.us        2021         [ +  + ]:             20 :     if (v.type == jbvNull)
                               2022                 :                :     {
                               2023         [ -  + ]:              5 :         PG_FREE_IF_COPY(in, 0);
                               2024                 :              5 :         PG_RETURN_NULL();
                               2025                 :                :     }
                               2026                 :                : 
                               2027         [ -  + ]:             15 :     if (v.type != jbvNumeric)
  245 peter@eisentraut.org     2028                 :UBC           0 :         return cannotCastJsonbValue(v.type, "real", fcinfo->context);
                               2029                 :                : 
 3166 teodor@sigaev.ru         2030                 :CBC          15 :     retValue = DirectFunctionCall1(numeric_float4,
                               2031                 :                :                                    NumericGetDatum(v.val.numeric));
                               2032                 :                : 
                               2033         [ -  + ]:             15 :     PG_FREE_IF_COPY(in, 0);
                               2034                 :                : 
                               2035                 :             15 :     PG_RETURN_DATUM(retValue);
                               2036                 :                : }
                               2037                 :                : 
                               2038                 :                : Datum
                               2039                 :             24 : jsonb_float8(PG_FUNCTION_ARGS)
                               2040                 :                : {
                               2041                 :             24 :     Jsonb      *in = PG_GETARG_JSONB_P(0);
                               2042                 :                :     JsonbValue  v;
                               2043                 :                :     Datum       retValue;
                               2044                 :                : 
  673 tgl@sss.pgh.pa.us        2045         [ +  + ]:             24 :     if (!JsonbExtractScalar(&in->root, &v))
  245 peter@eisentraut.org     2046                 :              4 :         return cannotCastJsonbValue(v.type, "double precision", fcinfo->context);
                               2047                 :                : 
  673 tgl@sss.pgh.pa.us        2048         [ +  + ]:             20 :     if (v.type == jbvNull)
                               2049                 :                :     {
                               2050         [ -  + ]:              5 :         PG_FREE_IF_COPY(in, 0);
                               2051                 :              5 :         PG_RETURN_NULL();
                               2052                 :                :     }
                               2053                 :                : 
                               2054         [ -  + ]:             15 :     if (v.type != jbvNumeric)
  245 peter@eisentraut.org     2055                 :UBC           0 :         return cannotCastJsonbValue(v.type, "double precision", fcinfo->context);
                               2056                 :                : 
 3166 teodor@sigaev.ru         2057                 :CBC          15 :     retValue = DirectFunctionCall1(numeric_float8,
                               2058                 :                :                                    NumericGetDatum(v.val.numeric));
                               2059                 :                : 
                               2060         [ -  + ]:             15 :     PG_FREE_IF_COPY(in, 0);
                               2061                 :                : 
                               2062                 :             15 :     PG_RETURN_DATUM(retValue);
                               2063                 :                : }
                               2064                 :                : 
                               2065                 :                : /*
                               2066                 :                :  * Convert jsonb to a C-string stripping quotes from scalar strings.
                               2067                 :                :  */
                               2068                 :                : char *
  982 amitlan@postgresql.o     2069                 :            256 : JsonbUnquote(Jsonb *jb)
                               2070                 :                : {
                               2071         [ +  + ]:            256 :     if (JB_ROOT_IS_SCALAR(jb))
                               2072                 :                :     {
                               2073                 :                :         JsonbValue  v;
                               2074                 :                : 
                               2075                 :            240 :         (void) JsonbExtractScalar(&jb->root, &v);
                               2076                 :                : 
                               2077         [ +  + ]:            240 :         if (v.type == jbvString)
                               2078                 :            156 :             return pnstrdup(v.val.string.val, v.val.string.len);
                               2079         [ +  + ]:             84 :         else if (v.type == jbvBool)
                               2080         [ +  + ]:             24 :             return pstrdup(v.val.boolean ? "true" : "false");
                               2081         [ +  + ]:             60 :         else if (v.type == jbvNumeric)
                               2082                 :             52 :             return DatumGetCString(DirectFunctionCall1(numeric_out,
                               2083                 :                :                                                        PointerGetDatum(v.val.numeric)));
                               2084         [ +  - ]:              8 :         else if (v.type == jbvNull)
                               2085                 :              8 :             return pstrdup("null");
                               2086                 :                :         else
                               2087                 :                :         {
  982 amitlan@postgresql.o     2088         [ #  # ]:UBC           0 :             elog(ERROR, "unrecognized jsonb value type %d", v.type);
                               2089                 :                :             return NULL;
                               2090                 :                :         }
                               2091                 :                :     }
                               2092                 :                :     else
  982 amitlan@postgresql.o     2093                 :CBC          16 :         return JsonbToCString(NULL, &jb->root, VARSIZE(jb));
                               2094                 :                : }
        

Generated by: LCOV version 2.0-1