Branch data 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
109 : 4448 : json_in(PG_FUNCTION_ARGS)
110 : : {
111 : 4448 : char *json = PG_GETARG_CSTRING(0);
112 : 4448 : text *result = cstring_to_text(json);
113 : : JsonLexContext lex;
114 : :
115 : : /* validate it */
116 : 4448 : makeJsonLexContext(&lex, result, false);
117 [ + + ]: 4448 : if (!pg_parse_json_or_errsave(&lex, &nullSemAction, fcinfo->context))
118 : 8 : PG_RETURN_NULL();
119 : :
120 : : /* Internal representation is the same as text */
121 : 4308 : PG_RETURN_TEXT_P(result);
122 : : }
123 : :
124 : : /*
125 : : * Output.
126 : : */
127 : : Datum
128 : 4035 : json_out(PG_FUNCTION_ARGS)
129 : : {
130 : : /* we needn't detoast because text_to_cstring will handle that */
131 : 4035 : Datum txt = PG_GETARG_DATUM(0);
132 : :
133 : 4035 : PG_RETURN_CSTRING(TextDatumGetCString(txt));
134 : : }
135 : :
136 : : /*
137 : : * Binary send.
138 : : */
139 : : Datum
140 : 0 : json_send(PG_FUNCTION_ARGS)
141 : : {
142 : 0 : text *t = PG_GETARG_TEXT_PP(0);
143 : : StringInfoData buf;
144 : :
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. */
164 : 0 : makeJsonLexContextCstringLen(&lex, str, nbytes, GetDatabaseEncoding(),
165 : : false);
166 : 0 : pg_parse_json_or_ereport(&lex, &nullSemAction);
167 : :
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
181 : 6833 : 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 : :
189 : 6833 : check_stack_depth();
190 : :
191 : : /* callers are expected to ensure that null keys are not passed in */
192 : : Assert(!(key_scalar && is_null));
193 : :
194 [ + + ]: 6833 : if (is_null)
195 : : {
196 : 320 : appendBinaryStringInfo(result, "null", strlen("null"));
197 : 320 : return;
198 : : }
199 : :
200 [ + + + + ]: 6513 : if (key_scalar &&
201 [ + + ]: 1471 : (tcategory == JSONTYPE_ARRAY ||
202 [ + + ]: 1467 : tcategory == JSONTYPE_COMPOSITE ||
203 [ - + ]: 1459 : 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 : :
209 [ + + + + : 6489 : switch (tcategory)
+ + + + +
+ ]
210 : : {
211 : 240 : case JSONTYPE_ARRAY:
212 : 240 : array_to_json_internal(val, result, false);
213 : 240 : break;
214 : 332 : case JSONTYPE_COMPOSITE:
215 : 332 : composite_to_json(val, result, false);
216 : 332 : break;
217 : 42 : case JSONTYPE_BOOL:
218 [ - + ]: 42 : if (key_scalar)
219 : 0 : appendStringInfoChar(result, '"');
220 [ + + ]: 42 : if (DatumGetBool(val))
221 : 26 : appendBinaryStringInfo(result, "true", strlen("true"));
222 : : else
223 : 16 : appendBinaryStringInfo(result, "false", strlen("false"));
224 [ - + ]: 42 : if (key_scalar)
225 : 0 : appendStringInfoChar(result, '"');
226 : 42 : break;
227 : 3939 : case JSONTYPE_NUMERIC:
228 : 3939 : 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 : : */
236 [ + + ]: 3939 : if (!key_scalar &&
237 [ + + + + ]: 2853 : ((*outputstr >= '0' && *outputstr <= '9') ||
238 [ + + ]: 52 : (*outputstr == '-' &&
239 [ + - + + ]: 44 : (outputstr[1] >= '0' && outputstr[1] <= '9'))))
240 : 2841 : appendStringInfoString(result, outputstr);
241 : : else
242 : : {
243 : 1098 : appendStringInfoChar(result, '"');
244 : 1098 : appendStringInfoString(result, outputstr);
245 : 1098 : appendStringInfoChar(result, '"');
246 : : }
247 : 3939 : pfree(outputstr);
248 : 3939 : break;
249 : 16 : case JSONTYPE_DATE:
250 : : {
251 : : char buf[MAXDATELEN + 1];
252 : :
253 : 16 : JsonEncodeDateTime(buf, val, DATEOID, NULL);
254 : 16 : appendStringInfoChar(result, '"');
255 : 16 : appendStringInfoString(result, buf);
256 : 16 : appendStringInfoChar(result, '"');
257 : : }
258 : 16 : break;
259 : 35 : case JSONTYPE_TIMESTAMP:
260 : : {
261 : : char buf[MAXDATELEN + 1];
262 : :
263 : 35 : JsonEncodeDateTime(buf, val, TIMESTAMPOID, NULL);
264 : 35 : appendStringInfoChar(result, '"');
265 : 35 : appendStringInfoString(result, buf);
266 : 35 : appendStringInfoChar(result, '"');
267 : : }
268 : 35 : break;
269 : 37 : case JSONTYPE_TIMESTAMPTZ:
270 : : {
271 : : char buf[MAXDATELEN + 1];
272 : :
273 : 37 : JsonEncodeDateTime(buf, val, TIMESTAMPTZOID, NULL);
274 : 37 : appendStringInfoChar(result, '"');
275 : 37 : appendStringInfoString(result, buf);
276 : 37 : appendStringInfoChar(result, '"');
277 : : }
278 : 37 : break;
279 : 632 : case JSONTYPE_JSON:
280 : : /* JSON and JSONB output will already be escaped */
281 : 632 : outputstr = OidOutputFunctionCall(outfuncoid, val);
282 : 632 : appendStringInfoString(result, outputstr);
283 : 632 : pfree(outputstr);
284 : 632 : break;
285 : 10 : case JSONTYPE_CAST:
286 : : /* outfuncoid refers to a cast function, not an output function */
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);
293 : 6 : jsontext = DatumGetTextPP(OidFunctionCall1(outfuncoid, val));
294 : 6 : appendBinaryStringInfo(result, VARDATA_ANY(jsontext),
295 : 6 : VARSIZE_ANY_EXHDR(jsontext));
296 : 6 : pfree(jsontext);
297 : 6 : break;
298 : 1206 : default:
299 : : /* special-case text types to save useless palloc/memcpy cycles */
300 [ + + + + : 1206 : if (outfuncoid == F_TEXTOUT || outfuncoid == F_VARCHAROUT ||
+ + ]
301 : : outfuncoid == F_BPCHAROUT)
302 : 979 : escape_json_text(result, (text *) DatumGetPointer(val));
303 : : else
304 : : {
305 : 227 : outputstr = OidOutputFunctionCall(outfuncoid, val);
306 : 227 : escape_json(result, outputstr);
307 : 227 : pfree(outputstr);
308 : : }
309 : 1206 : 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 *
319 : 1272 : JsonEncodeDateTime(char *buf, Datum value, Oid typid, const int *tzp)
320 : : {
321 [ + + ]: 1272 : if (!buf)
322 : 40 : buf = palloc(MAXDATELEN + 1);
323 : :
324 [ + + + + : 1272 : 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 */
334 [ + + + + ]: 160 : if (DATE_NOT_FINITE(date))
335 : 16 : EncodeSpecialDate(date, buf);
336 : : else
337 : : {
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;
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 : 263 : case TIMESTAMPOID:
370 : : {
371 : : Timestamp timestamp;
372 : : struct pg_tm tm;
373 : : fsec_t fsec;
374 : :
375 : 263 : timestamp = DatumGetTimestamp(value);
376 : : /* Same as timestamp_out(), but forcing DateStyle */
377 [ + + + + ]: 263 : if (TIMESTAMP_NOT_FINITE(timestamp))
378 : 16 : EncodeSpecialTimestamp(timestamp, buf);
379 [ + - ]: 247 : else if (timestamp2tm(timestamp, NULL, &tm, &fsec, NULL, NULL) == 0)
380 : 247 : EncodeDateTime(&tm, fsec, false, 0, NULL, USE_XSD_DATES, buf);
381 : : else
382 [ # # ]: 0 : ereport(ERROR,
383 : : (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
384 : : errmsg("timestamp out of range")));
385 : : }
386 : 263 : break;
387 : 361 : case TIMESTAMPTZOID:
388 : : {
389 : : TimestampTz timestamp;
390 : : struct pg_tm tm;
391 : : int tz;
392 : : fsec_t fsec;
393 : 361 : const char *tzn = NULL;
394 : :
395 : 361 : 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 : : */
403 [ + + ]: 361 : 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 */
410 [ + + + + ]: 361 : if (TIMESTAMP_NOT_FINITE(timestamp))
411 : 16 : EncodeSpecialTimestamp(timestamp, buf);
412 [ + + + + : 345 : else if (timestamp2tm(timestamp, tzp ? NULL : &tz, &tm, &fsec,
+ - ]
413 : : tzp ? NULL : &tzn, NULL) == 0)
414 : : {
415 [ + + ]: 345 : if (tzp)
416 : 308 : tm.tm_isdst = 1; /* set time-zone presence flag */
417 : :
418 : 345 : EncodeDateTime(&tm, fsec, true, tz, tzn, USE_XSD_DATES, buf);
419 : : }
420 : : else
421 [ # # ]: 0 : ereport(ERROR,
422 : : (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
423 : : errmsg("timestamp out of range")));
424 : : }
425 : 361 : break;
426 : 0 : default:
427 [ # # ]: 0 : elog(ERROR, "unknown jsonb value datetime type oid %u", typid);
428 : : return NULL;
429 : : }
430 : :
431 : 1272 : 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
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 : :
447 : : 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)
456 : 460 : appendStringInfoString(result, sep);
457 : :
458 [ + + ]: 728 : if (dim + 1 == ndims)
459 : : {
460 : 720 : datum_to_json_internal(vals[*valcount], nulls[*valcount],
461 : : result, tcategory,
462 : : outfuncoid, false);
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 : : */
471 : 8 : array_dim_to_json(result, dim + 1, ndims, dims, vals, nulls,
472 : : valcount, tcategory, outfuncoid, false);
473 : : }
474 : : }
475 : :
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;
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 : :
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 : : {
505 : 8 : appendStringInfoString(result, "[]");
506 : 8 : return;
507 : : }
508 : :
509 : 260 : get_typlenbyvalalign(element_type,
510 : : &typlen, &typbyval, &typalign);
511 : :
512 : 260 : json_categorize_type(element_type, false,
513 : : &tcategory, &outfuncoid);
514 : :
515 : 260 : deconstruct_array(v, element_type, typlen, typbyval,
516 : : typalign, &elements, &nulls,
517 : : &nitems);
518 : :
519 : 260 : array_dim_to_json(result, 0, ndim, dim, elements, nulls, &count, tcategory,
520 : : outfuncoid, use_line_feeds);
521 : :
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
531 : 1186 : 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;
540 : 1186 : 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 : : */
548 [ + + ]: 1186 : sep = use_line_feeds ? ",\n " : ",";
549 [ + + ]: 1186 : seplen = use_line_feeds ? strlen(",\n ") : strlen(",");
550 : :
551 : 1186 : td = DatumGetHeapTupleHeader(composite);
552 : :
553 : : /* Extract rowtype info and find a tupdesc */
554 : 1186 : tupType = HeapTupleHeaderGetTypeId(td);
555 : 1186 : tupTypmod = HeapTupleHeaderGetTypMod(td);
556 : 1186 : tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
557 : :
558 : : /* Build a temporary HeapTuple control structure */
559 : 1186 : tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
560 : 1186 : tmptup.t_data = td;
561 : 1186 : tuple = &tmptup;
562 : :
563 : 1186 : appendStringInfoChar(result, '{');
564 : :
565 [ + + ]: 3701 : for (i = 0; i < tupdesc->natts; i++)
566 : : {
567 : : Datum val;
568 : : bool isnull;
569 : : char *attname;
570 : : JsonTypeCategory tcategory;
571 : : Oid outfuncoid;
572 : 2515 : Form_pg_attribute att = TupleDescAttr(tupdesc, i);
573 : :
574 [ - + ]: 2515 : if (att->attisdropped)
575 : 0 : continue;
576 : :
577 [ + + ]: 2515 : if (needsep)
578 : 1329 : appendBinaryStringInfo(result, sep, seplen);
579 : 2515 : needsep = true;
580 : :
581 : 2515 : attname = NameStr(att->attname);
582 : 2515 : escape_json(result, attname);
583 : 2515 : appendStringInfoChar(result, ':');
584 : :
585 : 2515 : val = heap_getattr(tuple, i + 1, tupdesc, &isnull);
586 : :
587 [ + + ]: 2515 : if (isnull)
588 : : {
589 : 184 : tcategory = JSONTYPE_NULL;
590 : 184 : outfuncoid = InvalidOid;
591 : : }
592 : : else
593 : 2331 : json_categorize_type(att->atttypid, false, &tcategory,
594 : : &outfuncoid);
595 : :
596 : 2515 : datum_to_json_internal(val, isnull, result, tcategory, outfuncoid,
597 : : false);
598 : : }
599 : :
600 : 1186 : appendStringInfoChar(result, '}');
601 [ + - ]: 1186 : ReleaseTupleDesc(tupdesc);
602 : 1186 : }
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
612 : 962 : add_json(Datum val, bool is_null, StringInfo result,
613 : : Oid val_type, bool key_scalar)
614 : : {
615 : : JsonTypeCategory tcategory;
616 : : Oid outfuncoid;
617 : :
618 [ - + ]: 962 : if (val_type == InvalidOid)
619 [ # # ]: 0 : ereport(ERROR,
620 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
621 : : errmsg("could not determine input data type")));
622 : :
623 [ + + ]: 962 : if (is_null)
624 : : {
625 : 48 : tcategory = JSONTYPE_NULL;
626 : 48 : outfuncoid = InvalidOid;
627 : : }
628 : : else
629 : 914 : json_categorize_type(val_type, false,
630 : : &tcategory, &outfuncoid);
631 : :
632 : 962 : datum_to_json_internal(val, is_null, result, tcategory, outfuncoid,
633 : : key_scalar);
634 : 938 : }
635 : :
636 : : /*
637 : : * SQL function array_to_json(row)
638 : : */
639 : : Datum
640 : 12 : array_to_json(PG_FUNCTION_ARGS)
641 : : {
642 : 12 : Datum array = PG_GETARG_DATUM(0);
643 : : StringInfoData result;
644 : :
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
656 : 16 : array_to_json_pretty(PG_FUNCTION_ARGS)
657 : : {
658 : 16 : Datum array = PG_GETARG_DATUM(0);
659 : 16 : bool use_line_feeds = PG_GETARG_BOOL(1);
660 : : StringInfoData result;
661 : :
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
673 : 472 : row_to_json(PG_FUNCTION_ARGS)
674 : : {
675 : 472 : Datum array = PG_GETARG_DATUM(0);
676 : : StringInfoData result;
677 : :
678 : 472 : initStringInfo(&result);
679 : :
680 : 472 : composite_to_json(array, &result, false);
681 : :
682 : 472 : 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
689 : 32 : row_to_json_pretty(PG_FUNCTION_ARGS)
690 : : {
691 : 32 : Datum array = PG_GETARG_DATUM(0);
692 : 32 : bool use_line_feeds = PG_GETARG_BOOL(1);
693 : : StringInfoData result;
694 : :
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
710 : 0 : to_json_is_immutable(Oid typoid)
711 : : {
712 : : JsonTypeCategory tcategory;
713 : : Oid outfuncoid;
714 : :
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
749 : 132 : to_json(PG_FUNCTION_ARGS)
750 : : {
751 : 132 : Datum val = PG_GETARG_DATUM(0);
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)
757 [ # # ]: 0 : ereport(ERROR,
758 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
759 : : errmsg("could not determine input data type")));
760 : :
761 : 132 : json_categorize_type(val_type, false,
762 : : &tcategory, &outfuncoid);
763 : :
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 : 182 : datum_to_json(Datum val, JsonTypeCategory tcategory, Oid outfuncoid)
774 : : {
775 : : StringInfoData result;
776 : :
777 : 182 : initStringInfo(&result);
778 : 182 : datum_to_json_internal(val, false, &result, tcategory, outfuncoid,
779 : : false);
780 : :
781 : 178 : 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
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 : :
797 [ - + ]: 384 : if (!AggCheckCallContext(fcinfo, &aggcontext))
798 : : {
799 : : /* cannot be called directly because of internal-type argument */
800 [ # # ]: 0 : elog(ERROR, "json_agg_transfn called in non-aggregate context");
801 : : }
802 : :
803 [ + + ]: 384 : if (PG_ARGISNULL(0))
804 : : {
805 : 94 : Oid arg_type = get_fn_expr_argtype(fcinfo->flinfo, 1);
806 : :
807 [ - + ]: 94 : if (arg_type == InvalidOid)
808 [ # # ]: 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 : : */
818 : 94 : oldcontext = MemoryContextSwitchTo(aggcontext);
819 : 94 : state = palloc_object(JsonAggState);
820 : 94 : state->str = makeStringInfo();
821 : 94 : MemoryContextSwitchTo(oldcontext);
822 : :
823 : 94 : appendStringInfoChar(state->str, '[');
824 : 94 : json_categorize_type(arg_type, false, &state->val_category,
825 : : &state->val_output_func);
826 : : }
827 : : else
828 : : {
829 : 290 : state = (JsonAggState *) PG_GETARG_POINTER(0);
830 : : }
831 : :
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 */
839 [ + + ]: 324 : if (PG_ARGISNULL(1))
840 : : {
841 : 36 : datum_to_json_internal((Datum) 0, true, state->str, JSONTYPE_NULL,
842 : : InvalidOid, false);
843 : 36 : PG_RETURN_POINTER(state);
844 : : }
845 : :
846 : 288 : val = PG_GETARG_DATUM(1);
847 : :
848 : : /* add some whitespace if structured type and not first item */
849 [ + + + + ]: 288 : if (!PG_ARGISNULL(0) && state->str->len > 1 &&
850 [ + + ]: 206 : (state->val_category == JSONTYPE_ARRAY ||
851 [ + + ]: 202 : state->val_category == JSONTYPE_COMPOSITE))
852 : : {
853 : 74 : appendStringInfoString(state->str, "\n ");
854 : : }
855 : :
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 : : */
864 : 288 : PG_RETURN_POINTER(state);
865 : : }
866 : :
867 : :
868 : : /*
869 : : * json_agg aggregate function
870 : : */
871 : : Datum
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
890 : 121 : json_agg_finalfn(PG_FUNCTION_ARGS)
891 : : {
892 : : JsonAggState *state;
893 : :
894 : : /* cannot be called directly because of internal-type argument */
895 : : Assert(AggCheckCallContext(fcinfo, NULL));
896 : :
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 */
902 [ + + ]: 121 : if (state == NULL)
903 : 27 : PG_RETURN_NULL();
904 : :
905 : : /* Else return state with appropriate array terminator added */
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
911 : 1226 : json_unique_hash(const void *key, Size keysize)
912 : : {
913 : 1226 : const JsonUniqueHashEntry *entry = (const JsonUniqueHashEntry *) key;
914 : 1226 : uint32 hash = hash_bytes_uint32(entry->object_id);
915 : :
916 : 1226 : hash ^= hash_bytes((const unsigned char *) entry->key, entry->key_len);
917 : :
918 : 1226 : return hash;
919 : : }
920 : :
921 : : static int
922 : 94 : json_unique_hash_match(const void *key1, const void *key2, Size keysize)
923 : : {
924 : 94 : const JsonUniqueHashEntry *entry1 = (const JsonUniqueHashEntry *) key1;
925 : 94 : const JsonUniqueHashEntry *entry2 = (const JsonUniqueHashEntry *) key2;
926 : :
927 [ - + ]: 94 : if (entry1->object_id != entry2->object_id)
928 [ # # ]: 0 : return entry1->object_id > entry2->object_id ? 1 : -1;
929 : :
930 [ - + ]: 94 : if (entry1->key_len != entry2->key_len)
931 [ # # ]: 0 : return entry1->key_len > entry2->key_len ? 1 : -1;
932 : :
933 : 94 : 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 : 238 : json_unique_check_init(JsonUniqueCheckState *cxt)
944 : : {
945 : : HASHCTL ctl;
946 : :
947 : 238 : memset(&ctl, 0, sizeof(ctl));
948 : 238 : ctl.keysize = sizeof(JsonUniqueHashEntry);
949 : 238 : ctl.entrysize = sizeof(JsonUniqueHashEntry);
950 : 238 : ctl.hcxt = CurrentMemoryContext;
951 : 238 : ctl.hash = json_unique_hash;
952 : 238 : ctl.match = json_unique_hash_match;
953 : :
954 : 238 : *cxt = hash_create("json object hashtable",
955 : : 32,
956 : : &ctl,
957 : : HASH_ELEM | HASH_CONTEXT | HASH_FUNCTION | HASH_COMPARE);
958 : 238 : }
959 : :
960 : : static void
961 : 70 : json_unique_builder_init(JsonUniqueBuilderState *cxt)
962 : : {
963 : 70 : json_unique_check_init(&cxt->check);
964 : 70 : cxt->mcxt = CurrentMemoryContext;
965 : 70 : cxt->skipped_keys.data = NULL;
966 : 70 : }
967 : :
968 : : static bool
969 : 1226 : json_unique_check_key(JsonUniqueCheckState *cxt, const char *key, int object_id)
970 : : {
971 : : JsonUniqueHashEntry entry;
972 : : bool found;
973 : :
974 : 1226 : entry.key = key;
975 : 1226 : entry.key_len = strlen(key);
976 : 1226 : entry.object_id = object_id;
977 : :
978 : 1226 : (void) hash_search(*cxt, &entry, HASH_ENTER, &found);
979 : :
980 : 1226 : 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 : :
1024 [ - + ]: 1135 : if (!AggCheckCallContext(fcinfo, &aggcontext))
1025 : : {
1026 : : /* cannot be called directly because of internal-type argument */
1027 [ # # ]: 0 : elog(ERROR, "json_object_agg_transfn called in non-aggregate context");
1028 : : }
1029 : :
1030 [ + + ]: 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);
1041 : 117 : state = palloc_object(JsonAggState);
1042 : 117 : state->str = makeStringInfo();
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));
1047 : 117 : MemoryContextSwitchTo(oldcontext);
1048 : :
1049 : 117 : arg_type = get_fn_expr_argtype(fcinfo->flinfo, 1);
1050 : :
1051 [ - + ]: 117 : if (arg_type == InvalidOid)
1052 [ # # ]: 0 : ereport(ERROR,
1053 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1054 : : errmsg("could not determine data type for argument %d", 1)));
1055 : :
1056 : 117 : json_categorize_type(arg_type, false, &state->key_category,
1057 : : &state->key_output_func);
1058 : :
1059 : 117 : arg_type = get_fn_expr_argtype(fcinfo->flinfo, 2);
1060 : :
1061 [ - + ]: 117 : if (arg_type == InvalidOid)
1062 [ # # ]: 0 : ereport(ERROR,
1063 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1064 : : errmsg("could not determine data type for argument %d", 2)));
1065 : :
1066 : 117 : json_categorize_type(arg_type, false, &state->val_category,
1067 : : &state->val_output_func);
1068 : :
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 : :
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 */
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 : :
1116 : 1107 : arg = PG_GETARG_DATUM(1);
1117 : :
1118 : 1107 : key_offset = out->len;
1119 : :
1120 : 1107 : datum_to_json_internal(arg, false, out, state->key_category,
1121 : : state->key_output_func, true);
1122 : :
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 : : */
1131 : 960 : const char *key = MemoryContextStrdup(aggcontext,
1132 : 960 : &out->data[key_offset]);
1133 : :
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 : :
1143 : 1023 : appendStringInfoString(state->str, " : ");
1144 : :
1145 [ + + ]: 1023 : if (PG_ARGISNULL(2))
1146 : 52 : arg = (Datum) 0;
1147 : : else
1148 : 971 : arg = PG_GETARG_DATUM(2);
1149 : :
1150 : 1023 : datum_to_json_internal(arg, PG_ARGISNULL(2), state->str,
1151 : : state->val_category,
1152 : : state->val_output_func, false);
1153 : :
1154 : 1023 : PG_RETURN_POINTER(state);
1155 : : }
1156 : :
1157 : : /*
1158 : : * json_object_agg aggregate function
1159 : : */
1160 : : Datum
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
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 : : Assert(AggCheckCallContext(fcinfo, NULL));
1203 : :
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 */
1207 [ + + ]: 177 : if (state == NULL)
1208 : 8 : PG_RETURN_NULL();
1209 : :
1210 : : /* Else return state with appropriate object terminator added */
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 *
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
1235 : 317 : 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;
1239 : 317 : const char *sep = "";
1240 : : StringInfo result;
1241 : : JsonUniqueBuilderState unique_check;
1242 : :
1243 [ + + ]: 317 : 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 : 305 : result = makeStringInfo();
1252 : :
1253 : 305 : appendStringInfoChar(result, '{');
1254 : :
1255 [ + + ]: 305 : if (unique_keys)
1256 : 22 : json_unique_builder_init(&unique_check);
1257 : :
1258 [ + + ]: 645 : 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 */
1265 [ + + + + ]: 402 : skip = absent_on_null && nulls[i + 1];
1266 : :
1267 [ + + ]: 402 : if (skip)
1268 : : {
1269 : : /* If key uniqueness check is needed we must save skipped keys */
1270 [ + + ]: 18 : if (!unique_keys)
1271 : 10 : continue;
1272 : :
1273 : 8 : out = json_unique_builder_get_throwawaybuf(&unique_check);
1274 : : }
1275 : : else
1276 : : {
1277 : 384 : appendStringInfoString(result, sep);
1278 : 384 : sep = ", ";
1279 : 384 : out = result;
1280 : : }
1281 : :
1282 : : /* process key */
1283 [ + + ]: 392 : if (nulls[i])
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 */
1289 : 376 : key_offset = out->len;
1290 : :
1291 : 376 : add_json(args[i], false, out, types[i], true);
1292 : :
1293 [ + + ]: 352 : 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 : : */
1303 : 64 : const char *key = pstrdup(&out->data[key_offset]);
1304 : :
1305 [ + + ]: 64 : if (!json_unique_check_key(&unique_check.check, key, 0))
1306 [ + - ]: 22 : ereport(ERROR,
1307 : : errcode(ERRCODE_DUPLICATE_JSON_OBJECT_KEY_VALUE),
1308 : : errmsg("duplicate JSON object key value: %s", key));
1309 : :
1310 [ + + ]: 42 : if (skip)
1311 : 4 : continue;
1312 : : }
1313 : :
1314 : 326 : appendStringInfoString(result, " : ");
1315 : :
1316 : : /* process value */
1317 : 326 : add_json(args[i + 1], nulls[i + 1], result, types[i + 1], false);
1318 : : }
1319 : :
1320 : 243 : appendStringInfoChar(result, '}');
1321 : :
1322 : 243 : 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
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
1355 : 155 : json_build_array_worker(int nargs, const Datum *args, const bool *nulls, const Oid *types,
1356 : : bool absent_on_null)
1357 : : {
1358 : : int i;
1359 : 155 : const char *sep = "";
1360 : : StringInfoData result;
1361 : :
1362 : 155 : initStringInfo(&result);
1363 : :
1364 : 155 : appendStringInfoChar(&result, '[');
1365 : :
1366 [ + + ]: 427 : for (i = 0; i < nargs; i++)
1367 : : {
1368 [ + + + + ]: 272 : if (absent_on_null && nulls[i])
1369 : 12 : continue;
1370 : :
1371 : 260 : appendStringInfoString(&result, sep);
1372 : 260 : sep = ", ";
1373 : 260 : add_json(args[i], nulls[i], &result, types[i], false);
1374 : : }
1375 : :
1376 : 155 : appendStringInfoChar(&result, ']');
1377 : :
1378 : 155 : 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
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
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 : :
1455 : 14 : deconstruct_array_builtin(in_array, TEXTOID, &in_datums, &in_nulls, &in_count);
1456 : :
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])
1466 [ # # ]: 0 : ereport(ERROR,
1467 : : (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1468 : : errmsg("null value not allowed for object key")));
1469 : :
1470 [ + + ]: 1240 : if (i > 0)
1471 : 1226 : appendStringInfoString(&result, ", ");
1472 : 1240 : escape_json_text(&result, (text *) DatumGetPointer(in_datums[i * 2]));
1473 : 1240 : appendStringInfoString(&result, " : ");
1474 [ + + ]: 1240 : if (in_nulls[i * 2 + 1])
1475 : 10 : appendStringInfoString(&result, "null");
1476 : : else
1477 : : {
1478 : 1230 : escape_json_text(&result,
1479 : 1230 : (text *) DatumGetPointer(in_datums[i * 2 + 1]));
1480 : : }
1481 : : }
1482 : :
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 : :
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 : :
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, ", ");
1546 : 48 : escape_json_text(&result, (text *) DatumGetPointer(key_datums[i]));
1547 : 48 : appendStringInfoString(&result, " : ");
1548 [ - + ]: 48 : if (val_nulls[i])
1549 : 0 : appendStringInfoString(&result, "null");
1550 : : else
1551 : 48 : escape_json_text(&result,
1552 : 48 : (text *) DatumGetPointer(val_datums[i]));
1553 : : }
1554 : :
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
1573 : 2716044 : escape_json_char(StringInfo buf, char c)
1574 : : {
1575 [ + + + + : 2716044 : 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 : 2715060 : default:
1599 [ + + ]: 2715060 : if ((unsigned char) c < ' ')
1600 : 4 : appendStringInfo(buf, "\\u%04x", (int) c);
1601 : : else
1602 [ + + ]: 2715056 : appendStringInfoCharMacro(buf, c);
1603 : 2715060 : break;
1604 : : }
1605 : 2716044 : }
1606 : :
1607 : : /*
1608 : : * escape_json
1609 : : * Produce a JSON string literal, properly escaping the NUL-terminated
1610 : : * cstring.
1611 : : */
1612 : : void
1613 : 26759 : escape_json(StringInfo buf, const char *str)
1614 : : {
1615 [ + + ]: 26759 : appendStringInfoCharMacro(buf, '"');
1616 : :
1617 [ + + ]: 358458 : for (; *str != '\0'; str++)
1618 : 331699 : escape_json_char(buf, *str);
1619 : :
1620 [ + + ]: 26759 : appendStringInfoCharMacro(buf, '"');
1621 : 26759 : }
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 : 239148 : escape_json_with_len(StringInfo buf, const char *str, int len)
1643 : : {
1644 : : int vlen;
1645 : :
1646 : : 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 : 239148 : 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 : 239148 : vlen = len & (int) (~(sizeof(Vector8) - 1));
1660 : :
1661 [ - + ]: 239148 : appendStringInfoCharMacro(buf, '"');
1662 : :
1663 : 239148 : 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 [ + + ]: 258707 : for (; i < vlen; i += sizeof(Vector8))
1676 : : {
1677 : : Vector8 chunk;
1678 : :
1679 : 19559 : 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 [ + + + + ]: 39070 : if (vector8_has_le(chunk, (unsigned char) 0x1F) ||
1686 [ + + ]: 39006 : vector8_has(chunk, (unsigned char) '"') ||
1687 : 19495 : 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 [ + + ]: 19471 : 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 [ + + ]: 239236 : if (copypos < i)
1711 : : {
1712 : 17719 : appendBinaryStringInfo(buf, &str[copypos], i - copypos);
1713 : 17719 : copypos = i;
1714 : : }
1715 : :
1716 : : /*
1717 : : * Per-byte loop for Vector8s containing special chars and for
1718 : : * processing the tail of the string.
1719 : : */
1720 [ + + ]: 2623581 : for (size_t b = 0; b < sizeof(Vector8); b++)
1721 : : {
1722 : : /* check if we've finished */
1723 [ + + ]: 2623493 : if (i == len)
1724 : 239148 : goto done;
1725 : :
1726 : : Assert(i < len);
1727 : :
1728 : 2384345 : 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 : 239148 : done:
1736 [ - + ]: 239148 : appendStringInfoCharMacro(buf, '"');
1737 : 239148 : }
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 : 3630 : escape_json_text(StringInfo buf, const text *txt)
1748 : : {
1749 : : /* must cast away the const, unfortunately */
1750 : 3630 : text *tunpacked = pg_detoast_datum_packed(unconstify(text *, txt));
1751 : 3630 : int len = VARSIZE_ANY_EXHDR(tunpacked);
1752 : : char *str;
1753 : :
1754 : 3630 : str = VARDATA_ANY(tunpacked);
1755 : :
1756 : 3630 : escape_json_with_len(buf, str, len);
1757 : :
1758 : : /* pfree any detoasted values */
1759 [ - + ]: 3630 : if (tunpacked != txt)
1760 : 0 : pfree(tunpacked);
1761 : 3630 : }
1762 : :
1763 : : /* Semantic actions for key uniqueness check */
1764 : : static JsonParseErrorType
1765 : 134 : json_unique_object_start(void *_state)
1766 : : {
1767 : 134 : JsonUniqueParsingState *state = _state;
1768 : : JsonUniqueStackEntry *entry;
1769 : :
1770 [ - + ]: 134 : if (!state->unique)
1771 : 0 : return JSON_SUCCESS;
1772 : :
1773 : : /* push object entry to stack */
1774 : 134 : entry = palloc_object(JsonUniqueStackEntry);
1775 : 134 : entry->object_id = state->id_counter++;
1776 : 134 : entry->parent = state->stack;
1777 : 134 : state->stack = entry;
1778 : :
1779 : 134 : return JSON_SUCCESS;
1780 : : }
1781 : :
1782 : : static JsonParseErrorType
1783 : 130 : json_unique_object_end(void *_state)
1784 : : {
1785 : 130 : JsonUniqueParsingState *state = _state;
1786 : : JsonUniqueStackEntry *entry;
1787 : :
1788 [ + + ]: 130 : if (!state->unique)
1789 : 58 : 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 : 202 : json_unique_object_field_start(void *_state, char *field, bool isnull)
1799 : : {
1800 : 202 : JsonUniqueParsingState *state = _state;
1801 : : JsonUniqueStackEntry *entry;
1802 : :
1803 [ - + ]: 202 : if (!state->unique)
1804 : 0 : return JSON_SUCCESS;
1805 : :
1806 : : /* find key collision in the current object */
1807 [ + + ]: 202 : if (json_unique_check_key(&state->check, field, state->stack->object_id))
1808 : 158 : return JSON_SUCCESS;
1809 : :
1810 : 44 : state->unique = false;
1811 : :
1812 : : /* pop all objects entries */
1813 [ + + ]: 102 : while ((entry = state->stack))
1814 : : {
1815 : 58 : state->stack = entry->parent;
1816 : 58 : pfree(entry);
1817 : : }
1818 : 44 : return JSON_SUCCESS;
1819 : : }
1820 : :
1821 : : /* Validate JSON text and additionally check key uniqueness */
1822 : : bool
1823 : 902 : json_validate(text *json, bool check_unique_keys, bool throw_error)
1824 : : {
1825 : : JsonLexContext lex;
1826 : 902 : JsonSemAction uniqueSemAction = {0};
1827 : : JsonUniqueParsingState state;
1828 : : JsonParseErrorType result;
1829 : :
1830 : 902 : makeJsonLexContext(&lex, json, check_unique_keys);
1831 : :
1832 [ + + ]: 902 : if (check_unique_keys)
1833 : : {
1834 : 168 : state.lex = &lex;
1835 : 168 : state.stack = NULL;
1836 : 168 : state.id_counter = 0;
1837 : 168 : state.unique = true;
1838 : 168 : json_unique_check_init(&state.check);
1839 : :
1840 : 168 : uniqueSemAction.semstate = &state;
1841 : 168 : uniqueSemAction.object_start = json_unique_object_start;
1842 : 168 : uniqueSemAction.object_field_start = json_unique_object_field_start;
1843 : 168 : uniqueSemAction.object_end = json_unique_object_end;
1844 : : }
1845 : :
1846 [ + + ]: 902 : result = pg_parse_json(&lex, check_unique_keys ? &uniqueSemAction : &nullSemAction);
1847 : :
1848 [ + + ]: 902 : if (result != JSON_SUCCESS)
1849 : : {
1850 [ - + ]: 144 : if (throw_error)
1851 : 0 : json_errsave_error(result, &lex, NULL);
1852 : :
1853 : 144 : return false; /* invalid json */
1854 : : }
1855 : :
1856 [ + + + + ]: 758 : if (check_unique_keys && !state.unique)
1857 : : {
1858 [ + + ]: 44 : if (throw_error)
1859 [ + - ]: 6 : ereport(ERROR,
1860 : : (errcode(ERRCODE_DUPLICATE_JSON_OBJECT_KEY_VALUE),
1861 : : errmsg("duplicate JSON object key value")));
1862 : :
1863 : 38 : return false; /* not unique keys */
1864 : : }
1865 : :
1866 [ + + ]: 714 : if (check_unique_keys)
1867 : 108 : freeJsonLexContext(&lex);
1868 : :
1869 : 714 : 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
1885 : 40 : json_typeof(PG_FUNCTION_ARGS)
1886 : : {
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. */
1893 : 40 : makeJsonLexContext(&lex, json, false);
1894 : 40 : result = json_lex(&lex);
1895 [ - + ]: 40 : if (result != JSON_SUCCESS)
1896 : 0 : json_errsave_error(result, &lex, NULL);
1897 : :
1898 [ + + + + : 40 : switch (lex.token_type)
+ + - ]
1899 : : {
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;
1919 : 0 : default:
1920 [ # # ]: 0 : elog(ERROR, "unexpected json token: %d", lex.token_type);
1921 : : }
1922 : :
1923 : 40 : PG_RETURN_TEXT_P(cstring_to_text(type));
1924 : : }
|