LCOV - differential code coverage report
Current view: top level - src/backend/utils/adt - json.c (source / functions) Coverage Total Hit UBC GNC CBC DCB
Current: 4b3c9325757dfd8f2312e9f1a8decf4431f344ae vs e87b024bfb8dd55e3049b1b6e6ab4e810cf1abc8 Lines: 92.8 % 693 643 50 1 642 1
Current Date: 2026-11-28 16:48:44 +0900 Functions: 94.1 % 51 48 3 1 47
Baseline: lcov-20261128-baseline Branches: 78.9 % 393 310 83 2 308
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: 27.8 % 18 5 13 5
(30,360] days: 100.0 % 5 5 1 4
(360..) days: 94.5 % 670 633 37 633
Function coverage date bins:
(360..) days: 94.1 % 51 48 3 1 47
Branch coverage date bins:
(7,30] days: 30.0 % 10 3 7 3
(30,360] days: 100.0 % 2 2 2
(360..) days: 80.1 % 381 305 76 305

 Age         Owner                    Branch data    TLA  Line data    Source code
                                  1                 :                : /*-------------------------------------------------------------------------
                                  2                 :                :  *
                                  3                 :                :  * json.c
                                  4                 :                :  *      JSON data type support.
                                  5                 :                :  *
                                  6                 :                :  * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
                                  7                 :                :  * Portions Copyright (c) 1994, Regents of the University of California
                                  8                 :                :  *
                                  9                 :                :  * IDENTIFICATION
                                 10                 :                :  *    src/backend/utils/adt/json.c
                                 11                 :                :  *
                                 12                 :                :  *-------------------------------------------------------------------------
                                 13                 :                :  */
                                 14                 :                : #include "postgres.h"
                                 15                 :                : 
                                 16                 :                : #include "access/htup_details.h"
                                 17                 :                : #include "catalog/objectaccess.h"
                                 18                 :                : #include "catalog/pg_proc.h"
                                 19                 :                : #include "catalog/pg_type.h"
                                 20                 :                : #include "common/hashfn.h"
                                 21                 :                : #include "funcapi.h"
                                 22                 :                : #include "libpq/pqformat.h"
                                 23                 :                : #include "miscadmin.h"
                                 24                 :                : #include "port/simd.h"
                                 25                 :                : #include "utils/acl.h"
                                 26                 :                : #include "utils/array.h"
                                 27                 :                : #include "utils/builtins.h"
                                 28                 :                : #include "utils/date.h"
                                 29                 :                : #include "utils/datetime.h"
                                 30                 :                : #include "utils/fmgroids.h"
                                 31                 :                : #include "utils/hsearch.h"
                                 32                 :                : #include "utils/json.h"
                                 33                 :                : #include "utils/jsonfuncs.h"
                                 34                 :                : #include "utils/lsyscache.h"
                                 35                 :                : #include "utils/typcache.h"
                                 36                 :                : 
                                 37                 :                : 
                                 38                 :                : /*
                                 39                 :                :  * Support for fast key uniqueness checking.
                                 40                 :                :  *
                                 41                 :                :  * We maintain a hash table of used keys in JSON objects for fast detection
                                 42                 :                :  * of duplicates.
                                 43                 :                :  */
                                 44                 :                : /* Common context for key uniqueness check */
                                 45                 :                : typedef struct HTAB *JsonUniqueCheckState;  /* hash table for key names */
                                 46                 :                : 
                                 47                 :                : /* Hash entry for JsonUniqueCheckState */
                                 48                 :                : typedef struct JsonUniqueHashEntry
                                 49                 :                : {
                                 50                 :                :     const char *key;
                                 51                 :                :     int         key_len;
                                 52                 :                :     int         object_id;
                                 53                 :                : } JsonUniqueHashEntry;
                                 54                 :                : 
                                 55                 :                : /* Stack element for key uniqueness check during JSON parsing */
                                 56                 :                : typedef struct JsonUniqueStackEntry
                                 57                 :                : {
                                 58                 :                :     struct JsonUniqueStackEntry *parent;
                                 59                 :                :     int         object_id;
                                 60                 :                : } JsonUniqueStackEntry;
                                 61                 :                : 
                                 62                 :                : /* Context struct for key uniqueness check during JSON parsing */
                                 63                 :                : typedef struct JsonUniqueParsingState
                                 64                 :                : {
                                 65                 :                :     JsonLexContext *lex;
                                 66                 :                :     JsonUniqueCheckState check;
                                 67                 :                :     JsonUniqueStackEntry *stack;
                                 68                 :                :     int         id_counter;
                                 69                 :                :     bool        unique;
                                 70                 :                : } JsonUniqueParsingState;
                                 71                 :                : 
                                 72                 :                : /* Context struct for key uniqueness check during JSON building */
                                 73                 :                : typedef struct JsonUniqueBuilderState
                                 74                 :                : {
                                 75                 :                :     JsonUniqueCheckState check; /* unique check */
                                 76                 :                :     StringInfoData skipped_keys;    /* skipped keys with NULL values */
                                 77                 :                :     MemoryContext mcxt;         /* context for saving skipped keys */
                                 78                 :                : } JsonUniqueBuilderState;
                                 79                 :                : 
                                 80                 :                : 
                                 81                 :                : /* State struct for JSON aggregation */
                                 82                 :                : typedef struct JsonAggState
                                 83                 :                : {
                                 84                 :                :     StringInfo  str;
                                 85                 :                :     JsonTypeCategory key_category;
                                 86                 :                :     Oid         key_output_func;
                                 87                 :                :     JsonTypeCategory val_category;
                                 88                 :                :     Oid         val_output_func;
                                 89                 :                :     JsonUniqueBuilderState unique_check;
                                 90                 :                : } JsonAggState;
                                 91                 :                : 
                                 92                 :                : static void array_dim_to_json(StringInfo result, int dim, int ndims, int *dims,
                                 93                 :                :                               const Datum *vals, const bool *nulls, int *valcount,
                                 94                 :                :                               JsonTypeCategory tcategory, Oid outfuncoid,
                                 95                 :                :                               bool use_line_feeds);
                                 96                 :                : static void array_to_json_internal(Datum array, StringInfo result,
                                 97                 :                :                                    bool use_line_feeds);
                                 98                 :                : static void datum_to_json_internal(Datum val, bool is_null, StringInfo result,
                                 99                 :                :                                    JsonTypeCategory tcategory, Oid outfuncoid,
                                100                 :                :                                    bool key_scalar);
                                101                 :                : static void add_json(Datum val, bool is_null, StringInfo result,
                                102                 :                :                      Oid val_type, bool key_scalar);
                                103                 :                : static text *catenate_stringinfo_string(StringInfo buffer, const char *addon);
                                104                 :                : 
                                105                 :                : /*
                                106                 :                :  * Input.
                                107                 :                :  */
                                108                 :                : Datum
 5415 rhaas@postgresql.org      109                 :CBC        4442 : json_in(PG_FUNCTION_ARGS)
                                110                 :                : {
 4992 andrew@dunslane.net       111                 :           4442 :     char       *json = PG_GETARG_CSTRING(0);
                                112                 :           4442 :     text       *result = cstring_to_text(json);
                                113                 :                :     JsonLexContext lex;
                                114                 :                : 
                                115                 :                :     /* validate it */
 1150 alvherre@alvh.no-ip.      116                 :           4442 :     makeJsonLexContext(&lex, result, false);
                                117         [ +  + ]:           4442 :     if (!pg_parse_json_or_errsave(&lex, &nullSemAction, fcinfo->context))
 1448 tgl@sss.pgh.pa.us         118                 :              8 :         PG_RETURN_NULL();
                                119                 :                : 
                                120                 :                :     /* Internal representation is the same as text */
 4992 andrew@dunslane.net       121                 :           4302 :     PG_RETURN_TEXT_P(result);
                                122                 :                : }
                                123                 :                : 
                                124                 :                : /*
                                125                 :                :  * Output.
                                126                 :                :  */
                                127                 :                : Datum
 5415 rhaas@postgresql.org      128                 :           4023 : json_out(PG_FUNCTION_ARGS)
                                129                 :                : {
                                130                 :                :     /* we needn't detoast because text_to_cstring will handle that */
 5284 bruce@momjian.us          131                 :           4023 :     Datum       txt = PG_GETARG_DATUM(0);
                                132                 :                : 
 5415 rhaas@postgresql.org      133                 :           4023 :     PG_RETURN_CSTRING(TextDatumGetCString(txt));
                                134                 :                : }
                                135                 :                : 
                                136                 :                : /*
                                137                 :                :  * Binary send.
                                138                 :                :  */
                                139                 :                : Datum
 5415 rhaas@postgresql.org      140                 :UBC           0 : json_send(PG_FUNCTION_ARGS)
                                141                 :                : {
 5284 bruce@momjian.us          142                 :              0 :     text       *t = PG_GETARG_TEXT_PP(0);
                                143                 :                :     StringInfoData buf;
                                144                 :                : 
 5415 rhaas@postgresql.org      145                 :              0 :     pq_begintypsend(&buf);
                                146                 :              0 :     pq_sendtext(&buf, VARDATA_ANY(t), VARSIZE_ANY_EXHDR(t));
                                147                 :              0 :     PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
                                148                 :                : }
                                149                 :                : 
                                150                 :                : /*
                                151                 :                :  * Binary receive.
                                152                 :                :  */
                                153                 :                : Datum
                                154                 :              0 : json_recv(PG_FUNCTION_ARGS)
                                155                 :                : {
                                156                 :              0 :     StringInfo  buf = (StringInfo) PG_GETARG_POINTER(0);
                                157                 :                :     char       *str;
                                158                 :                :     int         nbytes;
                                159                 :                :     JsonLexContext lex;
                                160                 :                : 
                                161                 :              0 :     str = pq_getmsgtext(buf, buf->len - buf->cursor, &nbytes);
                                162                 :                : 
                                163                 :                :     /* Validate it. */
 1150 alvherre@alvh.no-ip.      164                 :              0 :     makeJsonLexContextCstringLen(&lex, str, nbytes, GetDatabaseEncoding(),
                                165                 :                :                                  false);
                                166                 :              0 :     pg_parse_json_or_ereport(&lex, &nullSemAction);
                                167                 :                : 
 4633 andrew@dunslane.net       168                 :              0 :     PG_RETURN_TEXT_P(cstring_to_text_with_len(str, nbytes));
                                169                 :                : }
                                170                 :                : 
                                171                 :                : /*
                                172                 :                :  * Turn a Datum into JSON text, appending the string to "result".
                                173                 :                :  *
                                174                 :                :  * tcategory and outfuncoid are from a previous call to json_categorize_type,
                                175                 :                :  * except that if is_null is true then they can be invalid.
                                176                 :                :  *
                                177                 :                :  * If key_scalar is true, the value is being printed as a key, so insist
                                178                 :                :  * it's of an acceptable type, and force it to be quoted.
                                179                 :                :  */
                                180                 :                : static void
 1226 amitlan@postgresql.o      181                 :CBC        6839 : datum_to_json_internal(Datum val, bool is_null, StringInfo result,
                                182                 :                :                        JsonTypeCategory tcategory, Oid outfuncoid,
                                183                 :                :                        bool key_scalar)
                                184                 :                : {
                                185                 :                :     char       *outputstr;
                                186                 :                :     text       *jsontext;
                                187                 :                :     AclResult   aclresult;
                                188                 :                : 
 4072 noah@leadboat.com         189                 :           6839 :     check_stack_depth();
                                190                 :                : 
                                191                 :                :     /* callers are expected to ensure that null keys are not passed in */
 4379 tgl@sss.pgh.pa.us         192   [ +  +  -  + ]:           6839 :     Assert(!(key_scalar && is_null));
                                193                 :                : 
 5392 andrew@dunslane.net       194         [ +  + ]:           6839 :     if (is_null)
                                195                 :                :     {
 1076 nathan@postgresql.or      196                 :            326 :         appendBinaryStringInfo(result, "null", strlen("null"));
 5412 andrew@dunslane.net       197                 :            326 :         return;
                                198                 :                :     }
                                199                 :                : 
 4586 tgl@sss.pgh.pa.us         200   [ +  +  +  + ]:           6513 :     if (key_scalar &&
                                201         [ +  + ]:           1467 :         (tcategory == JSONTYPE_ARRAY ||
                                202         [ +  + ]:           1463 :          tcategory == JSONTYPE_COMPOSITE ||
                                203         [ -  + ]:           1455 :          tcategory == JSONTYPE_JSON ||
                                204                 :                :          tcategory == JSONTYPE_CAST))
                                205         [ +  - ]:             24 :         ereport(ERROR,
                                206                 :                :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                                207                 :                :                  errmsg("key value must be scalar, not array, composite, or json")));
                                208                 :                : 
 5412 andrew@dunslane.net       209   [ +  +  +  +  :           6489 :     switch (tcategory)
                                     +  +  +  +  +  
                                                 + ]
                                210                 :                :     {
 4586 tgl@sss.pgh.pa.us         211                 :            240 :         case JSONTYPE_ARRAY:
 5412 andrew@dunslane.net       212                 :            240 :             array_to_json_internal(val, result, false);
                                213                 :            240 :             break;
 4586 tgl@sss.pgh.pa.us         214                 :            332 :         case JSONTYPE_COMPOSITE:
 4443 sfrost@snowman.net        215                 :            332 :             composite_to_json(val, result, false);
 5412 andrew@dunslane.net       216                 :            332 :             break;
 4586 tgl@sss.pgh.pa.us         217                 :             41 :         case JSONTYPE_BOOL:
                                218         [ -  + ]:             41 :             if (key_scalar)
 1076 nathan@postgresql.or      219                 :UBC           0 :                 appendStringInfoChar(result, '"');
 1076 nathan@postgresql.or      220         [ +  + ]:CBC          41 :             if (DatumGetBool(val))
                                221                 :             25 :                 appendBinaryStringInfo(result, "true", strlen("true"));
                                222                 :                :             else
                                223                 :             16 :                 appendBinaryStringInfo(result, "false", strlen("false"));
                                224         [ -  + ]:             41 :             if (key_scalar)
 1076 nathan@postgresql.or      225                 :UBC           0 :                 appendStringInfoChar(result, '"');
 5412 andrew@dunslane.net       226                 :CBC          41 :             break;
 4586 tgl@sss.pgh.pa.us         227                 :           3933 :         case JSONTYPE_NUMERIC:
                                228                 :           3933 :             outputstr = OidOutputFunctionCall(outfuncoid, val);
                                229                 :                : 
                                230                 :                :             /*
                                231                 :                :              * Don't quote a non-key if it's a valid JSON number (i.e., not
                                232                 :                :              * "Infinity", "-Infinity", or "NaN").  Since we know this is a
                                233                 :                :              * numeric data type's output, we simplify and open-code the
                                234                 :                :              * validation for better performance.
                                235                 :                :              */
 1086 nathan@postgresql.or      236         [ +  + ]:           3933 :             if (!key_scalar &&
                                237   [ +  +  +  + ]:           2850 :                 ((*outputstr >= '0' && *outputstr <= '9') ||
                                238         [ +  + ]:             52 :                  (*outputstr == '-' &&
                                239   [ +  -  +  + ]:             44 :                   (outputstr[1] >= '0' && outputstr[1] <= '9'))))
 4380 andrew@dunslane.net       240                 :           2838 :                 appendStringInfoString(result, outputstr);
                                241                 :                :             else
                                242                 :                :             {
 1086 nathan@postgresql.or      243                 :           1095 :                 appendStringInfoChar(result, '"');
                                244                 :           1095 :                 appendStringInfoString(result, outputstr);
                                245                 :           1095 :                 appendStringInfoChar(result, '"');
                                246                 :                :             }
 5395 andrew@dunslane.net       247                 :           3933 :             pfree(outputstr);
                                248                 :           3933 :             break;
 4486 tgl@sss.pgh.pa.us         249                 :             16 :         case JSONTYPE_DATE:
                                250                 :                :             {
                                251                 :                :                 char        buf[MAXDATELEN + 1];
                                252                 :                : 
 2621 akorotkov@postgresql      253                 :             16 :                 JsonEncodeDateTime(buf, val, DATEOID, NULL);
 1086 nathan@postgresql.or      254                 :             16 :                 appendStringInfoChar(result, '"');
                                255                 :             16 :                 appendStringInfoString(result, buf);
                                256                 :             16 :                 appendStringInfoChar(result, '"');
                                257                 :                :             }
 3238 andrew@dunslane.net       258                 :             16 :             break;
                                259                 :             34 :         case JSONTYPE_TIMESTAMP:
                                260                 :                :             {
                                261                 :                :                 char        buf[MAXDATELEN + 1];
                                262                 :                : 
 2621 akorotkov@postgresql      263                 :             34 :                 JsonEncodeDateTime(buf, val, TIMESTAMPOID, NULL);
 1086 nathan@postgresql.or      264                 :             34 :                 appendStringInfoChar(result, '"');
                                265                 :             34 :                 appendStringInfoString(result, buf);
                                266                 :             34 :                 appendStringInfoChar(result, '"');
                                267                 :                :             }
 3238 andrew@dunslane.net       268                 :             34 :             break;
                                269                 :             43 :         case JSONTYPE_TIMESTAMPTZ:
                                270                 :                :             {
                                271                 :                :                 char        buf[MAXDATELEN + 1];
                                272                 :                : 
 2621 akorotkov@postgresql      273                 :             43 :                 JsonEncodeDateTime(buf, val, TIMESTAMPTZOID, NULL);
 1086 nathan@postgresql.or      274                 :             43 :                 appendStringInfoChar(result, '"');
                                275                 :             43 :                 appendStringInfoString(result, buf);
                                276                 :             43 :                 appendStringInfoChar(result, '"');
                                277                 :                :             }
 3238 andrew@dunslane.net       278                 :             43 :             break;
                                279                 :            631 :         case JSONTYPE_JSON:
                                280                 :                :             /* JSON and JSONB output will already be escaped */
                                281                 :            631 :             outputstr = OidOutputFunctionCall(outfuncoid, val);
                                282                 :            631 :             appendStringInfoString(result, outputstr);
                                283                 :            631 :             pfree(outputstr);
                                284                 :            631 :             break;
                                285                 :             10 :         case JSONTYPE_CAST:
                                286                 :                :             /* outfuncoid refers to a cast function, not an output function */
   19 nathan@postgresql.or      287                 :             10 :             aclresult = object_aclcheck(ProcedureRelationId, outfuncoid,
                                288                 :                :                                         GetUserId(), ACL_EXECUTE);
                                289         [ +  + ]:             10 :             if (aclresult != ACLCHECK_OK)
                                290                 :              4 :                 aclcheck_error(aclresult, OBJECT_FUNCTION,
                                291                 :              4 :                                get_func_name(outfuncoid));
                                292         [ -  + ]:              6 :             InvokeFunctionExecuteHook(outfuncoid);
 3238 andrew@dunslane.net       293                 :              6 :             jsontext = DatumGetTextPP(OidFunctionCall1(outfuncoid, val));
 1076 nathan@postgresql.or      294                 :              6 :             appendBinaryStringInfo(result, VARDATA_ANY(jsontext),
                                295                 :              6 :                                    VARSIZE_ANY_EXHDR(jsontext));
 3238 andrew@dunslane.net       296                 :              6 :             pfree(jsontext);
                                297                 :              6 :             break;
                                298                 :           1209 :         default:
                                299                 :                :             /* special-case text types to save useless palloc/memcpy cycles */
  854 drowley@postgresql.o      300   [ +  +  +  +  :           1209 :             if (outfuncoid == F_TEXTOUT || outfuncoid == F_VARCHAROUT ||
                                              +  + ]
                                301                 :                :                 outfuncoid == F_BPCHAROUT)
                                302                 :            977 :                 escape_json_text(result, (text *) DatumGetPointer(val));
                                303                 :                :             else
                                304                 :                :             {
                                305                 :            232 :                 outputstr = OidOutputFunctionCall(outfuncoid, val);
                                306                 :            232 :                 escape_json(result, outputstr);
                                307                 :            232 :                 pfree(outputstr);
                                308                 :                :             }
 3238 andrew@dunslane.net       309                 :           1209 :             break;
                                310                 :                :     }
                                311                 :                : }
                                312                 :                : 
                                313                 :                : /*
                                314                 :                :  * Encode 'value' of datetime type 'typid' into JSON string in ISO format using
                                315                 :                :  * optionally preallocated buffer 'buf'.  Optional 'tzp' determines time-zone
                                316                 :                :  * offset (in seconds) in which we want to show timestamptz.
                                317                 :                :  */
                                318                 :                : char *
 2621 akorotkov@postgresql      319                 :           1277 : JsonEncodeDateTime(char *buf, Datum value, Oid typid, const int *tzp)
                                320                 :                : {
 3238 andrew@dunslane.net       321         [ +  + ]:           1277 :     if (!buf)
                                322                 :             40 :         buf = palloc(MAXDATELEN + 1);
                                323                 :                : 
                                324   [ +  +  +  +  :           1277 :     switch (typid)
                                              +  - ]
                                325                 :                :     {
                                326                 :            160 :         case DATEOID:
                                327                 :                :             {
                                328                 :                :                 DateADT     date;
                                329                 :                :                 struct pg_tm tm;
                                330                 :                : 
                                331                 :            160 :                 date = DatumGetDateADT(value);
                                332                 :                : 
                                333                 :                :                 /* Same as date_out(), but forcing DateStyle */
 4486 tgl@sss.pgh.pa.us         334   [ +  +  +  + ]:            160 :                 if (DATE_NOT_FINITE(date))
 4057                           335                 :             16 :                     EncodeSpecialDate(date, buf);
                                336                 :                :                 else
                                337                 :                :                 {
 4486                           338                 :            144 :                     j2date(date + POSTGRES_EPOCH_JDATE,
                                339                 :                :                            &(tm.tm_year), &(tm.tm_mon), &(tm.tm_mday));
                                340                 :            144 :                     EncodeDateOnly(&tm, USE_XSD_DATES, buf);
                                341                 :                :                 }
                                342                 :                :             }
                                343                 :            160 :             break;
 3238 andrew@dunslane.net       344                 :            260 :         case TIMEOID:
                                345                 :                :             {
                                346                 :            260 :                 TimeADT     time = DatumGetTimeADT(value);
                                347                 :                :                 struct pg_tm tt,
                                348                 :            260 :                            *tm = &tt;
                                349                 :                :                 fsec_t      fsec;
                                350                 :                : 
                                351                 :                :                 /* Same as time_out(), but forcing DateStyle */
                                352                 :            260 :                 time2tm(time, tm, &fsec);
                                353                 :            260 :                 EncodeTimeOnly(tm, fsec, false, 0, USE_XSD_DATES, buf);
                                354                 :                :             }
                                355                 :            260 :             break;
                                356                 :            228 :         case TIMETZOID:
                                357                 :                :             {
                                358                 :            228 :                 TimeTzADT  *time = DatumGetTimeTzADTP(value);
                                359                 :                :                 struct pg_tm tt,
                                360                 :            228 :                            *tm = &tt;
                                361                 :                :                 fsec_t      fsec;
                                362                 :                :                 int         tz;
                                363                 :                : 
                                364                 :                :                 /* Same as timetz_out(), but forcing DateStyle */
                                365                 :            228 :                 timetz2tm(time, tm, &fsec, &tz);
                                366                 :            228 :                 EncodeTimeOnly(tm, fsec, true, tz, USE_XSD_DATES, buf);
                                367                 :                :             }
                                368                 :            228 :             break;
                                369                 :            262 :         case TIMESTAMPOID:
                                370                 :                :             {
                                371                 :                :                 Timestamp   timestamp;
                                372                 :                :                 struct pg_tm tm;
                                373                 :                :                 fsec_t      fsec;
                                374                 :                : 
                                375                 :            262 :                 timestamp = DatumGetTimestamp(value);
                                376                 :                :                 /* Same as timestamp_out(), but forcing DateStyle */
 4561                           377   [ +  +  +  + ]:            262 :                 if (TIMESTAMP_NOT_FINITE(timestamp))
 4057 tgl@sss.pgh.pa.us         378                 :             16 :                     EncodeSpecialTimestamp(timestamp, buf);
 4561 andrew@dunslane.net       379         [ +  - ]:            246 :                 else if (timestamp2tm(timestamp, NULL, &tm, &fsec, NULL, NULL) == 0)
                                380                 :            246 :                     EncodeDateTime(&tm, fsec, false, 0, NULL, USE_XSD_DATES, buf);
                                381                 :                :                 else
 4561 andrew@dunslane.net       382         [ #  # ]:UBC           0 :                     ereport(ERROR,
                                383                 :                :                             (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
                                384                 :                :                              errmsg("timestamp out of range")));
                                385                 :                :             }
 4561 andrew@dunslane.net       386                 :CBC         262 :             break;
 3238                           387                 :            367 :         case TIMESTAMPTZOID:
                                388                 :                :             {
                                389                 :                :                 TimestampTz timestamp;
                                390                 :                :                 struct pg_tm tm;
                                391                 :                :                 int         tz;
                                392                 :                :                 fsec_t      fsec;
 4561                           393                 :            367 :                 const char *tzn = NULL;
                                394                 :                : 
 3238                           395                 :            367 :                 timestamp = DatumGetTimestampTz(value);
                                396                 :                : 
                                397                 :                :                 /*
                                398                 :                :                  * If a time zone is specified, we apply the time-zone shift,
                                399                 :                :                  * convert timestamptz to pg_tm as if it were without a time
                                400                 :                :                  * zone, and then use the specified time zone for converting
                                401                 :                :                  * the timestamp into a string.
                                402                 :                :                  */
 2621 akorotkov@postgresql      403         [ +  + ]:            367 :                 if (tzp)
                                404                 :                :                 {
                                405                 :            308 :                     tz = *tzp;
                                406                 :            308 :                     timestamp -= (TimestampTz) tz * USECS_PER_SEC;
                                407                 :                :                 }
                                408                 :                : 
                                409                 :                :                 /* Same as timestamptz_out(), but forcing DateStyle */
 4561 andrew@dunslane.net       410   [ +  +  +  + ]:            367 :                 if (TIMESTAMP_NOT_FINITE(timestamp))
 4057 tgl@sss.pgh.pa.us         411                 :             16 :                     EncodeSpecialTimestamp(timestamp, buf);
 2621 akorotkov@postgresql      412   [ +  +  +  +  :            351 :                 else if (timestamp2tm(timestamp, tzp ? NULL : &tz, &tm, &fsec,
                                              +  - ]
                                413                 :                :                                       tzp ? NULL : &tzn, NULL) == 0)
                                414                 :                :                 {
                                415         [ +  + ]:            351 :                     if (tzp)
                                416                 :            308 :                         tm.tm_isdst = 1;    /* set time-zone presence flag */
                                417                 :                : 
 4561 andrew@dunslane.net       418                 :            351 :                     EncodeDateTime(&tm, fsec, true, tz, tzn, USE_XSD_DATES, buf);
                                419                 :                :                 }
                                420                 :                :                 else
 4561 andrew@dunslane.net       421         [ #  # ]:UBC           0 :                     ereport(ERROR,
                                422                 :                :                             (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
                                423                 :                :                              errmsg("timestamp out of range")));
                                424                 :                :             }
 4561 andrew@dunslane.net       425                 :CBC         367 :             break;
 5412 andrew@dunslane.net       426                 :UBC           0 :         default:
 2313 michael@paquier.xyz       427         [ #  # ]:              0 :             elog(ERROR, "unknown jsonb value datetime type oid %u", typid);
                                428                 :                :             return NULL;
                                429                 :                :     }
                                430                 :                : 
 3238 andrew@dunslane.net       431                 :CBC        1277 :     return buf;
                                432                 :                : }
                                433                 :                : 
                                434                 :                : /*
                                435                 :                :  * Process a single dimension of an array.
                                436                 :                :  * If it's the innermost dimension, output the values, otherwise call
                                437                 :                :  * ourselves recursively to process the next dimension.
                                438                 :                :  */
                                439                 :                : static void
  393 peter@eisentraut.org      440                 :            268 : array_dim_to_json(StringInfo result, int dim, int ndims, int *dims, const Datum *vals,
                                441                 :                :                   const bool *nulls, int *valcount, JsonTypeCategory tcategory,
                                442                 :                :                   Oid outfuncoid, bool use_line_feeds)
                                443                 :                : {
                                444                 :                :     int         i;
                                445                 :                :     const char *sep;
                                446                 :                : 
 5412 andrew@dunslane.net       447         [ -  + ]:            268 :     Assert(dim < ndims);
                                448                 :                : 
                                449         [ +  + ]:            268 :     sep = use_line_feeds ? ",\n " : ",";
                                450                 :                : 
                                451                 :            268 :     appendStringInfoChar(result, '[');
                                452                 :                : 
                                453         [ +  + ]:            996 :     for (i = 1; i <= dims[dim]; i++)
                                454                 :                :     {
                                455         [ +  + ]:            728 :         if (i > 1)
 5284 bruce@momjian.us          456                 :            460 :             appendStringInfoString(result, sep);
                                457                 :                : 
 5412 andrew@dunslane.net       458         [ +  + ]:            728 :         if (dim + 1 == ndims)
                                459                 :                :         {
 1226 amitlan@postgresql.o      460                 :            720 :             datum_to_json_internal(vals[*valcount], nulls[*valcount],
                                461                 :                :                                    result, tcategory,
                                462                 :                :                                    outfuncoid, false);
 5412 andrew@dunslane.net       463                 :            720 :             (*valcount)++;
                                464                 :                :         }
                                465                 :                :         else
                                466                 :                :         {
                                467                 :                :             /*
                                468                 :                :              * Do we want line feeds on inner dimensions of arrays? For now
                                469                 :                :              * we'll say no.
                                470                 :                :              */
 5284 bruce@momjian.us          471                 :              8 :             array_dim_to_json(result, dim + 1, ndims, dims, vals, nulls,
                                472                 :                :                               valcount, tcategory, outfuncoid, false);
                                473                 :                :         }
                                474                 :                :     }
                                475                 :                : 
 5412 andrew@dunslane.net       476                 :            268 :     appendStringInfoChar(result, ']');
                                477                 :            268 : }
                                478                 :                : 
                                479                 :                : /*
                                480                 :                :  * Turn an array into JSON.
                                481                 :                :  */
                                482                 :                : static void
                                483                 :            268 : array_to_json_internal(Datum array, StringInfo result, bool use_line_feeds)
                                484                 :                : {
                                485                 :            268 :     ArrayType  *v = DatumGetArrayTypeP(array);
                                486                 :            268 :     Oid         element_type = ARR_ELEMTYPE(v);
                                487                 :                :     int        *dim;
                                488                 :                :     int         ndim;
                                489                 :                :     int         nitems;
 5284 bruce@momjian.us          490                 :            268 :     int         count = 0;
                                491                 :                :     Datum      *elements;
                                492                 :                :     bool       *nulls;
                                493                 :                :     int16       typlen;
                                494                 :                :     bool        typbyval;
                                495                 :                :     char        typalign;
                                496                 :                :     JsonTypeCategory tcategory;
                                497                 :                :     Oid         outfuncoid;
                                498                 :                : 
 5412 andrew@dunslane.net       499                 :            268 :     ndim = ARR_NDIM(v);
                                500                 :            268 :     dim = ARR_DIMS(v);
                                501                 :            268 :     nitems = ArrayGetNItems(ndim, dim);
                                502                 :                : 
                                503         [ +  + ]:            268 :     if (nitems <= 0)
                                504                 :                :     {
 5284 bruce@momjian.us          505                 :              8 :         appendStringInfoString(result, "[]");
 5412 andrew@dunslane.net       506                 :              8 :         return;
                                507                 :                :     }
                                508                 :                : 
 4586 tgl@sss.pgh.pa.us         509                 :            260 :     get_typlenbyvalalign(element_type,
                                510                 :                :                          &typlen, &typbyval, &typalign);
                                511                 :                : 
 1227 amitlan@postgresql.o      512                 :            260 :     json_categorize_type(element_type, false,
                                513                 :                :                          &tcategory, &outfuncoid);
                                514                 :                : 
 5412 andrew@dunslane.net       515                 :            260 :     deconstruct_array(v, element_type, typlen, typbyval,
                                516                 :                :                       typalign, &elements, &nulls,
                                517                 :                :                       &nitems);
                                518                 :                : 
 5392                           519                 :            260 :     array_dim_to_json(result, 0, ndim, dim, elements, nulls, &count, tcategory,
                                520                 :                :                       outfuncoid, use_line_feeds);
                                521                 :                : 
 5412                           522                 :            260 :     pfree(elements);
                                523                 :            260 :     pfree(nulls);
                                524                 :                : }
                                525                 :                : 
                                526                 :                : /*
                                527                 :                :  * Turn a composite / record into JSON.
                                528                 :                :  * Exported so COPY TO can use it.
                                529                 :                :  */
                                530                 :                : void
 4443 sfrost@snowman.net        531                 :           1192 : composite_to_json(Datum composite, StringInfo result, bool use_line_feeds)
                                532                 :                : {
                                533                 :                :     HeapTupleHeader td;
                                534                 :                :     Oid         tupType;
                                535                 :                :     int32       tupTypmod;
                                536                 :                :     TupleDesc   tupdesc;
                                537                 :                :     HeapTupleData tmptup,
                                538                 :                :                *tuple;
                                539                 :                :     int         i;
 5284 bruce@momjian.us          540                 :           1192 :     bool        needsep = false;
                                541                 :                :     const char *sep;
                                542                 :                :     int         seplen;
                                543                 :                : 
                                544                 :                :     /*
                                545                 :                :      * We can avoid expensive strlen() calls by precalculating the separator
                                546                 :                :      * length.
                                547                 :                :      */
 5412 andrew@dunslane.net       548         [ +  + ]:           1192 :     sep = use_line_feeds ? ",\n " : ",";
 1086 nathan@postgresql.or      549         [ +  + ]:           1192 :     seplen = use_line_feeds ? strlen(",\n ") : strlen(",");
                                550                 :                : 
 5284 bruce@momjian.us          551                 :           1192 :     td = DatumGetHeapTupleHeader(composite);
                                552                 :                : 
                                553                 :                :     /* Extract rowtype info and find a tupdesc */
                                554                 :           1192 :     tupType = HeapTupleHeaderGetTypeId(td);
                                555                 :           1192 :     tupTypmod = HeapTupleHeaderGetTypMod(td);
                                556                 :           1192 :     tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
                                557                 :                : 
                                558                 :                :     /* Build a temporary HeapTuple control structure */
                                559                 :           1192 :     tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
                                560                 :           1192 :     tmptup.t_data = td;
 5412 andrew@dunslane.net       561                 :           1192 :     tuple = &tmptup;
                                562                 :                : 
 5284 bruce@momjian.us          563                 :           1192 :     appendStringInfoChar(result, '{');
                                564                 :                : 
                                565         [ +  + ]:           3725 :     for (i = 0; i < tupdesc->natts; i++)
                                566                 :                :     {
                                567                 :                :         Datum       val;
                                568                 :                :         bool        isnull;
                                569                 :                :         char       *attname;
                                570                 :                :         JsonTypeCategory tcategory;
                                571                 :                :         Oid         outfuncoid;
 3387 andres@anarazel.de        572                 :           2533 :         Form_pg_attribute att = TupleDescAttr(tupdesc, i);
                                573                 :                : 
                                574         [ -  + ]:           2533 :         if (att->attisdropped)
 5284 bruce@momjian.us          575                 :UBC           0 :             continue;
                                576                 :                : 
 5412 andrew@dunslane.net       577         [ +  + ]:CBC        2533 :         if (needsep)
 1086 nathan@postgresql.or      578                 :           1341 :             appendBinaryStringInfo(result, sep, seplen);
 5412 andrew@dunslane.net       579                 :           2533 :         needsep = true;
                                580                 :                : 
 3387 andres@anarazel.de        581                 :           2533 :         attname = NameStr(att->attname);
 5284 bruce@momjian.us          582                 :           2533 :         escape_json(result, attname);
                                583                 :           2533 :         appendStringInfoChar(result, ':');
                                584                 :                : 
 4443 sfrost@snowman.net        585                 :           2533 :         val = heap_getattr(tuple, i + 1, tupdesc, &isnull);
                                586                 :                : 
 4586 tgl@sss.pgh.pa.us         587         [ +  + ]:           2533 :         if (isnull)
                                588                 :                :         {
                                589                 :            190 :             tcategory = JSONTYPE_NULL;
                                590                 :            190 :             outfuncoid = InvalidOid;
                                591                 :                :         }
                                592                 :                :         else
 1227 amitlan@postgresql.o      593                 :           2343 :             json_categorize_type(att->atttypid, false, &tcategory,
                                594                 :                :                                  &outfuncoid);
                                595                 :                : 
 1226                           596                 :           2533 :         datum_to_json_internal(val, isnull, result, tcategory, outfuncoid,
                                597                 :                :                                false);
                                598                 :                :     }
                                599                 :                : 
 5284 bruce@momjian.us          600                 :           1192 :     appendStringInfoChar(result, '}');
                                601         [ +  - ]:           1192 :     ReleaseTupleDesc(tupdesc);
 5412 andrew@dunslane.net       602                 :           1192 : }
                                603                 :                : 
                                604                 :                : /*
                                605                 :                :  * Append JSON text for "val" to "result".
                                606                 :                :  *
                                607                 :                :  * This is just a thin wrapper around datum_to_json.  If the same type will be
                                608                 :                :  * printed many times, avoid using this; better to do the json_categorize_type
                                609                 :                :  * lookups only once.
                                610                 :                :  */
                                611                 :                : static void
 4586 tgl@sss.pgh.pa.us         612                 :            955 : add_json(Datum val, bool is_null, StringInfo result,
                                613                 :                :          Oid val_type, bool key_scalar)
                                614                 :                : {
                                615                 :                :     JsonTypeCategory tcategory;
                                616                 :                :     Oid         outfuncoid;
                                617                 :                : 
 4687 andrew@dunslane.net       618         [ -  + ]:            955 :     if (val_type == InvalidOid)
 4687 andrew@dunslane.net       619         [ #  # ]:UBC           0 :         ereport(ERROR,
                                620                 :                :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                                621                 :                :                  errmsg("could not determine input data type")));
                                622                 :                : 
 4586 tgl@sss.pgh.pa.us         623         [ +  + ]:CBC         955 :     if (is_null)
                                624                 :                :     {
                                625                 :             48 :         tcategory = JSONTYPE_NULL;
                                626                 :             48 :         outfuncoid = InvalidOid;
                                627                 :                :     }
                                628                 :                :     else
 1227 amitlan@postgresql.o      629                 :            907 :         json_categorize_type(val_type, false,
                                630                 :                :                              &tcategory, &outfuncoid);
                                631                 :                : 
 1226                           632                 :            955 :     datum_to_json_internal(val, is_null, result, tcategory, outfuncoid,
                                633                 :                :                            key_scalar);
 4687 andrew@dunslane.net       634                 :            931 : }
                                635                 :                : 
                                636                 :                : /*
                                637                 :                :  * SQL function array_to_json(row)
                                638                 :                :  */
                                639                 :                : Datum
 4461 sfrost@snowman.net        640                 :             12 : array_to_json(PG_FUNCTION_ARGS)
                                641                 :                : {
 4443                           642                 :             12 :     Datum       array = PG_GETARG_DATUM(0);
                                643                 :                :     StringInfoData result;
                                644                 :                : 
  387 drowley@postgresql.o      645                 :             12 :     initStringInfo(&result);
                                646                 :                : 
                                647                 :             12 :     array_to_json_internal(array, &result, false);
                                648                 :                : 
                                649                 :             12 :     PG_RETURN_TEXT_P(cstring_to_text_with_len(result.data, result.len));
                                650                 :                : }
                                651                 :                : 
                                652                 :                : /*
                                653                 :                :  * SQL function array_to_json(row, prettybool)
                                654                 :                :  */
                                655                 :                : Datum
 4443 sfrost@snowman.net        656                 :             16 : array_to_json_pretty(PG_FUNCTION_ARGS)
                                657                 :                : {
 5284 bruce@momjian.us          658                 :             16 :     Datum       array = PG_GETARG_DATUM(0);
                                659                 :             16 :     bool        use_line_feeds = PG_GETARG_BOOL(1);
                                660                 :                :     StringInfoData result;
                                661                 :                : 
  387 drowley@postgresql.o      662                 :             16 :     initStringInfo(&result);
                                663                 :                : 
                                664                 :             16 :     array_to_json_internal(array, &result, use_line_feeds);
                                665                 :                : 
                                666                 :             16 :     PG_RETURN_TEXT_P(cstring_to_text_with_len(result.data, result.len));
                                667                 :                : }
                                668                 :                : 
                                669                 :                : /*
                                670                 :                :  * SQL function row_to_json(row)
                                671                 :                :  */
                                672                 :                : Datum
 5412 andrew@dunslane.net       673                 :            478 : row_to_json(PG_FUNCTION_ARGS)
                                674                 :                : {
 4443 sfrost@snowman.net        675                 :            478 :     Datum       array = PG_GETARG_DATUM(0);
                                676                 :                :     StringInfoData result;
                                677                 :                : 
  387 drowley@postgresql.o      678                 :            478 :     initStringInfo(&result);
                                679                 :                : 
                                680                 :            478 :     composite_to_json(array, &result, false);
                                681                 :                : 
                                682                 :            478 :     PG_RETURN_TEXT_P(cstring_to_text_with_len(result.data, result.len));
                                683                 :                : }
                                684                 :                : 
                                685                 :                : /*
                                686                 :                :  * SQL function row_to_json(row, prettybool)
                                687                 :                :  */
                                688                 :                : Datum
 4443 sfrost@snowman.net        689                 :             32 : row_to_json_pretty(PG_FUNCTION_ARGS)
                                690                 :                : {
 5284 bruce@momjian.us          691                 :             32 :     Datum       array = PG_GETARG_DATUM(0);
                                692                 :             32 :     bool        use_line_feeds = PG_GETARG_BOOL(1);
                                693                 :                :     StringInfoData result;
                                694                 :                : 
  387 drowley@postgresql.o      695                 :             32 :     initStringInfo(&result);
                                696                 :                : 
                                697                 :             32 :     composite_to_json(array, &result, use_line_feeds);
                                698                 :                : 
                                699                 :             32 :     PG_RETURN_TEXT_P(cstring_to_text_with_len(result.data, result.len));
                                700                 :                : }
                                701                 :                : 
                                702                 :                : /*
                                703                 :                :  * Is the given type immutable when coming out of a JSON context?
                                704                 :                :  *
                                705                 :                :  * At present, datetimes are all considered mutable, because they
                                706                 :                :  * depend on timezone.  XXX we should also drill down into objects
                                707                 :                :  * and arrays, but do not.
                                708                 :                :  */
                                709                 :                : bool
 1340 alvherre@alvh.no-ip.      710                 :UBC           0 : to_json_is_immutable(Oid typoid)
                                711                 :                : {
                                712                 :                :     JsonTypeCategory tcategory;
                                713                 :                :     Oid         outfuncoid;
                                714                 :                : 
   22 andrew@dunslane.net       715                 :              0 :     json_categorize_type(typoid, false, &tcategory, &outfuncoid);
                                716                 :                : 
                                717   [ #  #  #  #  :              0 :     switch (tcategory)
                                              #  # ]
                                718                 :                :     {
                                719                 :              0 :         case JSONTYPE_BOOL:
                                720                 :                :         case JSONTYPE_JSON:
                                721                 :                :         case JSONTYPE_JSONB:
                                722                 :                :         case JSONTYPE_NULL:
                                723                 :              0 :             return true;
                                724                 :                : 
                                725                 :              0 :         case JSONTYPE_DATE:
                                726                 :                :         case JSONTYPE_TIMESTAMP:
                                727                 :                :         case JSONTYPE_TIMESTAMPTZ:
                                728                 :              0 :             return false;
                                729                 :                : 
                                730                 :              0 :         case JSONTYPE_ARRAY:
                                731                 :              0 :             return false;       /* TODO recurse into elements */
                                732                 :                : 
                                733                 :              0 :         case JSONTYPE_COMPOSITE:
                                734                 :              0 :             return false;       /* TODO recurse into fields */
                                735                 :                : 
                                736                 :              0 :         case JSONTYPE_NUMERIC:
                                737                 :                :         case JSONTYPE_CAST:
                                738                 :                :         case JSONTYPE_OTHER:
                                739                 :              0 :             return func_volatile(outfuncoid) == PROVOLATILE_IMMUTABLE;
                                740                 :                :     }
                                741                 :                : 
                                742                 :              0 :     return false;               /* not reached */
                                743                 :                : }
                                744                 :                : 
                                745                 :                : /*
                                746                 :                :  * SQL function to_json(anyvalue)
                                747                 :                :  */
                                748                 :                : Datum
 5011 andrew@dunslane.net       749                 :CBC         132 : to_json(PG_FUNCTION_ARGS)
                                750                 :                : {
 4773 tgl@sss.pgh.pa.us         751                 :            132 :     Datum       val = PG_GETARG_DATUM(0);
 5011 andrew@dunslane.net       752                 :            132 :     Oid         val_type = get_fn_expr_argtype(fcinfo->flinfo, 0);
                                753                 :                :     JsonTypeCategory tcategory;
                                754                 :                :     Oid         outfuncoid;
                                755                 :                : 
                                756         [ -  + ]:            132 :     if (val_type == InvalidOid)
 5011 andrew@dunslane.net       757         [ #  # ]:UBC           0 :         ereport(ERROR,
                                758                 :                :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                                759                 :                :                  errmsg("could not determine input data type")));
                                760                 :                : 
 1227 amitlan@postgresql.o      761                 :CBC         132 :     json_categorize_type(val_type, false,
                                762                 :                :                          &tcategory, &outfuncoid);
                                763                 :                : 
 1226                           764                 :            132 :     PG_RETURN_DATUM(datum_to_json(val, tcategory, outfuncoid));
                                765                 :                : }
                                766                 :                : 
                                767                 :                : /*
                                768                 :                :  * Turn a Datum into JSON text.
                                769                 :                :  *
                                770                 :                :  * tcategory and outfuncoid are from a previous call to json_categorize_type.
                                771                 :                :  */
                                772                 :                : Datum
                                773                 :            177 : datum_to_json(Datum val, JsonTypeCategory tcategory, Oid outfuncoid)
                                774                 :                : {
                                775                 :                :     StringInfoData result;
                                776                 :                : 
  387 drowley@postgresql.o      777                 :            177 :     initStringInfo(&result);
                                778                 :            177 :     datum_to_json_internal(val, false, &result, tcategory, outfuncoid,
                                779                 :                :                            false);
                                780                 :                : 
                                781                 :            173 :     return PointerGetDatum(cstring_to_text_with_len(result.data, result.len));
                                782                 :                : }
                                783                 :                : 
                                784                 :                : /*
                                785                 :                :  * json_agg transition function
                                786                 :                :  *
                                787                 :                :  * aggregate input column as a json array value.
                                788                 :                :  */
                                789                 :                : static Datum
 1340 alvherre@alvh.no-ip.      790                 :            384 : json_agg_transfn_worker(FunctionCallInfo fcinfo, bool absent_on_null)
                                791                 :                : {
                                792                 :                :     MemoryContext aggcontext,
                                793                 :                :                 oldcontext;
                                794                 :                :     JsonAggState *state;
                                795                 :                :     Datum       val;
                                796                 :                : 
 5011 andrew@dunslane.net       797         [ -  + ]:            384 :     if (!AggCheckCallContext(fcinfo, &aggcontext))
                                798                 :                :     {
                                799                 :                :         /* cannot be called directly because of internal-type argument */
 5011 andrew@dunslane.net       800         [ #  # ]:UBC           0 :         elog(ERROR, "json_agg_transfn called in non-aggregate context");
                                801                 :                :     }
                                802                 :                : 
 5011 andrew@dunslane.net       803         [ +  + ]:CBC         384 :     if (PG_ARGISNULL(0))
                                804                 :                :     {
 4057 tgl@sss.pgh.pa.us         805                 :             94 :         Oid         arg_type = get_fn_expr_argtype(fcinfo->flinfo, 1);
                                806                 :                : 
 4089 andrew@dunslane.net       807         [ -  + ]:             94 :         if (arg_type == InvalidOid)
 4089 andrew@dunslane.net       808         [ #  # ]:UBC           0 :             ereport(ERROR,
                                809                 :                :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                                810                 :                :                      errmsg("could not determine input data type")));
                                811                 :                : 
                                812                 :                :         /*
                                813                 :                :          * Make this state object in a context where it will persist for the
                                814                 :                :          * duration of the aggregate call.  MemoryContextSwitchTo is only
                                815                 :                :          * needed the first time, as the StringInfo routines make sure they
                                816                 :                :          * use the right context to enlarge the object if necessary.
                                817                 :                :          */
 5011 andrew@dunslane.net       818                 :CBC          94 :         oldcontext = MemoryContextSwitchTo(aggcontext);
  353 michael@paquier.xyz       819                 :             94 :         state = palloc_object(JsonAggState);
 4089 andrew@dunslane.net       820                 :             94 :         state->str = makeStringInfo();
 5011                           821                 :             94 :         MemoryContextSwitchTo(oldcontext);
                                822                 :                : 
 4089                           823                 :             94 :         appendStringInfoChar(state->str, '[');
 1227 amitlan@postgresql.o      824                 :             94 :         json_categorize_type(arg_type, false, &state->val_category,
                                825                 :                :                              &state->val_output_func);
                                826                 :                :     }
                                827                 :                :     else
                                828                 :                :     {
 4089 andrew@dunslane.net       829                 :            290 :         state = (JsonAggState *) PG_GETARG_POINTER(0);
                                830                 :                :     }
                                831                 :                : 
 1340 alvherre@alvh.no-ip.      832   [ +  +  +  + ]:            384 :     if (absent_on_null && PG_ARGISNULL(1))
                                833                 :             60 :         PG_RETURN_POINTER(state);
                                834                 :                : 
                                835         [ +  + ]:            324 :     if (state->str->len > 1)
                                836                 :            234 :         appendStringInfoString(state->str, ", ");
                                837                 :                : 
                                838                 :                :     /* fast path for NULLs */
 5011 andrew@dunslane.net       839         [ +  + ]:            324 :     if (PG_ARGISNULL(1))
                                840                 :                :     {
 1226 amitlan@postgresql.o      841                 :             36 :         datum_to_json_internal((Datum) 0, true, state->str, JSONTYPE_NULL,
                                842                 :                :                                InvalidOid, false);
 5011 andrew@dunslane.net       843                 :             36 :         PG_RETURN_POINTER(state);
                                844                 :                :     }
                                845                 :                : 
 4773 tgl@sss.pgh.pa.us         846                 :            288 :     val = PG_GETARG_DATUM(1);
                                847                 :                : 
                                848                 :                :     /* add some whitespace if structured type and not first item */
 1340 alvherre@alvh.no-ip.      849   [ +  +  +  + ]:            288 :     if (!PG_ARGISNULL(0) && state->str->len > 1 &&
 4089 andrew@dunslane.net       850         [ +  + ]:            206 :         (state->val_category == JSONTYPE_ARRAY ||
                                851         [ +  + ]:            202 :          state->val_category == JSONTYPE_COMPOSITE))
                                852                 :                :     {
                                853                 :             74 :         appendStringInfoString(state->str, "\n ");
                                854                 :                :     }
                                855                 :                : 
 1226 amitlan@postgresql.o      856                 :            288 :     datum_to_json_internal(val, false, state->str, state->val_category,
                                857                 :                :                            state->val_output_func, false);
                                858                 :                : 
                                859                 :                :     /*
                                860                 :                :      * The transition type for json_agg() is declared to be "internal", which
                                861                 :                :      * is a pass-by-value type the same size as a pointer.  So we can safely
                                862                 :                :      * pass the JsonAggState pointer through nodeAgg.c's machinations.
                                863                 :                :      */
 5011 andrew@dunslane.net       864                 :            288 :     PG_RETURN_POINTER(state);
                                865                 :                : }
                                866                 :                : 
                                867                 :                : 
                                868                 :                : /*
                                869                 :                :  * json_agg aggregate function
                                870                 :                :  */
                                871                 :                : Datum
 1340 alvherre@alvh.no-ip.      872                 :            104 : json_agg_transfn(PG_FUNCTION_ARGS)
                                873                 :                : {
                                874                 :            104 :     return json_agg_transfn_worker(fcinfo, false);
                                875                 :                : }
                                876                 :                : 
                                877                 :                : /*
                                878                 :                :  * json_agg_strict aggregate function
                                879                 :                :  */
                                880                 :                : Datum
                                881                 :            280 : json_agg_strict_transfn(PG_FUNCTION_ARGS)
                                882                 :                : {
                                883                 :            280 :     return json_agg_transfn_worker(fcinfo, true);
                                884                 :                : }
                                885                 :                : 
                                886                 :                : /*
                                887                 :                :  * json_agg final function
                                888                 :                :  */
                                889                 :                : Datum
 5011 andrew@dunslane.net       890                 :            121 : json_agg_finalfn(PG_FUNCTION_ARGS)
                                891                 :                : {
                                892                 :                :     JsonAggState *state;
                                893                 :                : 
                                894                 :                :     /* cannot be called directly because of internal-type argument */
                                895         [ -  + ]:            121 :     Assert(AggCheckCallContext(fcinfo, NULL));
                                896                 :                : 
 4089                           897                 :            242 :     state = PG_ARGISNULL(0) ?
                                898         [ +  + ]:            121 :         NULL :
                                899                 :             94 :         (JsonAggState *) PG_GETARG_POINTER(0);
                                900                 :                : 
                                901                 :                :     /* NULL result for no rows in, as is standard with aggregates */
 5011                           902         [ +  + ]:            121 :     if (state == NULL)
                                903                 :             27 :         PG_RETURN_NULL();
                                904                 :                : 
                                905                 :                :     /* Else return state with appropriate array terminator added */
 4089                           906                 :             94 :     PG_RETURN_TEXT_P(catenate_stringinfo_string(state->str, "]"));
                                907                 :                : }
                                908                 :                : 
                                909                 :                : /* Functions implementing hash table for key uniqueness check */
                                910                 :                : static uint32
 1340 alvherre@alvh.no-ip.      911                 :           1217 : json_unique_hash(const void *key, Size keysize)
                                912                 :                : {
  306 peter@eisentraut.org      913                 :           1217 :     const JsonUniqueHashEntry *entry = (const JsonUniqueHashEntry *) key;
 1340 alvherre@alvh.no-ip.      914                 :           1217 :     uint32      hash = hash_bytes_uint32(entry->object_id);
                                915                 :                : 
                                916                 :           1217 :     hash ^= hash_bytes((const unsigned char *) entry->key, entry->key_len);
                                917                 :                : 
  477 peter@eisentraut.org      918                 :           1217 :     return hash;
                                919                 :                : }
                                920                 :                : 
                                921                 :                : static int
 1340 alvherre@alvh.no-ip.      922                 :             91 : json_unique_hash_match(const void *key1, const void *key2, Size keysize)
                                923                 :                : {
                                924                 :             91 :     const JsonUniqueHashEntry *entry1 = (const JsonUniqueHashEntry *) key1;
                                925                 :             91 :     const JsonUniqueHashEntry *entry2 = (const JsonUniqueHashEntry *) key2;
                                926                 :                : 
                                927         [ -  + ]:             91 :     if (entry1->object_id != entry2->object_id)
 1340 alvherre@alvh.no-ip.      928         [ #  # ]:UBC           0 :         return entry1->object_id > entry2->object_id ? 1 : -1;
                                929                 :                : 
 1340 alvherre@alvh.no-ip.      930         [ -  + ]:CBC          91 :     if (entry1->key_len != entry2->key_len)
 1340 alvherre@alvh.no-ip.      931         [ #  # ]:UBC           0 :         return entry1->key_len > entry2->key_len ? 1 : -1;
                                932                 :                : 
 1340 alvherre@alvh.no-ip.      933                 :CBC          91 :     return strncmp(entry1->key, entry2->key, entry1->key_len);
                                934                 :                : }
                                935                 :                : 
                                936                 :                : /*
                                937                 :                :  * Uniqueness detection support.
                                938                 :                :  *
                                939                 :                :  * In order to detect uniqueness during building or parsing of a JSON
                                940                 :                :  * object, we maintain a hash table of key names already seen.
                                941                 :                :  */
                                942                 :                : static void
                                943                 :            235 : json_unique_check_init(JsonUniqueCheckState *cxt)
                                944                 :                : {
                                945                 :                :     HASHCTL     ctl;
                                946                 :                : 
                                947                 :            235 :     memset(&ctl, 0, sizeof(ctl));
                                948                 :            235 :     ctl.keysize = sizeof(JsonUniqueHashEntry);
                                949                 :            235 :     ctl.entrysize = sizeof(JsonUniqueHashEntry);
                                950                 :            235 :     ctl.hcxt = CurrentMemoryContext;
                                951                 :            235 :     ctl.hash = json_unique_hash;
                                952                 :            235 :     ctl.match = json_unique_hash_match;
                                953                 :                : 
                                954                 :            235 :     *cxt = hash_create("json object hashtable",
                                955                 :                :                        32,
                                956                 :                :                        &ctl,
                                957                 :                :                        HASH_ELEM | HASH_CONTEXT | HASH_FUNCTION | HASH_COMPARE);
                                958                 :            235 : }
                                959                 :                : 
                                960                 :                : static void
                                961                 :             69 : json_unique_builder_init(JsonUniqueBuilderState *cxt)
                                962                 :                : {
                                963                 :             69 :     json_unique_check_init(&cxt->check);
                                964                 :             69 :     cxt->mcxt = CurrentMemoryContext;
                                965                 :             69 :     cxt->skipped_keys.data = NULL;
                                966                 :             69 : }
                                967                 :                : 
                                968                 :                : static bool
                                969                 :           1217 : json_unique_check_key(JsonUniqueCheckState *cxt, const char *key, int object_id)
                                970                 :                : {
                                971                 :                :     JsonUniqueHashEntry entry;
                                972                 :                :     bool        found;
                                973                 :                : 
                                974                 :           1217 :     entry.key = key;
                                975                 :           1217 :     entry.key_len = strlen(key);
                                976                 :           1217 :     entry.object_id = object_id;
                                977                 :                : 
                                978                 :           1217 :     (void) hash_search(*cxt, &entry, HASH_ENTER, &found);
                                979                 :                : 
                                980                 :           1217 :     return !found;
                                981                 :                : }
                                982                 :                : 
                                983                 :                : /*
                                984                 :                :  * On-demand initialization of a throwaway StringInfo.  This is used to
                                985                 :                :  * read a key name that we don't need to store in the output object, for
                                986                 :                :  * duplicate key detection when the value is NULL.
                                987                 :                :  */
                                988                 :                : static StringInfo
                                989                 :             72 : json_unique_builder_get_throwawaybuf(JsonUniqueBuilderState *cxt)
                                990                 :                : {
                                991                 :             72 :     StringInfo  out = &cxt->skipped_keys;
                                992                 :                : 
                                993         [ +  + ]:             72 :     if (!out->data)
                                994                 :                :     {
                                995                 :             28 :         MemoryContext oldcxt = MemoryContextSwitchTo(cxt->mcxt);
                                996                 :                : 
                                997                 :             28 :         initStringInfo(out);
                                998                 :             28 :         MemoryContextSwitchTo(oldcxt);
                                999                 :                :     }
                               1000                 :                :     else
                               1001                 :                :         /* Just reset the string to empty */
                               1002                 :             44 :         out->len = 0;
                               1003                 :                : 
                               1004                 :             72 :     return out;
                               1005                 :                : }
                               1006                 :                : 
                               1007                 :                : /*
                               1008                 :                :  * json_object_agg transition function.
                               1009                 :                :  *
                               1010                 :                :  * aggregate two input columns as a single json object value.
                               1011                 :                :  */
                               1012                 :                : static Datum
                               1013                 :           1135 : json_object_agg_transfn_worker(FunctionCallInfo fcinfo,
                               1014                 :                :                                bool absent_on_null, bool unique_keys)
                               1015                 :                : {
                               1016                 :                :     MemoryContext aggcontext,
                               1017                 :                :                 oldcontext;
                               1018                 :                :     JsonAggState *state;
                               1019                 :                :     StringInfo  out;
                               1020                 :                :     Datum       arg;
                               1021                 :                :     bool        skip;
                               1022                 :                :     int         key_offset;
                               1023                 :                : 
 4687 andrew@dunslane.net      1024         [ -  + ]:           1135 :     if (!AggCheckCallContext(fcinfo, &aggcontext))
                               1025                 :                :     {
                               1026                 :                :         /* cannot be called directly because of internal-type argument */
 4379 tgl@sss.pgh.pa.us        1027         [ #  # ]:UBC           0 :         elog(ERROR, "json_object_agg_transfn called in non-aggregate context");
                               1028                 :                :     }
                               1029                 :                : 
 4687 andrew@dunslane.net      1030         [ +  + ]:CBC        1135 :     if (PG_ARGISNULL(0))
                               1031                 :                :     {
                               1032                 :                :         Oid         arg_type;
                               1033                 :                : 
                               1034                 :                :         /*
                               1035                 :                :          * Make the StringInfo in a context where it will persist for the
                               1036                 :                :          * duration of the aggregate call. Switching context is only needed
                               1037                 :                :          * for this initial step, as the StringInfo and dynahash routines make
                               1038                 :                :          * sure they use the right context to enlarge the object if necessary.
                               1039                 :                :          */
                               1040                 :            117 :         oldcontext = MemoryContextSwitchTo(aggcontext);
  353 michael@paquier.xyz      1041                 :            117 :         state = palloc_object(JsonAggState);
 4089 andrew@dunslane.net      1042                 :            117 :         state->str = makeStringInfo();
 1340 alvherre@alvh.no-ip.     1043         [ +  + ]:            117 :         if (unique_keys)
                               1044                 :             48 :             json_unique_builder_init(&state->unique_check);
                               1045                 :                :         else
                               1046                 :             69 :             memset(&state->unique_check, 0, sizeof(state->unique_check));
 4687 andrew@dunslane.net      1047                 :            117 :         MemoryContextSwitchTo(oldcontext);
                               1048                 :                : 
 4089                          1049                 :            117 :         arg_type = get_fn_expr_argtype(fcinfo->flinfo, 1);
                               1050                 :                : 
                               1051         [ -  + ]:            117 :         if (arg_type == InvalidOid)
 4089 andrew@dunslane.net      1052         [ #  # ]:UBC           0 :             ereport(ERROR,
                               1053                 :                :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                               1054                 :                :                      errmsg("could not determine data type for argument %d", 1)));
                               1055                 :                : 
 1227 amitlan@postgresql.o     1056                 :CBC         117 :         json_categorize_type(arg_type, false, &state->key_category,
                               1057                 :                :                              &state->key_output_func);
                               1058                 :                : 
 4089 andrew@dunslane.net      1059                 :            117 :         arg_type = get_fn_expr_argtype(fcinfo->flinfo, 2);
                               1060                 :                : 
                               1061         [ -  + ]:            117 :         if (arg_type == InvalidOid)
 4089 andrew@dunslane.net      1062         [ #  # ]:UBC           0 :             ereport(ERROR,
                               1063                 :                :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                               1064                 :                :                      errmsg("could not determine data type for argument %d", 2)));
                               1065                 :                : 
 1227 amitlan@postgresql.o     1066                 :CBC         117 :         json_categorize_type(arg_type, false, &state->val_category,
                               1067                 :                :                              &state->val_output_func);
                               1068                 :                : 
 4089 andrew@dunslane.net      1069                 :            117 :         appendStringInfoString(state->str, "{ ");
                               1070                 :                :     }
                               1071                 :                :     else
                               1072                 :                :     {
                               1073                 :           1018 :         state = (JsonAggState *) PG_GETARG_POINTER(0);
                               1074                 :                :     }
                               1075                 :                : 
                               1076                 :                :     /*
                               1077                 :                :      * Note: since json_object_agg() is declared as taking type "any", the
                               1078                 :                :      * parser will not do any type conversion on unknown-type literals (that
                               1079                 :                :      * is, undecorated strings or NULLs).  Such values will arrive here as
                               1080                 :                :      * type UNKNOWN, which fortunately does not matter to us, since
                               1081                 :                :      * unknownout() works fine.
                               1082                 :                :      */
                               1083                 :                : 
 4494 tgl@sss.pgh.pa.us        1084         [ +  + ]:           1135 :     if (PG_ARGISNULL(1))
                               1085         [ +  - ]:             12 :         ereport(ERROR,
                               1086                 :                :                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
                               1087                 :                :                  errmsg("null value not allowed for object key")));
                               1088                 :                : 
                               1089                 :                :     /* Skip null values if absent_on_null */
 1340 alvherre@alvh.no-ip.     1090   [ +  +  +  + ]:           1123 :     skip = absent_on_null && PG_ARGISNULL(2);
                               1091                 :                : 
                               1092         [ +  + ]:           1123 :     if (skip)
                               1093                 :                :     {
                               1094                 :                :         /*
                               1095                 :                :          * We got a NULL value and we're not storing those; if we're not
                               1096                 :                :          * testing key uniqueness, we're done.  If we are, use the throwaway
                               1097                 :                :          * buffer to store the key name so that we can check it.
                               1098                 :                :          */
                               1099         [ +  + ]:             80 :         if (!unique_keys)
                               1100                 :             16 :             PG_RETURN_POINTER(state);
                               1101                 :                : 
                               1102                 :             64 :         out = json_unique_builder_get_throwawaybuf(&state->unique_check);
                               1103                 :                :     }
                               1104                 :                :     else
                               1105                 :                :     {
                               1106                 :           1043 :         out = state->str;
                               1107                 :                : 
                               1108                 :                :         /*
                               1109                 :                :          * Append comma delimiter only if we have already output some fields
                               1110                 :                :          * after the initial string "{ ".
                               1111                 :                :          */
                               1112         [ +  + ]:           1043 :         if (out->len > 2)
                               1113                 :            938 :             appendStringInfoString(out, ", ");
                               1114                 :                :     }
                               1115                 :                : 
 4494 tgl@sss.pgh.pa.us        1116                 :           1107 :     arg = PG_GETARG_DATUM(1);
                               1117                 :                : 
 1340 alvherre@alvh.no-ip.     1118                 :           1107 :     key_offset = out->len;
                               1119                 :                : 
 1226 amitlan@postgresql.o     1120                 :           1107 :     datum_to_json_internal(arg, false, out, state->key_category,
                               1121                 :                :                            state->key_output_func, true);
                               1122                 :                : 
 1340 alvherre@alvh.no-ip.     1123         [ +  + ]:           1107 :     if (unique_keys)
                               1124                 :                :     {
                               1125                 :                :         /*
                               1126                 :                :          * Copy the key first, instead of pointing into the buffer. It will be
                               1127                 :                :          * added to the hash table, but the buffer may get reallocated as
                               1128                 :                :          * we're appending more data to it. That would invalidate pointers to
                               1129                 :                :          * keys in the current buffer.
                               1130                 :                :          */
  808 tomas.vondra@postgre     1131                 :            960 :         const char *key = MemoryContextStrdup(aggcontext,
                               1132                 :            960 :                                               &out->data[key_offset]);
                               1133                 :                : 
 1340 alvherre@alvh.no-ip.     1134         [ +  + ]:            960 :         if (!json_unique_check_key(&state->unique_check.check, key, 0))
                               1135         [ +  - ]:             28 :             ereport(ERROR,
                               1136                 :                :                     errcode(ERRCODE_DUPLICATE_JSON_OBJECT_KEY_VALUE),
                               1137                 :                :                     errmsg("duplicate JSON object key value: %s", key));
                               1138                 :                : 
                               1139         [ +  + ]:            932 :         if (skip)
                               1140                 :             56 :             PG_RETURN_POINTER(state);
                               1141                 :                :     }
                               1142                 :                : 
 4089 andrew@dunslane.net      1143                 :           1023 :     appendStringInfoString(state->str, " : ");
                               1144                 :                : 
 4494 tgl@sss.pgh.pa.us        1145         [ +  + ]:           1023 :     if (PG_ARGISNULL(2))
                               1146                 :             52 :         arg = (Datum) 0;
                               1147                 :                :     else
                               1148                 :            971 :         arg = PG_GETARG_DATUM(2);
                               1149                 :                : 
 1226 amitlan@postgresql.o     1150                 :           1023 :     datum_to_json_internal(arg, PG_ARGISNULL(2), state->str,
                               1151                 :                :                            state->val_category,
                               1152                 :                :                            state->val_output_func, false);
                               1153                 :                : 
 4687 andrew@dunslane.net      1154                 :           1023 :     PG_RETURN_POINTER(state);
                               1155                 :                : }
                               1156                 :                : 
                               1157                 :                : /*
                               1158                 :                :  * json_object_agg aggregate function
                               1159                 :                :  */
                               1160                 :                : Datum
 1340 alvherre@alvh.no-ip.     1161                 :            135 : json_object_agg_transfn(PG_FUNCTION_ARGS)
                               1162                 :                : {
                               1163                 :            135 :     return json_object_agg_transfn_worker(fcinfo, false, false);
                               1164                 :                : }
                               1165                 :                : 
                               1166                 :                : /*
                               1167                 :                :  * json_object_agg_strict aggregate function
                               1168                 :                :  */
                               1169                 :                : Datum
                               1170                 :             40 : json_object_agg_strict_transfn(PG_FUNCTION_ARGS)
                               1171                 :                : {
                               1172                 :             40 :     return json_object_agg_transfn_worker(fcinfo, true, false);
                               1173                 :                : }
                               1174                 :                : 
                               1175                 :                : /*
                               1176                 :                :  * json_object_agg_unique aggregate function
                               1177                 :                :  */
                               1178                 :                : Datum
                               1179                 :            876 : json_object_agg_unique_transfn(PG_FUNCTION_ARGS)
                               1180                 :                : {
                               1181                 :            876 :     return json_object_agg_transfn_worker(fcinfo, false, true);
                               1182                 :                : }
                               1183                 :                : 
                               1184                 :                : /*
                               1185                 :                :  * json_object_agg_unique_strict aggregate function
                               1186                 :                :  */
                               1187                 :                : Datum
                               1188                 :             84 : json_object_agg_unique_strict_transfn(PG_FUNCTION_ARGS)
                               1189                 :                : {
                               1190                 :             84 :     return json_object_agg_transfn_worker(fcinfo, true, true);
                               1191                 :                : }
                               1192                 :                : 
                               1193                 :                : /*
                               1194                 :                :  * json_object_agg final function.
                               1195                 :                :  */
                               1196                 :                : Datum
 4687 andrew@dunslane.net      1197                 :            177 : json_object_agg_finalfn(PG_FUNCTION_ARGS)
                               1198                 :                : {
                               1199                 :                :     JsonAggState *state;
                               1200                 :                : 
                               1201                 :                :     /* cannot be called directly because of internal-type argument */
                               1202         [ -  + ]:            177 :     Assert(AggCheckCallContext(fcinfo, NULL));
                               1203                 :                : 
 4089                          1204         [ +  + ]:            177 :     state = PG_ARGISNULL(0) ? NULL : (JsonAggState *) PG_GETARG_POINTER(0);
                               1205                 :                : 
                               1206                 :                :     /* NULL result for no rows in, as is standard with aggregates */
 4687                          1207         [ +  + ]:            177 :     if (state == NULL)
 4447                          1208                 :              8 :         PG_RETURN_NULL();
                               1209                 :                : 
                               1210                 :                :     /* Else return state with appropriate object terminator added */
 4089                          1211                 :            169 :     PG_RETURN_TEXT_P(catenate_stringinfo_string(state->str, " }"));
                               1212                 :                : }
                               1213                 :                : 
                               1214                 :                : /*
                               1215                 :                :  * Helper function for aggregates: return given StringInfo's contents plus
                               1216                 :                :  * specified trailing string, as a text datum.  We need this because aggregate
                               1217                 :                :  * final functions are not allowed to modify the aggregate state.
                               1218                 :                :  */
                               1219                 :                : static text *
 4379 tgl@sss.pgh.pa.us        1220                 :            263 : catenate_stringinfo_string(StringInfo buffer, const char *addon)
                               1221                 :                : {
                               1222                 :                :     /* custom version of cstring_to_text_with_len */
                               1223                 :            263 :     int         buflen = buffer->len;
                               1224                 :            263 :     int         addlen = strlen(addon);
                               1225                 :            263 :     text       *result = (text *) palloc(buflen + addlen + VARHDRSZ);
                               1226                 :                : 
                               1227                 :            263 :     SET_VARSIZE(result, buflen + addlen + VARHDRSZ);
                               1228                 :            263 :     memcpy(VARDATA(result), buffer->data, buflen);
                               1229                 :            263 :     memcpy(VARDATA(result) + buflen, addon, addlen);
                               1230                 :                : 
                               1231                 :            263 :     return result;
                               1232                 :                : }
                               1233                 :                : 
                               1234                 :                : Datum
 1145 peter@eisentraut.org     1235                 :            313 : json_build_object_worker(int nargs, const Datum *args, const bool *nulls, const Oid *types,
                               1236                 :                :                          bool absent_on_null, bool unique_keys)
                               1237                 :                : {
                               1238                 :                :     int         i;
 4494 tgl@sss.pgh.pa.us        1239                 :            313 :     const char *sep = "";
                               1240                 :                :     StringInfo  result;
                               1241                 :                :     JsonUniqueBuilderState unique_check;
                               1242                 :                : 
 4687 andrew@dunslane.net      1243         [ +  + ]:            313 :     if (nargs % 2 != 0)
                               1244         [ +  - ]:             12 :         ereport(ERROR,
                               1245                 :                :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                               1246                 :                :                  errmsg("argument list must have even number of elements"),
                               1247                 :                :         /* translator: %s is a SQL function name */
                               1248                 :                :                  errhint("The arguments of %s must consist of alternating keys and values.",
                               1249                 :                :                          "json_build_object()")));
                               1250                 :                : 
                               1251                 :            301 :     result = makeStringInfo();
                               1252                 :                : 
                               1253                 :            301 :     appendStringInfoChar(result, '{');
                               1254                 :                : 
 1340 alvherre@alvh.no-ip.     1255         [ +  + ]:            301 :     if (unique_keys)
                               1256                 :             21 :         json_unique_builder_init(&unique_check);
                               1257                 :                : 
 4687 andrew@dunslane.net      1258         [ +  + ]:            637 :     for (i = 0; i < nargs; i += 2)
                               1259                 :                :     {
                               1260                 :                :         StringInfo  out;
                               1261                 :                :         bool        skip;
                               1262                 :                :         int         key_offset;
                               1263                 :                : 
                               1264                 :                :         /* Skip null values if absent_on_null */
 1340 alvherre@alvh.no-ip.     1265   [ +  +  +  + ]:            397 :         skip = absent_on_null && nulls[i + 1];
                               1266                 :                : 
                               1267         [ +  + ]:            397 :         if (skip)
                               1268                 :                :         {
                               1269                 :                :             /* If key uniqueness check is needed we must save skipped keys */
                               1270         [ +  + ]:             17 :             if (!unique_keys)
                               1271                 :              9 :                 continue;
                               1272                 :                : 
                               1273                 :              8 :             out = json_unique_builder_get_throwawaybuf(&unique_check);
                               1274                 :                :         }
                               1275                 :                :         else
                               1276                 :                :         {
                               1277                 :            380 :             appendStringInfoString(result, sep);
                               1278                 :            380 :             sep = ", ";
                               1279                 :            380 :             out = result;
                               1280                 :                :         }
                               1281                 :                : 
                               1282                 :                :         /* process key */
 3321 andrew@dunslane.net      1283         [ +  + ]:            388 :         if (nulls[i])
 4687                          1284         [ +  - ]:             16 :             ereport(ERROR,
                               1285                 :                :                     (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
                               1286                 :                :                      errmsg("null value not allowed for object key")));
                               1287                 :                : 
                               1288                 :                :         /* save key offset before appending it */
 1340 alvherre@alvh.no-ip.     1289                 :            372 :         key_offset = out->len;
                               1290                 :                : 
                               1291                 :            372 :         add_json(args[i], false, out, types[i], true);
                               1292                 :                : 
                               1293         [ +  + ]:            348 :         if (unique_keys)
                               1294                 :                :         {
                               1295                 :                :             /*
                               1296                 :                :              * check key uniqueness after key appending
                               1297                 :                :              *
                               1298                 :                :              * Copy the key first, instead of pointing into the buffer. It
                               1299                 :                :              * will be added to the hash table, but the buffer may get
                               1300                 :                :              * reallocated as we're appending more data to it. That would
                               1301                 :                :              * invalidate pointers to keys in the current buffer.
                               1302                 :                :              */
  808 tomas.vondra@postgre     1303                 :             62 :             const char *key = pstrdup(&out->data[key_offset]);
                               1304                 :                : 
 1340 alvherre@alvh.no-ip.     1305         [ +  + ]:             62 :             if (!json_unique_check_key(&unique_check.check, key, 0))
                               1306         [ +  - ]:             21 :                 ereport(ERROR,
                               1307                 :                :                         errcode(ERRCODE_DUPLICATE_JSON_OBJECT_KEY_VALUE),
                               1308                 :                :                         errmsg("duplicate JSON object key value: %s", key));
                               1309                 :                : 
                               1310         [ +  + ]:             41 :             if (skip)
                               1311                 :              4 :                 continue;
                               1312                 :                :         }
                               1313                 :                : 
 4687 andrew@dunslane.net      1314                 :            323 :         appendStringInfoString(result, " : ");
                               1315                 :                : 
                               1316                 :                :         /* process value */
 3321                          1317                 :            323 :         add_json(args[i + 1], nulls[i + 1], result, types[i + 1], false);
                               1318                 :                :     }
                               1319                 :                : 
 4687                          1320                 :            240 :     appendStringInfoChar(result, '}');
                               1321                 :                : 
 1340 alvherre@alvh.no-ip.     1322                 :            240 :     return PointerGetDatum(cstring_to_text_with_len(result->data, result->len));
                               1323                 :                : }
                               1324                 :                : 
                               1325                 :                : /*
                               1326                 :                :  * SQL function json_build_object(variadic "any")
                               1327                 :                :  */
                               1328                 :                : Datum
                               1329                 :            104 : json_build_object(PG_FUNCTION_ARGS)
                               1330                 :                : {
                               1331                 :                :     Datum      *args;
                               1332                 :                :     bool       *nulls;
                               1333                 :                :     Oid        *types;
                               1334                 :                : 
                               1335                 :                :     /* build argument values to build the object */
                               1336                 :            104 :     int         nargs = extract_variadic_args(fcinfo, 0, true,
                               1337                 :                :                                               &args, &types, &nulls);
                               1338                 :                : 
                               1339         [ +  + ]:            104 :     if (nargs < 0)
                               1340                 :              4 :         PG_RETURN_NULL();
                               1341                 :                : 
                               1342                 :            100 :     PG_RETURN_DATUM(json_build_object_worker(nargs, args, nulls, types, false, false));
                               1343                 :                : }
                               1344                 :                : 
                               1345                 :                : /*
                               1346                 :                :  * degenerate case of json_build_object where it gets 0 arguments.
                               1347                 :                :  */
                               1348                 :                : Datum
 4687 andrew@dunslane.net      1349                 :              4 : json_build_object_noargs(PG_FUNCTION_ARGS)
                               1350                 :                : {
                               1351                 :              4 :     PG_RETURN_TEXT_P(cstring_to_text_with_len("{}", 2));
                               1352                 :                : }
                               1353                 :                : 
                               1354                 :                : Datum
 1145 peter@eisentraut.org     1355                 :            154 : json_build_array_worker(int nargs, const Datum *args, const bool *nulls, const Oid *types,
                               1356                 :                :                         bool absent_on_null)
                               1357                 :                : {
                               1358                 :                :     int         i;
 4494 tgl@sss.pgh.pa.us        1359                 :            154 :     const char *sep = "";
                               1360                 :                :     StringInfoData result;
                               1361                 :                : 
  387 drowley@postgresql.o     1362                 :            154 :     initStringInfo(&result);
                               1363                 :                : 
                               1364                 :            154 :     appendStringInfoChar(&result, '[');
                               1365                 :                : 
 4687 andrew@dunslane.net      1366         [ +  + ]:            426 :     for (i = 0; i < nargs; i++)
                               1367                 :                :     {
 1340 alvherre@alvh.no-ip.     1368   [ +  +  +  + ]:            272 :         if (absent_on_null && nulls[i])
                               1369                 :             12 :             continue;
                               1370                 :                : 
  387 drowley@postgresql.o     1371                 :            260 :         appendStringInfoString(&result, sep);
 4494 tgl@sss.pgh.pa.us        1372                 :            260 :         sep = ", ";
  387 drowley@postgresql.o     1373                 :            260 :         add_json(args[i], nulls[i], &result, types[i], false);
                               1374                 :                :     }
                               1375                 :                : 
                               1376                 :            154 :     appendStringInfoChar(&result, ']');
                               1377                 :                : 
                               1378                 :            154 :     return PointerGetDatum(cstring_to_text_with_len(result.data, result.len));
                               1379                 :                : }
                               1380                 :                : 
                               1381                 :                : /*
                               1382                 :                :  * SQL function json_build_array(variadic "any")
                               1383                 :                :  */
                               1384                 :                : Datum
 1340 alvherre@alvh.no-ip.     1385                 :             36 : json_build_array(PG_FUNCTION_ARGS)
                               1386                 :                : {
                               1387                 :                :     Datum      *args;
                               1388                 :                :     bool       *nulls;
                               1389                 :                :     Oid        *types;
                               1390                 :                : 
                               1391                 :                :     /* build argument values to build the object */
                               1392                 :             36 :     int         nargs = extract_variadic_args(fcinfo, 0, true,
                               1393                 :                :                                               &args, &types, &nulls);
                               1394                 :                : 
                               1395         [ +  + ]:             36 :     if (nargs < 0)
                               1396                 :              4 :         PG_RETURN_NULL();
                               1397                 :                : 
                               1398                 :             32 :     PG_RETURN_DATUM(json_build_array_worker(nargs, args, nulls, types, false));
                               1399                 :                : }
                               1400                 :                : 
                               1401                 :                : /*
                               1402                 :                :  * degenerate case of json_build_array where it gets 0 arguments.
                               1403                 :                :  */
                               1404                 :                : Datum
 4687 andrew@dunslane.net      1405                 :              4 : json_build_array_noargs(PG_FUNCTION_ARGS)
                               1406                 :                : {
                               1407                 :              4 :     PG_RETURN_TEXT_P(cstring_to_text_with_len("[]", 2));
                               1408                 :                : }
                               1409                 :                : 
                               1410                 :                : /*
                               1411                 :                :  * SQL function json_object(text[])
                               1412                 :                :  *
                               1413                 :                :  * take a one or two dimensional array of text as key/value pairs
                               1414                 :                :  * for a json object.
                               1415                 :                :  */
                               1416                 :                : Datum
                               1417                 :             35 : json_object(PG_FUNCTION_ARGS)
                               1418                 :                : {
                               1419                 :             35 :     ArrayType  *in_array = PG_GETARG_ARRAYTYPE_P(0);
                               1420                 :             35 :     int         ndims = ARR_NDIM(in_array);
                               1421                 :                :     StringInfoData result;
                               1422                 :                :     Datum      *in_datums;
                               1423                 :                :     bool       *in_nulls;
                               1424                 :                :     int         in_count,
                               1425                 :                :                 count,
                               1426                 :                :                 i;
                               1427                 :                :     text       *rval;
                               1428                 :                : 
                               1429   [ +  +  +  + ]:             35 :     switch (ndims)
                               1430                 :                :     {
                               1431                 :              5 :         case 0:
                               1432                 :              5 :             PG_RETURN_DATUM(CStringGetTextDatum("{}"));
                               1433                 :                :             break;
                               1434                 :                : 
                               1435                 :             13 :         case 1:
                               1436         [ +  + ]:             13 :             if ((ARR_DIMS(in_array)[0]) % 2)
                               1437         [ +  - ]:              4 :                 ereport(ERROR,
                               1438                 :                :                         (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
                               1439                 :                :                          errmsg("array must have even number of elements")));
                               1440                 :              9 :             break;
                               1441                 :                : 
                               1442                 :             13 :         case 2:
                               1443         [ +  + ]:             13 :             if ((ARR_DIMS(in_array)[1]) != 2)
                               1444         [ +  - ]:              8 :                 ereport(ERROR,
                               1445                 :                :                         (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
                               1446                 :                :                          errmsg("array must have two columns")));
                               1447                 :              5 :             break;
                               1448                 :                : 
                               1449                 :              4 :         default:
                               1450         [ +  - ]:              4 :             ereport(ERROR,
                               1451                 :                :                     (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
                               1452                 :                :                      errmsg("wrong number of array subscripts")));
                               1453                 :                :     }
                               1454                 :                : 
 1611 peter@eisentraut.org     1455                 :             14 :     deconstruct_array_builtin(in_array, TEXTOID, &in_datums, &in_nulls, &in_count);
                               1456                 :                : 
 4687 andrew@dunslane.net      1457                 :             14 :     count = in_count / 2;
                               1458                 :                : 
                               1459                 :             14 :     initStringInfo(&result);
                               1460                 :                : 
                               1461                 :             14 :     appendStringInfoChar(&result, '{');
                               1462                 :                : 
                               1463         [ +  + ]:           1254 :     for (i = 0; i < count; ++i)
                               1464                 :                :     {
                               1465         [ -  + ]:           1240 :         if (in_nulls[i * 2])
 4687 andrew@dunslane.net      1466         [ #  # ]:UBC           0 :             ereport(ERROR,
                               1467                 :                :                     (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
                               1468                 :                :                      errmsg("null value not allowed for object key")));
                               1469                 :                : 
 4687 andrew@dunslane.net      1470         [ +  + ]:CBC        1240 :         if (i > 0)
                               1471                 :           1226 :             appendStringInfoString(&result, ", ");
  854 drowley@postgresql.o     1472                 :           1240 :         escape_json_text(&result, (text *) DatumGetPointer(in_datums[i * 2]));
 4687 andrew@dunslane.net      1473                 :           1240 :         appendStringInfoString(&result, " : ");
                               1474         [ +  + ]:           1240 :         if (in_nulls[i * 2 + 1])
                               1475                 :             10 :             appendStringInfoString(&result, "null");
                               1476                 :                :         else
                               1477                 :                :         {
  854 drowley@postgresql.o     1478                 :           1230 :             escape_json_text(&result,
                               1479                 :           1230 :                              (text *) DatumGetPointer(in_datums[i * 2 + 1]));
                               1480                 :                :         }
                               1481                 :                :     }
                               1482                 :                : 
 4687 andrew@dunslane.net      1483                 :             14 :     appendStringInfoChar(&result, '}');
                               1484                 :                : 
                               1485                 :             14 :     pfree(in_datums);
                               1486                 :             14 :     pfree(in_nulls);
                               1487                 :                : 
                               1488                 :             14 :     rval = cstring_to_text_with_len(result.data, result.len);
                               1489                 :             14 :     pfree(result.data);
                               1490                 :                : 
                               1491                 :             14 :     PG_RETURN_TEXT_P(rval);
                               1492                 :                : }
                               1493                 :                : 
                               1494                 :                : /*
                               1495                 :                :  * SQL function json_object(text[], text[])
                               1496                 :                :  *
                               1497                 :                :  * take separate key and value arrays of text to construct a json object
                               1498                 :                :  * pairwise.
                               1499                 :                :  */
                               1500                 :                : Datum
                               1501                 :             31 : json_object_two_arg(PG_FUNCTION_ARGS)
                               1502                 :                : {
                               1503                 :             31 :     ArrayType  *key_array = PG_GETARG_ARRAYTYPE_P(0);
                               1504                 :             31 :     ArrayType  *val_array = PG_GETARG_ARRAYTYPE_P(1);
                               1505                 :             31 :     int         nkdims = ARR_NDIM(key_array);
                               1506                 :             31 :     int         nvdims = ARR_NDIM(val_array);
                               1507                 :                :     StringInfoData result;
                               1508                 :                :     Datum      *key_datums,
                               1509                 :                :                *val_datums;
                               1510                 :                :     bool       *key_nulls,
                               1511                 :                :                *val_nulls;
                               1512                 :                :     int         key_count,
                               1513                 :                :                 val_count,
                               1514                 :                :                 i;
                               1515                 :                :     text       *rval;
                               1516                 :                : 
                               1517   [ +  +  -  + ]:             31 :     if (nkdims > 1 || nkdims != nvdims)
                               1518         [ +  - ]:              4 :         ereport(ERROR,
                               1519                 :                :                 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
                               1520                 :                :                  errmsg("wrong number of array subscripts")));
                               1521                 :                : 
                               1522         [ +  + ]:             27 :     if (nkdims == 0)
                               1523                 :              5 :         PG_RETURN_DATUM(CStringGetTextDatum("{}"));
                               1524                 :                : 
 1611 peter@eisentraut.org     1525                 :             22 :     deconstruct_array_builtin(key_array, TEXTOID, &key_datums, &key_nulls, &key_count);
                               1526                 :             22 :     deconstruct_array_builtin(val_array, TEXTOID, &val_datums, &val_nulls, &val_count);
                               1527                 :                : 
 4687 andrew@dunslane.net      1528         [ +  + ]:             22 :     if (key_count != val_count)
                               1529         [ +  - ]:              8 :         ereport(ERROR,
                               1530                 :                :                 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
                               1531                 :                :                  errmsg("mismatched array dimensions")));
                               1532                 :                : 
                               1533                 :             14 :     initStringInfo(&result);
                               1534                 :                : 
                               1535                 :             14 :     appendStringInfoChar(&result, '{');
                               1536                 :                : 
                               1537         [ +  + ]:             62 :     for (i = 0; i < key_count; ++i)
                               1538                 :                :     {
                               1539         [ +  + ]:             52 :         if (key_nulls[i])
                               1540         [ +  - ]:              4 :             ereport(ERROR,
                               1541                 :                :                     (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
                               1542                 :                :                      errmsg("null value not allowed for object key")));
                               1543                 :                : 
                               1544         [ +  + ]:             48 :         if (i > 0)
                               1545                 :             34 :             appendStringInfoString(&result, ", ");
  854 drowley@postgresql.o     1546                 :             48 :         escape_json_text(&result, (text *) DatumGetPointer(key_datums[i]));
 4687 andrew@dunslane.net      1547                 :             48 :         appendStringInfoString(&result, " : ");
                               1548         [ -  + ]:             48 :         if (val_nulls[i])
 4687 andrew@dunslane.net      1549                 :UBC           0 :             appendStringInfoString(&result, "null");
                               1550                 :                :         else
  854 drowley@postgresql.o     1551                 :CBC          48 :             escape_json_text(&result,
                               1552                 :             48 :                              (text *) DatumGetPointer(val_datums[i]));
                               1553                 :                :     }
                               1554                 :                : 
 4687 andrew@dunslane.net      1555                 :             10 :     appendStringInfoChar(&result, '}');
                               1556                 :                : 
                               1557                 :             10 :     pfree(key_datums);
                               1558                 :             10 :     pfree(key_nulls);
                               1559                 :             10 :     pfree(val_datums);
                               1560                 :             10 :     pfree(val_nulls);
                               1561                 :                : 
                               1562                 :             10 :     rval = cstring_to_text_with_len(result.data, result.len);
                               1563                 :             10 :     pfree(result.data);
                               1564                 :                : 
                               1565                 :             10 :     PG_RETURN_TEXT_P(rval);
                               1566                 :                : }
                               1567                 :                : 
                               1568                 :                : /*
                               1569                 :                :  * escape_json_char
                               1570                 :                :  *      Inline helper function for escape_json* functions
                               1571                 :                :  */
                               1572                 :                : static pg_always_inline void
  854 drowley@postgresql.o     1573                 :        2770122 : escape_json_char(StringInfo buf, char c)
                               1574                 :                : {
                               1575   [ +  +  +  +  :        2770122 :     switch (c)
                                        +  +  +  + ]
                               1576                 :                :     {
                               1577                 :             16 :         case '\b':
                               1578                 :             16 :             appendStringInfoString(buf, "\\b");
                               1579                 :             16 :             break;
                               1580                 :              8 :         case '\f':
                               1581                 :              8 :             appendStringInfoString(buf, "\\f");
                               1582                 :              8 :             break;
                               1583                 :            104 :         case '\n':
                               1584                 :            104 :             appendStringInfoString(buf, "\\n");
                               1585                 :            104 :             break;
                               1586                 :             92 :         case '\r':
                               1587                 :             92 :             appendStringInfoString(buf, "\\r");
                               1588                 :             92 :             break;
                               1589                 :            124 :         case '\t':
                               1590                 :            124 :             appendStringInfoString(buf, "\\t");
                               1591                 :            124 :             break;
                               1592                 :            436 :         case '"':
                               1593                 :            436 :             appendStringInfoString(buf, "\\\"");
                               1594                 :            436 :             break;
                               1595                 :            204 :         case '\\':
                               1596                 :            204 :             appendStringInfoString(buf, "\\\\");
                               1597                 :            204 :             break;
                               1598                 :        2769138 :         default:
                               1599         [ +  + ]:        2769138 :             if ((unsigned char) c < ' ')
                               1600                 :              4 :                 appendStringInfo(buf, "\\u%04x", (int) c);
                               1601                 :                :             else
                               1602         [ +  + ]:        2769134 :                 appendStringInfoCharMacro(buf, c);
                               1603                 :        2769138 :             break;
                               1604                 :                :     }
                               1605                 :        2770122 : }
                               1606                 :                : 
                               1607                 :                : /*
                               1608                 :                :  * escape_json
                               1609                 :                :  *      Produce a JSON string literal, properly escaping the NUL-terminated
                               1610                 :                :  *      cstring.
                               1611                 :                :  */
                               1612                 :                : void
 5412 andrew@dunslane.net      1613                 :          26827 : escape_json(StringInfo buf, const char *str)
                               1614                 :                : {
  854 drowley@postgresql.o     1615         [ +  + ]:          26827 :     appendStringInfoCharMacro(buf, '"');
                               1616                 :                : 
                               1617         [ +  + ]:         425115 :     for (; *str != '\0'; str++)
                               1618                 :         398288 :         escape_json_char(buf, *str);
                               1619                 :                : 
 3994 peter_e@gmx.net          1620         [ +  + ]:          26827 :     appendStringInfoCharMacro(buf, '"');
  854 drowley@postgresql.o     1621                 :          26827 : }
                               1622                 :                : 
                               1623                 :                : /*
                               1624                 :                :  * Define the number of bytes that escape_json_with_len will look ahead in the
                               1625                 :                :  * input string before flushing the input string to the destination buffer.
                               1626                 :                :  * Looking ahead too far could result in cachelines being evicted that will
                               1627                 :                :  * need to be reloaded in order to perform the appendBinaryStringInfo call.
                               1628                 :                :  * Smaller values will result in a larger number of calls to
                               1629                 :                :  * appendBinaryStringInfo and introduce additional function call overhead.
                               1630                 :                :  * Values larger than the size of L1d cache will likely result in worse
                               1631                 :                :  * performance.
                               1632                 :                :  */
                               1633                 :                : #define ESCAPE_JSON_FLUSH_AFTER 512
                               1634                 :                : 
                               1635                 :                : /*
                               1636                 :                :  * escape_json_with_len
                               1637                 :                :  *      Produce a JSON string literal, properly escaping the possibly not
                               1638                 :                :  *      NUL-terminated characters in 'str'.  'len' defines the number of bytes
                               1639                 :                :  *      from 'str' to process.
                               1640                 :                :  */
                               1641                 :                : void
                               1642                 :         239571 : escape_json_with_len(StringInfo buf, const char *str, int len)
                               1643                 :                : {
                               1644                 :                :     int         vlen;
                               1645                 :                : 
  845                          1646         [ -  + ]:         239571 :     Assert(len >= 0);
                               1647                 :                : 
                               1648                 :                :     /*
                               1649                 :                :      * Since we know the minimum length we'll need to append, let's just
                               1650                 :                :      * enlarge the buffer now rather than incrementally making more space when
                               1651                 :                :      * we run out.  Add two extra bytes for the enclosing quotes.
                               1652                 :                :      */
                               1653                 :         239571 :     enlargeStringInfo(buf, len + 2);
                               1654                 :                : 
                               1655                 :                :     /*
                               1656                 :                :      * Figure out how many bytes to process using SIMD.  Round 'len' down to
                               1657                 :                :      * the previous multiple of sizeof(Vector8), assuming that's a power-of-2.
                               1658                 :                :      */
                               1659                 :         239571 :     vlen = len & (int) (~(sizeof(Vector8) - 1));
                               1660                 :                : 
 3994 peter_e@gmx.net          1661         [ -  + ]:         239571 :     appendStringInfoCharMacro(buf, '"');
                               1662                 :                : 
  845 drowley@postgresql.o     1663                 :         239571 :     for (int i = 0, copypos = 0;;)
                               1664                 :                :     {
                               1665                 :                :         /*
                               1666                 :                :          * To speed this up, try searching sizeof(Vector8) bytes at once for
                               1667                 :                :          * special characters that we need to escape.  When we find one, we
                               1668                 :                :          * fall out of the Vector8 loop and copy the portion we've vector
                               1669                 :                :          * searched and then we process sizeof(Vector8) bytes one byte at a
                               1670                 :                :          * time.  Once done, come back and try doing vector searching again.
                               1671                 :                :          * We'll also process any remaining bytes at the tail end of the
                               1672                 :                :          * string byte-by-byte.  This optimization assumes that most chunks of
                               1673                 :                :          * sizeof(Vector8) bytes won't contain any special characters.
                               1674                 :                :          */
                               1675         [ +  + ]:         259076 :         for (; i < vlen; i += sizeof(Vector8))
                               1676                 :                :         {
                               1677                 :                :             Vector8     chunk;
                               1678                 :                : 
                               1679                 :          19505 :             vector8_load(&chunk, (const uint8 *) &str[i]);
                               1680                 :                : 
                               1681                 :                :             /*
                               1682                 :                :              * Break on anything less than ' ' or if we find a '"' or '\\'.
                               1683                 :                :              * Those need special handling.  That's done in the per-byte loop.
                               1684                 :                :              */
                               1685   [ +  +  +  + ]:          38962 :             if (vector8_has_le(chunk, (unsigned char) 0x1F) ||
                               1686         [ +  + ]:          38898 :                 vector8_has(chunk, (unsigned char) '"') ||
                               1687                 :          19441 :                 vector8_has(chunk, (unsigned char) '\\'))
                               1688                 :                :                 break;
                               1689                 :                : 
                               1690                 :                : #ifdef ESCAPE_JSON_FLUSH_AFTER
                               1691                 :                : 
                               1692                 :                :             /*
                               1693                 :                :              * Flush what's been checked so far out to the destination buffer
                               1694                 :                :              * every so often to avoid having to re-read cachelines when
                               1695                 :                :              * escaping large strings.
                               1696                 :                :              */
                               1697         [ +  + ]:          19417 :             if (i - copypos >= ESCAPE_JSON_FLUSH_AFTER)
                               1698                 :                :             {
                               1699                 :             20 :                 appendBinaryStringInfo(buf, &str[copypos], i - copypos);
                               1700                 :             20 :                 copypos = i;
                               1701                 :                :             }
                               1702                 :                : #endif
                               1703                 :                :         }
                               1704                 :                : 
                               1705                 :                :         /*
                               1706                 :                :          * Write to the destination up to the point that we've vector searched
                               1707                 :                :          * so far.  Do this only when switching into per-byte mode rather than
                               1708                 :                :          * once every sizeof(Vector8) bytes.
                               1709                 :                :          */
                               1710         [ +  + ]:         239659 :         if (copypos < i)
                               1711                 :                :         {
                               1712                 :          17670 :             appendBinaryStringInfo(buf, &str[copypos], i - copypos);
                               1713                 :          17670 :             copypos = i;
                               1714                 :                :         }
                               1715                 :                : 
                               1716                 :                :         /*
                               1717                 :                :          * Per-byte loop for Vector8s containing special chars and for
                               1718                 :                :          * processing the tail of the string.
                               1719                 :                :          */
  140 peter@eisentraut.org     1720         [ +  + ]:GNC     2611493 :         for (size_t b = 0; b < sizeof(Vector8); b++)
                               1721                 :                :         {
                               1722                 :                :             /* check if we've finished */
  845 drowley@postgresql.o     1723         [ +  + ]:CBC     2611405 :             if (i == len)
                               1724                 :         239571 :                 goto done;
                               1725                 :                : 
                               1726         [ -  + ]:        2371834 :             Assert(i < len);
                               1727                 :                : 
                               1728                 :        2371834 :             escape_json_char(buf, str[i++]);
                               1729                 :                :         }
                               1730                 :                : 
                               1731                 :             88 :         copypos = i;
                               1732                 :                :         /* We're not done yet.  Try the vector search again. */
                               1733                 :                :     }
                               1734                 :                : 
                               1735                 :         239571 : done:
  854                          1736         [ -  + ]:         239571 :     appendStringInfoCharMacro(buf, '"');
                               1737                 :         239571 : }
                               1738                 :                : 
                               1739                 :                : /*
                               1740                 :                :  * escape_json_text
                               1741                 :                :  *      Append 'txt' onto 'buf' and escape using escape_json_with_len.
                               1742                 :                :  *
                               1743                 :                :  * This is more efficient than calling text_to_cstring and appending the
                               1744                 :                :  * result as that could require an additional palloc and memcpy.
                               1745                 :                :  */
                               1746                 :                : void
                               1747                 :           3628 : escape_json_text(StringInfo buf, const text *txt)
                               1748                 :                : {
                               1749                 :                :     /* must cast away the const, unfortunately */
                               1750                 :           3628 :     text       *tunpacked = pg_detoast_datum_packed(unconstify(text *, txt));
                               1751                 :           3628 :     int         len = VARSIZE_ANY_EXHDR(tunpacked);
                               1752                 :                :     char       *str;
                               1753                 :                : 
                               1754                 :           3628 :     str = VARDATA_ANY(tunpacked);
                               1755                 :                : 
                               1756                 :           3628 :     escape_json_with_len(buf, str, len);
                               1757                 :                : 
                               1758                 :                :     /* pfree any detoasted values */
                               1759         [ -  + ]:           3628 :     if (tunpacked != txt)
  854 drowley@postgresql.o     1760                 :UBC           0 :         pfree(tunpacked);
 5412 andrew@dunslane.net      1761                 :CBC        3628 : }
                               1762                 :                : 
                               1763                 :                : /* Semantic actions for key uniqueness check */
                               1764                 :                : static JsonParseErrorType
 1338 alvherre@alvh.no-ip.     1765                 :            131 : json_unique_object_start(void *_state)
                               1766                 :                : {
                               1767                 :            131 :     JsonUniqueParsingState *state = _state;
                               1768                 :                :     JsonUniqueStackEntry *entry;
                               1769                 :                : 
                               1770         [ -  + ]:            131 :     if (!state->unique)
 1338 alvherre@alvh.no-ip.     1771                 :UBC           0 :         return JSON_SUCCESS;
                               1772                 :                : 
                               1773                 :                :     /* push object entry to stack */
  353 michael@paquier.xyz      1774                 :CBC         131 :     entry = palloc_object(JsonUniqueStackEntry);
 1338 alvherre@alvh.no-ip.     1775                 :            131 :     entry->object_id = state->id_counter++;
                               1776                 :            131 :     entry->parent = state->stack;
                               1777                 :            131 :     state->stack = entry;
                               1778                 :                : 
                               1779                 :            131 :     return JSON_SUCCESS;
                               1780                 :                : }
                               1781                 :                : 
                               1782                 :                : static JsonParseErrorType
                               1783                 :            127 : json_unique_object_end(void *_state)
                               1784                 :                : {
                               1785                 :            127 :     JsonUniqueParsingState *state = _state;
                               1786                 :                :     JsonUniqueStackEntry *entry;
                               1787                 :                : 
                               1788         [ +  + ]:            127 :     if (!state->unique)
                               1789                 :             55 :         return JSON_SUCCESS;
                               1790                 :                : 
                               1791                 :             72 :     entry = state->stack;
                               1792                 :             72 :     state->stack = entry->parent; /* pop object from stack */
                               1793                 :             72 :     pfree(entry);
                               1794                 :             72 :     return JSON_SUCCESS;
                               1795                 :                : }
                               1796                 :                : 
                               1797                 :                : static JsonParseErrorType
                               1798                 :            195 : json_unique_object_field_start(void *_state, char *field, bool isnull)
                               1799                 :                : {
                               1800                 :            195 :     JsonUniqueParsingState *state = _state;
                               1801                 :                :     JsonUniqueStackEntry *entry;
                               1802                 :                : 
                               1803         [ -  + ]:            195 :     if (!state->unique)
 1338 alvherre@alvh.no-ip.     1804                 :UBC           0 :         return JSON_SUCCESS;
                               1805                 :                : 
                               1806                 :                :     /* find key collision in the current object */
 1338 alvherre@alvh.no-ip.     1807         [ +  + ]:CBC         195 :     if (json_unique_check_key(&state->check, field, state->stack->object_id))
                               1808                 :            153 :         return JSON_SUCCESS;
                               1809                 :                : 
                               1810                 :             42 :     state->unique = false;
                               1811                 :                : 
                               1812                 :                :     /* pop all objects entries */
                               1813         [ +  + ]:             97 :     while ((entry = state->stack))
                               1814                 :                :     {
                               1815                 :             55 :         state->stack = entry->parent;
                               1816                 :             55 :         pfree(entry);
                               1817                 :                :     }
                               1818                 :             42 :     return JSON_SUCCESS;
                               1819                 :                : }
                               1820                 :                : 
                               1821                 :                : /* Validate JSON text and additionally check key uniqueness */
                               1822                 :                : bool
                               1823                 :            895 : json_validate(text *json, bool check_unique_keys, bool throw_error)
                               1824                 :                : {
                               1825                 :                :     JsonLexContext lex;
                               1826                 :            895 :     JsonSemAction uniqueSemAction = {0};
                               1827                 :                :     JsonUniqueParsingState state;
                               1828                 :                :     JsonParseErrorType result;
                               1829                 :                : 
 1150                          1830                 :            895 :     makeJsonLexContext(&lex, json, check_unique_keys);
                               1831                 :                : 
 1338                          1832         [ +  + ]:            895 :     if (check_unique_keys)
                               1833                 :                :     {
 1150                          1834                 :            166 :         state.lex = &lex;
 1338                          1835                 :            166 :         state.stack = NULL;
                               1836                 :            166 :         state.id_counter = 0;
                               1837                 :            166 :         state.unique = true;
                               1838                 :            166 :         json_unique_check_init(&state.check);
                               1839                 :                : 
                               1840                 :            166 :         uniqueSemAction.semstate = &state;
                               1841                 :            166 :         uniqueSemAction.object_start = json_unique_object_start;
                               1842                 :            166 :         uniqueSemAction.object_field_start = json_unique_object_field_start;
                               1843                 :            166 :         uniqueSemAction.object_end = json_unique_object_end;
                               1844                 :                :     }
                               1845                 :                : 
 1150                          1846         [ +  + ]:            895 :     result = pg_parse_json(&lex, check_unique_keys ? &uniqueSemAction : &nullSemAction);
                               1847                 :                : 
 1338                          1848         [ +  + ]:            895 :     if (result != JSON_SUCCESS)
                               1849                 :                :     {
                               1850         [ -  + ]:            144 :         if (throw_error)
 1150 alvherre@alvh.no-ip.     1851                 :UBC           0 :             json_errsave_error(result, &lex, NULL);
                               1852                 :                : 
 1338 alvherre@alvh.no-ip.     1853                 :CBC         144 :         return false;           /* invalid json */
                               1854                 :                :     }
                               1855                 :                : 
                               1856   [ +  +  +  + ]:            751 :     if (check_unique_keys && !state.unique)
                               1857                 :                :     {
                               1858         [ +  + ]:             42 :         if (throw_error)
                               1859         [ +  - ]:              5 :             ereport(ERROR,
                               1860                 :                :                     (errcode(ERRCODE_DUPLICATE_JSON_OBJECT_KEY_VALUE),
                               1861                 :                :                      errmsg("duplicate JSON object key value")));
                               1862                 :                : 
                               1863                 :             37 :         return false;           /* not unique keys */
                               1864                 :                :     }
                               1865                 :                : 
 1150                          1866         [ +  + ]:            709 :     if (check_unique_keys)
                               1867                 :            108 :         freeJsonLexContext(&lex);
                               1868                 :                : 
 1338                          1869                 :            709 :     return true;                /* ok */
                               1870                 :                : }
                               1871                 :                : 
                               1872                 :                : /*
                               1873                 :                :  * SQL function json_typeof(json) -> text
                               1874                 :                :  *
                               1875                 :                :  * Returns the type of the outermost JSON value as TEXT.  Possible types are
                               1876                 :                :  * "object", "array", "string", "number", "boolean", and "null".
                               1877                 :                :  *
                               1878                 :                :  * Performs a single call to json_lex() to get the first token of the supplied
                               1879                 :                :  * value.  This initial token uniquely determines the value's type.  As our
                               1880                 :                :  * input must already have been validated by json_in() or json_recv(), the
                               1881                 :                :  * initial token should never be JSON_TOKEN_OBJECT_END, JSON_TOKEN_ARRAY_END,
                               1882                 :                :  * JSON_TOKEN_COLON, JSON_TOKEN_COMMA, or JSON_TOKEN_END.
                               1883                 :                :  */
                               1884                 :                : Datum
 4797 andrew@dunslane.net      1885                 :             40 : json_typeof(PG_FUNCTION_ARGS)
                               1886                 :                : {
 1338 alvherre@alvh.no-ip.     1887                 :             40 :     text       *json = PG_GETARG_TEXT_PP(0);
                               1888                 :                :     JsonLexContext lex;
                               1889                 :                :     char       *type;
                               1890                 :                :     JsonParseErrorType result;
                               1891                 :                : 
                               1892                 :                :     /* Lex exactly one token from the input and check its type. */
 1150                          1893                 :             40 :     makeJsonLexContext(&lex, json, false);
                               1894                 :             40 :     result = json_lex(&lex);
 1549 andrew@dunslane.net      1895         [ -  + ]:             40 :     if (result != JSON_SUCCESS)
 1150 alvherre@alvh.no-ip.     1896                 :UBC           0 :         json_errsave_error(result, &lex, NULL);
                               1897                 :                : 
 1150 alvherre@alvh.no-ip.     1898   [ +  +  +  +  :CBC          40 :     switch (lex.token_type)
                                           +  +  - ]
                               1899                 :                :     {
 4693 andrew@dunslane.net      1900                 :              8 :         case JSON_TOKEN_OBJECT_START:
                               1901                 :              8 :             type = "object";
                               1902                 :              8 :             break;
                               1903                 :              8 :         case JSON_TOKEN_ARRAY_START:
                               1904                 :              8 :             type = "array";
                               1905                 :              8 :             break;
                               1906                 :              4 :         case JSON_TOKEN_STRING:
                               1907                 :              4 :             type = "string";
                               1908                 :              4 :             break;
                               1909                 :              8 :         case JSON_TOKEN_NUMBER:
                               1910                 :              8 :             type = "number";
                               1911                 :              8 :             break;
                               1912                 :              8 :         case JSON_TOKEN_TRUE:
                               1913                 :                :         case JSON_TOKEN_FALSE:
                               1914                 :              8 :             type = "boolean";
                               1915                 :              8 :             break;
                               1916                 :              4 :         case JSON_TOKEN_NULL:
                               1917                 :              4 :             type = "null";
                               1918                 :              4 :             break;
 4693 andrew@dunslane.net      1919                 :UBC           0 :         default:
 1150 alvherre@alvh.no-ip.     1920         [ #  # ]:              0 :             elog(ERROR, "unexpected json token: %d", lex.token_type);
                               1921                 :                :     }
                               1922                 :                : 
 4766 peter_e@gmx.net          1923                 :CBC          40 :     PG_RETURN_TEXT_P(cstring_to_text(type));
                               1924                 :                : }
        

Generated by: LCOV version 2.0-1