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