PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
jsonb.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * jsonb.c
4  * I/O routines for jsonb type
5  *
6  * Copyright (c) 2014-2017, PostgreSQL Global Development Group
7  *
8  * IDENTIFICATION
9  * src/backend/utils/adt/jsonb.c
10  *
11  *-------------------------------------------------------------------------
12  */
13 #include "postgres.h"
14 
15 #include "miscadmin.h"
16 #include "access/htup_details.h"
17 #include "access/transam.h"
18 #include "catalog/pg_type.h"
19 #include "libpq/pqformat.h"
20 #include "parser/parse_coerce.h"
21 #include "utils/builtins.h"
22 #include "utils/date.h"
23 #include "utils/datetime.h"
24 #include "utils/lsyscache.h"
25 #include "utils/json.h"
26 #include "utils/jsonapi.h"
27 #include "utils/jsonb.h"
28 #include "utils/syscache.h"
29 #include "utils/typcache.h"
30 
31 typedef struct JsonbInState
32 {
35 } JsonbInState;
36 
37 /* unlike with json categories, we need to treat json and jsonb differently */
38 typedef enum /* type categories for datum_to_jsonb */
39 {
40  JSONBTYPE_NULL, /* null, so we didn't bother to identify */
41  JSONBTYPE_BOOL, /* boolean (built-in types only) */
42  JSONBTYPE_NUMERIC, /* numeric (ditto) */
43  JSONBTYPE_DATE, /* we use special formatting for datetimes */
44  JSONBTYPE_TIMESTAMP, /* we use special formatting for timestamp */
45  JSONBTYPE_TIMESTAMPTZ, /* ... and timestamptz */
46  JSONBTYPE_JSON, /* JSON */
47  JSONBTYPE_JSONB, /* JSONB */
48  JSONBTYPE_ARRAY, /* array */
49  JSONBTYPE_COMPOSITE, /* composite */
50  JSONBTYPE_JSONCAST, /* something with an explicit cast to JSON */
51  JSONBTYPE_OTHER /* all else */
53 
54 typedef struct JsonbAggState
55 {
62 
63 static inline Datum jsonb_from_cstring(char *json, int len);
64 static size_t checkStringLen(size_t len);
65 static void jsonb_in_object_start(void *pstate);
66 static void jsonb_in_object_end(void *pstate);
67 static void jsonb_in_array_start(void *pstate);
68 static void jsonb_in_array_end(void *pstate);
69 static void jsonb_in_object_field_start(void *pstate, char *fname, bool isnull);
70 static void jsonb_put_escaped_value(StringInfo out, JsonbValue *scalarVal);
71 static void jsonb_in_scalar(void *pstate, char *token, JsonTokenType tokentype);
72 static void jsonb_categorize_type(Oid typoid,
73  JsonbTypeCategory *tcategory,
74  Oid *outfuncoid);
75 static void composite_to_jsonb(Datum composite, JsonbInState *result);
76 static void array_dim_to_jsonb(JsonbInState *result, int dim, int ndims, int *dims,
77  Datum *vals, bool *nulls, int *valcount,
78  JsonbTypeCategory tcategory, Oid outfuncoid);
79 static void array_to_jsonb_internal(Datum array, JsonbInState *result);
80 static void jsonb_categorize_type(Oid typoid,
81  JsonbTypeCategory *tcategory,
82  Oid *outfuncoid);
83 static void datum_to_jsonb(Datum val, bool is_null, JsonbInState *result,
84  JsonbTypeCategory tcategory, Oid outfuncoid,
85  bool key_scalar);
86 static void add_jsonb(Datum val, bool is_null, JsonbInState *result,
87  Oid val_type, bool key_scalar);
89 static char *JsonbToCStringWorker(StringInfo out, JsonbContainer *in, int estimated_len, bool indent);
90 static void add_indent(StringInfo out, bool indent, int level);
91 
92 /*
93  * jsonb type input function
94  */
95 Datum
97 {
98  char *json = PG_GETARG_CSTRING(0);
99 
100  return jsonb_from_cstring(json, strlen(json));
101 }
102 
103 /*
104  * jsonb type recv function
105  *
106  * The type is sent as text in binary mode, so this is almost the same
107  * as the input function, but it's prefixed with a version number so we
108  * can change the binary format sent in future if necessary. For now,
109  * only version 1 is supported.
110  */
111 Datum
113 {
115  int version = pq_getmsgint(buf, 1);
116  char *str;
117  int nbytes;
118 
119  if (version == 1)
120  str = pq_getmsgtext(buf, buf->len - buf->cursor, &nbytes);
121  else
122  elog(ERROR, "unsupported jsonb version number %d", version);
123 
124  return jsonb_from_cstring(str, nbytes);
125 }
126 
127 /*
128  * jsonb type output function
129  */
130 Datum
132 {
133  Jsonb *jb = PG_GETARG_JSONB(0);
134  char *out;
135 
136  out = JsonbToCString(NULL, &jb->root, VARSIZE(jb));
137 
138  PG_RETURN_CSTRING(out);
139 }
140 
141 /*
142  * jsonb type send function
143  *
144  * Just send jsonb as a version number, then a string of text
145  */
146 Datum
148 {
149  Jsonb *jb = PG_GETARG_JSONB(0);
151  StringInfo jtext = makeStringInfo();
152  int version = 1;
153 
154  (void) JsonbToCString(jtext, &jb->root, VARSIZE(jb));
155 
156  pq_begintypsend(&buf);
157  pq_sendint(&buf, version, 1);
158  pq_sendtext(&buf, jtext->data, jtext->len);
159  pfree(jtext->data);
160  pfree(jtext);
161 
163 }
164 
165 /*
166  * SQL function jsonb_typeof(jsonb) -> text
167  *
168  * This function is here because the analog json function is in json.c, since
169  * it uses the json parser internals not exposed elsewhere.
170  */
171 Datum
173 {
174  Jsonb *in = PG_GETARG_JSONB(0);
175  JsonbIterator *it;
176  JsonbValue v;
177  char *result;
178 
179  if (JB_ROOT_IS_OBJECT(in))
180  result = "object";
181  else if (JB_ROOT_IS_ARRAY(in) && !JB_ROOT_IS_SCALAR(in))
182  result = "array";
183  else
184  {
186 
187  it = JsonbIteratorInit(&in->root);
188 
189  /*
190  * A root scalar is stored as an array of one element, so we get the
191  * array and then its first (and only) member.
192  */
193  (void) JsonbIteratorNext(&it, &v, true);
194  Assert(v.type == jbvArray);
195  (void) JsonbIteratorNext(&it, &v, true);
196  switch (v.type)
197  {
198  case jbvNull:
199  result = "null";
200  break;
201  case jbvString:
202  result = "string";
203  break;
204  case jbvNumeric:
205  result = "number";
206  break;
207  case jbvBool:
208  result = "boolean";
209  break;
210  default:
211  elog(ERROR, "unknown jsonb scalar type");
212  }
213  }
214 
216 }
217 
218 /*
219  * jsonb_from_cstring
220  *
221  * Turns json string into a jsonb Datum.
222  *
223  * Uses the json parser (with hooks) to construct a jsonb.
224  */
225 static inline Datum
226 jsonb_from_cstring(char *json, int len)
227 {
228  JsonLexContext *lex;
230  JsonSemAction sem;
231 
232  memset(&state, 0, sizeof(state));
233  memset(&sem, 0, sizeof(sem));
234  lex = makeJsonLexContextCstringLen(json, len, true);
235 
236  sem.semstate = (void *) &state;
237 
242  sem.scalar = jsonb_in_scalar;
244 
245  pg_parse_json(lex, &sem);
246 
247  /* after parsing, the item member has the composed jsonb structure */
249 }
250 
251 static size_t
252 checkStringLen(size_t len)
253 {
254  if (len > JENTRY_OFFLENMASK)
255  ereport(ERROR,
256  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
257  errmsg("string too long to represent as jsonb string"),
258  errdetail("Due to an implementation restriction, jsonb strings cannot exceed %d bytes.",
260 
261  return len;
262 }
263 
264 static void
266 {
267  JsonbInState *_state = (JsonbInState *) pstate;
268 
269  _state->res = pushJsonbValue(&_state->parseState, WJB_BEGIN_OBJECT, NULL);
270 }
271 
272 static void
273 jsonb_in_object_end(void *pstate)
274 {
275  JsonbInState *_state = (JsonbInState *) pstate;
276 
277  _state->res = pushJsonbValue(&_state->parseState, WJB_END_OBJECT, NULL);
278 }
279 
280 static void
281 jsonb_in_array_start(void *pstate)
282 {
283  JsonbInState *_state = (JsonbInState *) pstate;
284 
285  _state->res = pushJsonbValue(&_state->parseState, WJB_BEGIN_ARRAY, NULL);
286 }
287 
288 static void
289 jsonb_in_array_end(void *pstate)
290 {
291  JsonbInState *_state = (JsonbInState *) pstate;
292 
293  _state->res = pushJsonbValue(&_state->parseState, WJB_END_ARRAY, NULL);
294 }
295 
296 static void
297 jsonb_in_object_field_start(void *pstate, char *fname, bool isnull)
298 {
299  JsonbInState *_state = (JsonbInState *) pstate;
300  JsonbValue v;
301 
302  Assert(fname != NULL);
303  v.type = jbvString;
304  v.val.string.len = checkStringLen(strlen(fname));
305  v.val.string.val = fname;
306 
307  _state->res = pushJsonbValue(&_state->parseState, WJB_KEY, &v);
308 }
309 
310 static void
312 {
313  switch (scalarVal->type)
314  {
315  case jbvNull:
316  appendBinaryStringInfo(out, "null", 4);
317  break;
318  case jbvString:
319  escape_json(out, pnstrdup(scalarVal->val.string.val, scalarVal->val.string.len));
320  break;
321  case jbvNumeric:
324  PointerGetDatum(scalarVal->val.numeric))));
325  break;
326  case jbvBool:
327  if (scalarVal->val.boolean)
328  appendBinaryStringInfo(out, "true", 4);
329  else
330  appendBinaryStringInfo(out, "false", 5);
331  break;
332  default:
333  elog(ERROR, "unknown jsonb scalar type");
334  }
335 }
336 
337 /*
338  * For jsonb we always want the de-escaped value - that's what's in token
339  */
340 static void
341 jsonb_in_scalar(void *pstate, char *token, JsonTokenType tokentype)
342 {
343  JsonbInState *_state = (JsonbInState *) pstate;
344  JsonbValue v;
345 
346  switch (tokentype)
347  {
348 
349  case JSON_TOKEN_STRING:
350  Assert(token != NULL);
351  v.type = jbvString;
352  v.val.string.len = checkStringLen(strlen(token));
353  v.val.string.val = token;
354  break;
355  case JSON_TOKEN_NUMBER:
356 
357  /*
358  * No need to check size of numeric values, because maximum
359  * numeric size is well below the JsonbValue restriction
360  */
361  Assert(token != NULL);
362  v.type = jbvNumeric;
364 
365  break;
366  case JSON_TOKEN_TRUE:
367  v.type = jbvBool;
368  v.val.boolean = true;
369 
370  break;
371  case JSON_TOKEN_FALSE:
372  v.type = jbvBool;
373  v.val.boolean = false;
374 
375  break;
376  case JSON_TOKEN_NULL:
377  v.type = jbvNull;
378  break;
379  default:
380  /* should not be possible */
381  elog(ERROR, "invalid json token type");
382  break;
383  }
384 
385  if (_state->parseState == NULL)
386  {
387  /* single scalar */
388  JsonbValue va;
389 
390  va.type = jbvArray;
391  va.val.array.rawScalar = true;
392  va.val.array.nElems = 1;
393 
394  _state->res = pushJsonbValue(&_state->parseState, WJB_BEGIN_ARRAY, &va);
395  _state->res = pushJsonbValue(&_state->parseState, WJB_ELEM, &v);
396  _state->res = pushJsonbValue(&_state->parseState, WJB_END_ARRAY, NULL);
397  }
398  else
399  {
400  JsonbValue *o = &_state->parseState->contVal;
401 
402  switch (o->type)
403  {
404  case jbvArray:
405  _state->res = pushJsonbValue(&_state->parseState, WJB_ELEM, &v);
406  break;
407  case jbvObject:
408  _state->res = pushJsonbValue(&_state->parseState, WJB_VALUE, &v);
409  break;
410  default:
411  elog(ERROR, "unexpected parent of nested structure");
412  }
413  }
414 }
415 
416 /*
417  * JsonbToCString
418  * Converts jsonb value to a C-string.
419  *
420  * If 'out' argument is non-null, the resulting C-string is stored inside the
421  * StringBuffer. The resulting string is always returned.
422  *
423  * A typical case for passing the StringInfo in rather than NULL is where the
424  * caller wants access to the len attribute without having to call strlen, e.g.
425  * if they are converting it to a text* object.
426  */
427 char *
428 JsonbToCString(StringInfo out, JsonbContainer *in, int estimated_len)
429 {
430  return JsonbToCStringWorker(out, in, estimated_len, false);
431 }
432 
433 /*
434  * same thing but with indentation turned on
435  */
436 char *
437 JsonbToCStringIndent(StringInfo out, JsonbContainer *in, int estimated_len)
438 {
439  return JsonbToCStringWorker(out, in, estimated_len, true);
440 }
441 
442 /*
443  * common worker for above two functions
444  */
445 static char *
446 JsonbToCStringWorker(StringInfo out, JsonbContainer *in, int estimated_len, bool indent)
447 {
448  bool first = true;
449  JsonbIterator *it;
450  JsonbValue v;
452  int level = 0;
453  bool redo_switch = false;
454 
455  /* If we are indenting, don't add a space after a comma */
456  int ispaces = indent ? 1 : 2;
457 
458  /*
459  * Don't indent the very first item. This gets set to the indent flag at
460  * the bottom of the loop.
461  */
462  bool use_indent = false;
463  bool raw_scalar = false;
464  bool last_was_key = false;
465 
466  if (out == NULL)
467  out = makeStringInfo();
468 
469  enlargeStringInfo(out, (estimated_len >= 0) ? estimated_len : 64);
470 
471  it = JsonbIteratorInit(in);
472 
473  while (redo_switch ||
474  ((type = JsonbIteratorNext(&it, &v, false)) != WJB_DONE))
475  {
476  redo_switch = false;
477  switch (type)
478  {
479  case WJB_BEGIN_ARRAY:
480  if (!first)
481  appendBinaryStringInfo(out, ", ", ispaces);
482 
483  if (!v.val.array.rawScalar)
484  {
485  add_indent(out, use_indent && !last_was_key, level);
486  appendStringInfoCharMacro(out, '[');
487  }
488  else
489  raw_scalar = true;
490 
491  first = true;
492  level++;
493  break;
494  case WJB_BEGIN_OBJECT:
495  if (!first)
496  appendBinaryStringInfo(out, ", ", ispaces);
497 
498  add_indent(out, use_indent && !last_was_key, level);
499  appendStringInfoCharMacro(out, '{');
500 
501  first = true;
502  level++;
503  break;
504  case WJB_KEY:
505  if (!first)
506  appendBinaryStringInfo(out, ", ", ispaces);
507  first = true;
508 
509  add_indent(out, use_indent, level);
510 
511  /* json rules guarantee this is a string */
512  jsonb_put_escaped_value(out, &v);
513  appendBinaryStringInfo(out, ": ", 2);
514 
515  type = JsonbIteratorNext(&it, &v, false);
516  if (type == WJB_VALUE)
517  {
518  first = false;
519  jsonb_put_escaped_value(out, &v);
520  }
521  else
522  {
523  Assert(type == WJB_BEGIN_OBJECT || type == WJB_BEGIN_ARRAY);
524 
525  /*
526  * We need to rerun the current switch() since we need to
527  * output the object which we just got from the iterator
528  * before calling the iterator again.
529  */
530  redo_switch = true;
531  }
532  break;
533  case WJB_ELEM:
534  if (!first)
535  appendBinaryStringInfo(out, ", ", ispaces);
536  first = false;
537 
538  if (!raw_scalar)
539  add_indent(out, use_indent, level);
540  jsonb_put_escaped_value(out, &v);
541  break;
542  case WJB_END_ARRAY:
543  level--;
544  if (!raw_scalar)
545  {
546  add_indent(out, use_indent, level);
547  appendStringInfoCharMacro(out, ']');
548  }
549  first = false;
550  break;
551  case WJB_END_OBJECT:
552  level--;
553  add_indent(out, use_indent, level);
554  appendStringInfoCharMacro(out, '}');
555  first = false;
556  break;
557  default:
558  elog(ERROR, "unknown jsonb iterator token type");
559  }
560  use_indent = indent;
561  last_was_key = redo_switch;
562  }
563 
564  Assert(level == 0);
565 
566  return out->data;
567 }
568 
569 static void
570 add_indent(StringInfo out, bool indent, int level)
571 {
572  if (indent)
573  {
574  int i;
575 
576  appendStringInfoCharMacro(out, '\n');
577  for (i = 0; i < level; i++)
578  appendBinaryStringInfo(out, " ", 4);
579  }
580 }
581 
582 
583 /*
584  * Determine how we want to render values of a given type in datum_to_jsonb.
585  *
586  * Given the datatype OID, return its JsonbTypeCategory, as well as the type's
587  * output function OID. If the returned category is JSONBTYPE_JSONCAST,
588  * we return the OID of the relevant cast function instead.
589  */
590 static void
592  JsonbTypeCategory *tcategory,
593  Oid *outfuncoid)
594 {
595  bool typisvarlena;
596 
597  /* Look through any domain */
598  typoid = getBaseType(typoid);
599 
600  *outfuncoid = InvalidOid;
601 
602  /*
603  * We need to get the output function for everything except date and
604  * timestamp types, booleans, array and composite types, json and jsonb,
605  * and non-builtin types where there's a cast to json. In this last case
606  * we return the oid of the cast function instead.
607  */
608 
609  switch (typoid)
610  {
611  case BOOLOID:
612  *tcategory = JSONBTYPE_BOOL;
613  break;
614 
615  case INT2OID:
616  case INT4OID:
617  case INT8OID:
618  case FLOAT4OID:
619  case FLOAT8OID:
620  case NUMERICOID:
621  getTypeOutputInfo(typoid, outfuncoid, &typisvarlena);
622  *tcategory = JSONBTYPE_NUMERIC;
623  break;
624 
625  case DATEOID:
626  *tcategory = JSONBTYPE_DATE;
627  break;
628 
629  case TIMESTAMPOID:
630  *tcategory = JSONBTYPE_TIMESTAMP;
631  break;
632 
633  case TIMESTAMPTZOID:
634  *tcategory = JSONBTYPE_TIMESTAMPTZ;
635  break;
636 
637  case JSONBOID:
638  *tcategory = JSONBTYPE_JSONB;
639  break;
640 
641  case JSONOID:
642  *tcategory = JSONBTYPE_JSON;
643  break;
644 
645  default:
646  /* Check for arrays and composites */
647  if (OidIsValid(get_element_type(typoid)))
648  *tcategory = JSONBTYPE_ARRAY;
649  else if (type_is_rowtype(typoid))
650  *tcategory = JSONBTYPE_COMPOSITE;
651  else
652  {
653  /* It's probably the general case ... */
654  *tcategory = JSONBTYPE_OTHER;
655 
656  /*
657  * but first let's look for a cast to json (note: not to
658  * jsonb) if it's not built-in.
659  */
660  if (typoid >= FirstNormalObjectId)
661  {
662  Oid castfunc;
663  CoercionPathType ctype;
664 
665  ctype = find_coercion_pathway(JSONOID, typoid,
666  COERCION_EXPLICIT, &castfunc);
667  if (ctype == COERCION_PATH_FUNC && OidIsValid(castfunc))
668  {
669  *tcategory = JSONBTYPE_JSONCAST;
670  *outfuncoid = castfunc;
671  }
672  else
673  {
674  /* not a cast type, so just get the usual output func */
675  getTypeOutputInfo(typoid, outfuncoid, &typisvarlena);
676  }
677  }
678  else
679  {
680  /* any other builtin type */
681  getTypeOutputInfo(typoid, outfuncoid, &typisvarlena);
682  }
683  break;
684  }
685  }
686 }
687 
688 /*
689  * Turn a Datum into jsonb, adding it to the result JsonbInState.
690  *
691  * tcategory and outfuncoid are from a previous call to json_categorize_type,
692  * except that if is_null is true then they can be invalid.
693  *
694  * If key_scalar is true, the value is stored as a key, so insist
695  * it's of an acceptable type, and force it to be a jbvString.
696  */
697 static void
698 datum_to_jsonb(Datum val, bool is_null, JsonbInState *result,
699  JsonbTypeCategory tcategory, Oid outfuncoid,
700  bool key_scalar)
701 {
702  char *outputstr;
703  bool numeric_error;
704  JsonbValue jb;
705  bool scalar_jsonb = false;
706 
708 
709  /* Convert val to a JsonbValue in jb (in most cases) */
710  if (is_null)
711  {
712  Assert(!key_scalar);
713  jb.type = jbvNull;
714  }
715  else if (key_scalar &&
716  (tcategory == JSONBTYPE_ARRAY ||
717  tcategory == JSONBTYPE_COMPOSITE ||
718  tcategory == JSONBTYPE_JSON ||
719  tcategory == JSONBTYPE_JSONB ||
720  tcategory == JSONBTYPE_JSONCAST))
721  {
722  ereport(ERROR,
723  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
724  errmsg("key value must be scalar, not array, composite, or json")));
725  }
726  else
727  {
728  if (tcategory == JSONBTYPE_JSONCAST)
729  val = OidFunctionCall1(outfuncoid, val);
730 
731  switch (tcategory)
732  {
733  case JSONBTYPE_ARRAY:
734  array_to_jsonb_internal(val, result);
735  break;
736  case JSONBTYPE_COMPOSITE:
737  composite_to_jsonb(val, result);
738  break;
739  case JSONBTYPE_BOOL:
740  if (key_scalar)
741  {
742  outputstr = DatumGetBool(val) ? "true" : "false";
743  jb.type = jbvString;
744  jb.val.string.len = strlen(outputstr);
745  jb.val.string.val = outputstr;
746  }
747  else
748  {
749  jb.type = jbvBool;
750  jb.val.boolean = DatumGetBool(val);
751  }
752  break;
753  case JSONBTYPE_NUMERIC:
754  outputstr = OidOutputFunctionCall(outfuncoid, val);
755  if (key_scalar)
756  {
757  /* always quote keys */
758  jb.type = jbvString;
759  jb.val.string.len = strlen(outputstr);
760  jb.val.string.val = outputstr;
761  }
762  else
763  {
764  /*
765  * Make it numeric if it's a valid JSON number, otherwise
766  * a string. Invalid numeric output will always have an
767  * 'N' or 'n' in it (I think).
768  */
769  numeric_error = (strchr(outputstr, 'N') != NULL ||
770  strchr(outputstr, 'n') != NULL);
771  if (!numeric_error)
772  {
773  jb.type = jbvNumeric;
774  jb.val.numeric = DatumGetNumeric(DirectFunctionCall3(numeric_in, CStringGetDatum(outputstr), 0, -1));
775 
776  pfree(outputstr);
777  }
778  else
779  {
780  jb.type = jbvString;
781  jb.val.string.len = strlen(outputstr);
782  jb.val.string.val = outputstr;
783  }
784  }
785  break;
786  case JSONBTYPE_DATE:
787  {
788  DateADT date;
789  struct pg_tm tm;
790  char buf[MAXDATELEN + 1];
791 
792  date = DatumGetDateADT(val);
793  /* Same as date_out(), but forcing DateStyle */
794  if (DATE_NOT_FINITE(date))
795  EncodeSpecialDate(date, buf);
796  else
797  {
799  &(tm.tm_year), &(tm.tm_mon), &(tm.tm_mday));
800  EncodeDateOnly(&tm, USE_XSD_DATES, buf);
801  }
802  jb.type = jbvString;
803  jb.val.string.len = strlen(buf);
804  jb.val.string.val = pstrdup(buf);
805  }
806  break;
807  case JSONBTYPE_TIMESTAMP:
808  {
810  struct pg_tm tm;
811  fsec_t fsec;
812  char buf[MAXDATELEN + 1];
813 
814  timestamp = DatumGetTimestamp(val);
815  /* Same as timestamp_out(), but forcing DateStyle */
816  if (TIMESTAMP_NOT_FINITE(timestamp))
817  EncodeSpecialTimestamp(timestamp, buf);
818  else if (timestamp2tm(timestamp, NULL, &tm, &fsec, NULL, NULL) == 0)
819  EncodeDateTime(&tm, fsec, false, 0, NULL, USE_XSD_DATES, buf);
820  else
821  ereport(ERROR,
822  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
823  errmsg("timestamp out of range")));
824  jb.type = jbvString;
825  jb.val.string.len = strlen(buf);
826  jb.val.string.val = pstrdup(buf);
827  }
828  break;
830  {
832  struct pg_tm tm;
833  int tz;
834  fsec_t fsec;
835  const char *tzn = NULL;
836  char buf[MAXDATELEN + 1];
837 
838  timestamp = DatumGetTimestampTz(val);
839  /* Same as timestamptz_out(), but forcing DateStyle */
840  if (TIMESTAMP_NOT_FINITE(timestamp))
841  EncodeSpecialTimestamp(timestamp, buf);
842  else if (timestamp2tm(timestamp, &tz, &tm, &fsec, &tzn, NULL) == 0)
843  EncodeDateTime(&tm, fsec, true, tz, tzn, USE_XSD_DATES, buf);
844  else
845  ereport(ERROR,
846  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
847  errmsg("timestamp out of range")));
848  jb.type = jbvString;
849  jb.val.string.len = strlen(buf);
850  jb.val.string.val = pstrdup(buf);
851  }
852  break;
853  case JSONBTYPE_JSONCAST:
854  case JSONBTYPE_JSON:
855  {
856  /* parse the json right into the existing result object */
857  JsonLexContext *lex;
858  JsonSemAction sem;
859  text *json = DatumGetTextP(val);
860 
861  lex = makeJsonLexContext(json, true);
862 
863  memset(&sem, 0, sizeof(sem));
864 
865  sem.semstate = (void *) result;
866 
871  sem.scalar = jsonb_in_scalar;
873 
874  pg_parse_json(lex, &sem);
875 
876  }
877  break;
878  case JSONBTYPE_JSONB:
879  {
880  Jsonb *jsonb = DatumGetJsonb(val);
881  JsonbIterator *it;
882 
883  it = JsonbIteratorInit(&jsonb->root);
884 
885  if (JB_ROOT_IS_SCALAR(jsonb))
886  {
887  (void) JsonbIteratorNext(&it, &jb, true);
888  Assert(jb.type == jbvArray);
889  (void) JsonbIteratorNext(&it, &jb, true);
890  scalar_jsonb = true;
891  }
892  else
893  {
894  JsonbIteratorToken type;
895 
896  while ((type = JsonbIteratorNext(&it, &jb, false))
897  != WJB_DONE)
898  {
899  if (type == WJB_END_ARRAY || type == WJB_END_OBJECT ||
900  type == WJB_BEGIN_ARRAY || type == WJB_BEGIN_OBJECT)
901  result->res = pushJsonbValue(&result->parseState,
902  type, NULL);
903  else
904  result->res = pushJsonbValue(&result->parseState,
905  type, &jb);
906  }
907  }
908  }
909  break;
910  default:
911  outputstr = OidOutputFunctionCall(outfuncoid, val);
912  jb.type = jbvString;
913  jb.val.string.len = checkStringLen(strlen(outputstr));
914  jb.val.string.val = outputstr;
915  break;
916  }
917  }
918 
919  /* Now insert jb into result, unless we did it recursively */
920  if (!is_null && !scalar_jsonb &&
921  tcategory >= JSONBTYPE_JSON && tcategory <= JSONBTYPE_JSONCAST)
922  {
923  /* work has been done recursively */
924  return;
925  }
926  else if (result->parseState == NULL)
927  {
928  /* single root scalar */
929  JsonbValue va;
930 
931  va.type = jbvArray;
932  va.val.array.rawScalar = true;
933  va.val.array.nElems = 1;
934 
935  result->res = pushJsonbValue(&result->parseState, WJB_BEGIN_ARRAY, &va);
936  result->res = pushJsonbValue(&result->parseState, WJB_ELEM, &jb);
937  result->res = pushJsonbValue(&result->parseState, WJB_END_ARRAY, NULL);
938  }
939  else
940  {
941  JsonbValue *o = &result->parseState->contVal;
942 
943  switch (o->type)
944  {
945  case jbvArray:
946  result->res = pushJsonbValue(&result->parseState, WJB_ELEM, &jb);
947  break;
948  case jbvObject:
949  result->res = pushJsonbValue(&result->parseState,
950  key_scalar ? WJB_KEY : WJB_VALUE,
951  &jb);
952  break;
953  default:
954  elog(ERROR, "unexpected parent of nested structure");
955  }
956  }
957 }
958 
959 /*
960  * Process a single dimension of an array.
961  * If it's the innermost dimension, output the values, otherwise call
962  * ourselves recursively to process the next dimension.
963  */
964 static void
965 array_dim_to_jsonb(JsonbInState *result, int dim, int ndims, int *dims, Datum *vals,
966  bool *nulls, int *valcount, JsonbTypeCategory tcategory,
967  Oid outfuncoid)
968 {
969  int i;
970 
971  Assert(dim < ndims);
972 
973  result->res = pushJsonbValue(&result->parseState, WJB_BEGIN_ARRAY, NULL);
974 
975  for (i = 1; i <= dims[dim]; i++)
976  {
977  if (dim + 1 == ndims)
978  {
979  datum_to_jsonb(vals[*valcount], nulls[*valcount], result, tcategory,
980  outfuncoid, false);
981  (*valcount)++;
982  }
983  else
984  {
985  array_dim_to_jsonb(result, dim + 1, ndims, dims, vals, nulls,
986  valcount, tcategory, outfuncoid);
987  }
988  }
989 
990  result->res = pushJsonbValue(&result->parseState, WJB_END_ARRAY, NULL);
991 }
992 
993 /*
994  * Turn an array into JSON.
995  */
996 static void
998 {
999  ArrayType *v = DatumGetArrayTypeP(array);
1000  Oid element_type = ARR_ELEMTYPE(v);
1001  int *dim;
1002  int ndim;
1003  int nitems;
1004  int count = 0;
1005  Datum *elements;
1006  bool *nulls;
1007  int16 typlen;
1008  bool typbyval;
1009  char typalign;
1010  JsonbTypeCategory tcategory;
1011  Oid outfuncoid;
1012 
1013  ndim = ARR_NDIM(v);
1014  dim = ARR_DIMS(v);
1015  nitems = ArrayGetNItems(ndim, dim);
1016 
1017  if (nitems <= 0)
1018  {
1019  result->res = pushJsonbValue(&result->parseState, WJB_BEGIN_ARRAY, NULL);
1020  result->res = pushJsonbValue(&result->parseState, WJB_END_ARRAY, NULL);
1021  return;
1022  }
1023 
1024  get_typlenbyvalalign(element_type,
1025  &typlen, &typbyval, &typalign);
1026 
1027  jsonb_categorize_type(element_type,
1028  &tcategory, &outfuncoid);
1029 
1030  deconstruct_array(v, element_type, typlen, typbyval,
1031  typalign, &elements, &nulls,
1032  &nitems);
1033 
1034  array_dim_to_jsonb(result, 0, ndim, dim, elements, nulls, &count, tcategory,
1035  outfuncoid);
1036 
1037  pfree(elements);
1038  pfree(nulls);
1039 }
1040 
1041 /*
1042  * Turn a composite / record into JSON.
1043  */
1044 static void
1046 {
1047  HeapTupleHeader td;
1048  Oid tupType;
1049  int32 tupTypmod;
1050  TupleDesc tupdesc;
1051  HeapTupleData tmptup,
1052  *tuple;
1053  int i;
1054 
1055  td = DatumGetHeapTupleHeader(composite);
1056 
1057  /* Extract rowtype info and find a tupdesc */
1058  tupType = HeapTupleHeaderGetTypeId(td);
1059  tupTypmod = HeapTupleHeaderGetTypMod(td);
1060  tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
1061 
1062  /* Build a temporary HeapTuple control structure */
1063  tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
1064  tmptup.t_data = td;
1065  tuple = &tmptup;
1066 
1067  result->res = pushJsonbValue(&result->parseState, WJB_BEGIN_OBJECT, NULL);
1068 
1069  for (i = 0; i < tupdesc->natts; i++)
1070  {
1071  Datum val;
1072  bool isnull;
1073  char *attname;
1074  JsonbTypeCategory tcategory;
1075  Oid outfuncoid;
1076  JsonbValue v;
1077 
1078  if (tupdesc->attrs[i]->attisdropped)
1079  continue;
1080 
1081  attname = NameStr(tupdesc->attrs[i]->attname);
1082 
1083  v.type = jbvString;
1084  /* don't need checkStringLen here - can't exceed maximum name length */
1085  v.val.string.len = strlen(attname);
1086  v.val.string.val = attname;
1087 
1088  result->res = pushJsonbValue(&result->parseState, WJB_KEY, &v);
1089 
1090  val = heap_getattr(tuple, i + 1, tupdesc, &isnull);
1091 
1092  if (isnull)
1093  {
1094  tcategory = JSONBTYPE_NULL;
1095  outfuncoid = InvalidOid;
1096  }
1097  else
1098  jsonb_categorize_type(tupdesc->attrs[i]->atttypid,
1099  &tcategory, &outfuncoid);
1100 
1101  datum_to_jsonb(val, isnull, result, tcategory, outfuncoid, false);
1102  }
1103 
1104  result->res = pushJsonbValue(&result->parseState, WJB_END_OBJECT, NULL);
1105  ReleaseTupleDesc(tupdesc);
1106 }
1107 
1108 /*
1109  * Append JSON text for "val" to "result".
1110  *
1111  * This is just a thin wrapper around datum_to_jsonb. If the same type will be
1112  * printed many times, avoid using this; better to do the jsonb_categorize_type
1113  * lookups only once.
1114  */
1115 
1116 static void
1117 add_jsonb(Datum val, bool is_null, JsonbInState *result,
1118  Oid val_type, bool key_scalar)
1119 {
1120  JsonbTypeCategory tcategory;
1121  Oid outfuncoid;
1122 
1123  if (val_type == InvalidOid)
1124  ereport(ERROR,
1125  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1126  errmsg("could not determine input data type")));
1127 
1128  if (is_null)
1129  {
1130  tcategory = JSONBTYPE_NULL;
1131  outfuncoid = InvalidOid;
1132  }
1133  else
1134  jsonb_categorize_type(val_type,
1135  &tcategory, &outfuncoid);
1136 
1137  datum_to_jsonb(val, is_null, result, tcategory, outfuncoid, key_scalar);
1138 }
1139 
1140 /*
1141  * SQL function to_jsonb(anyvalue)
1142  */
1143 Datum
1145 {
1146  Datum val = PG_GETARG_DATUM(0);
1147  Oid val_type = get_fn_expr_argtype(fcinfo->flinfo, 0);
1148  JsonbInState result;
1149  JsonbTypeCategory tcategory;
1150  Oid outfuncoid;
1151 
1152  if (val_type == InvalidOid)
1153  ereport(ERROR,
1154  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1155  errmsg("could not determine input data type")));
1156 
1157  jsonb_categorize_type(val_type,
1158  &tcategory, &outfuncoid);
1159 
1160  memset(&result, 0, sizeof(JsonbInState));
1161 
1162  datum_to_jsonb(val, false, &result, tcategory, outfuncoid, false);
1163 
1165 }
1166 
1167 /*
1168  * SQL function jsonb_build_object(variadic "any")
1169  */
1170 Datum
1172 {
1173  int nargs = PG_NARGS();
1174  int i;
1175  Datum arg;
1176  Oid val_type;
1177  JsonbInState result;
1178 
1179  if (nargs % 2 != 0)
1180  ereport(ERROR,
1181  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1182  errmsg("invalid number of arguments: object must be matched key value pairs")));
1183 
1184  memset(&result, 0, sizeof(JsonbInState));
1185 
1186  result.res = pushJsonbValue(&result.parseState, WJB_BEGIN_OBJECT, NULL);
1187 
1188  for (i = 0; i < nargs; i += 2)
1189  {
1190  /* process key */
1191 
1192  if (PG_ARGISNULL(i))
1193  ereport(ERROR,
1194  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1195  errmsg("argument %d: key must not be null", i + 1)));
1196  val_type = get_fn_expr_argtype(fcinfo->flinfo, i);
1197 
1198  /*
1199  * turn a constant (more or less literal) value that's of unknown type
1200  * into text. Unknowns come in as a cstring pointer.
1201  */
1202  if (val_type == UNKNOWNOID && get_fn_expr_arg_stable(fcinfo->flinfo, i))
1203  {
1204  val_type = TEXTOID;
1206  }
1207  else
1208  {
1209  arg = PG_GETARG_DATUM(i);
1210  }
1211  if (val_type == InvalidOid || val_type == UNKNOWNOID)
1212  ereport(ERROR,
1213  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1214  errmsg("argument %d: could not determine data type", i + 1)));
1215 
1216  add_jsonb(arg, false, &result, val_type, true);
1217 
1218  /* process value */
1219 
1220  val_type = get_fn_expr_argtype(fcinfo->flinfo, i + 1);
1221  /* see comments above */
1222  if (val_type == UNKNOWNOID && get_fn_expr_arg_stable(fcinfo->flinfo, i + 1))
1223  {
1224  val_type = TEXTOID;
1225  if (PG_ARGISNULL(i + 1))
1226  arg = (Datum) 0;
1227  else
1228  arg = CStringGetTextDatum(PG_GETARG_POINTER(i + 1));
1229  }
1230  else
1231  {
1232  arg = PG_GETARG_DATUM(i + 1);
1233  }
1234  if (val_type == InvalidOid || val_type == UNKNOWNOID)
1235  ereport(ERROR,
1236  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1237  errmsg("argument %d: could not determine data type", i + 2)));
1238  add_jsonb(arg, PG_ARGISNULL(i + 1), &result, val_type, false);
1239  }
1240 
1241  result.res = pushJsonbValue(&result.parseState, WJB_END_OBJECT, NULL);
1242 
1244 }
1245 
1246 /*
1247  * degenerate case of jsonb_build_object where it gets 0 arguments.
1248  */
1249 Datum
1251 {
1252  JsonbInState result;
1253 
1254  memset(&result, 0, sizeof(JsonbInState));
1255 
1256  (void) pushJsonbValue(&result.parseState, WJB_BEGIN_OBJECT, NULL);
1257  result.res = pushJsonbValue(&result.parseState, WJB_END_OBJECT, NULL);
1258 
1260 }
1261 
1262 /*
1263  * SQL function jsonb_build_array(variadic "any")
1264  */
1265 Datum
1267 {
1268  int nargs = PG_NARGS();
1269  int i;
1270  Datum arg;
1271  Oid val_type;
1272  JsonbInState result;
1273 
1274  memset(&result, 0, sizeof(JsonbInState));
1275 
1276  result.res = pushJsonbValue(&result.parseState, WJB_BEGIN_ARRAY, NULL);
1277 
1278  for (i = 0; i < nargs; i++)
1279  {
1280  val_type = get_fn_expr_argtype(fcinfo->flinfo, i);
1281  /* see comments in jsonb_build_object above */
1282  if (val_type == UNKNOWNOID && get_fn_expr_arg_stable(fcinfo->flinfo, i))
1283  {
1284  val_type = TEXTOID;
1285  if (PG_ARGISNULL(i))
1286  arg = (Datum) 0;
1287  else
1289  }
1290  else
1291  {
1292  arg = PG_GETARG_DATUM(i);
1293  }
1294  if (val_type == InvalidOid || val_type == UNKNOWNOID)
1295  ereport(ERROR,
1296  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1297  errmsg("argument %d: could not determine data type", i + 1)));
1298  add_jsonb(arg, PG_ARGISNULL(i), &result, val_type, false);
1299  }
1300 
1301  result.res = pushJsonbValue(&result.parseState, WJB_END_ARRAY, NULL);
1302 
1304 }
1305 
1306 /*
1307  * degenerate case of jsonb_build_array where it gets 0 arguments.
1308  */
1309 Datum
1311 {
1312  JsonbInState result;
1313 
1314  memset(&result, 0, sizeof(JsonbInState));
1315 
1316  (void) pushJsonbValue(&result.parseState, WJB_BEGIN_ARRAY, NULL);
1317  result.res = pushJsonbValue(&result.parseState, WJB_END_ARRAY, NULL);
1318 
1320 }
1321 
1322 
1323 /*
1324  * SQL function jsonb_object(text[])
1325  *
1326  * take a one or two dimensional array of text as name value pairs
1327  * for a jsonb object.
1328  *
1329  */
1330 Datum
1332 {
1333  ArrayType *in_array = PG_GETARG_ARRAYTYPE_P(0);
1334  int ndims = ARR_NDIM(in_array);
1335  Datum *in_datums;
1336  bool *in_nulls;
1337  int in_count,
1338  count,
1339  i;
1340  JsonbInState result;
1341 
1342  memset(&result, 0, sizeof(JsonbInState));
1343 
1344  (void) pushJsonbValue(&result.parseState, WJB_BEGIN_OBJECT, NULL);
1345 
1346  switch (ndims)
1347  {
1348  case 0:
1349  goto close_object;
1350  break;
1351 
1352  case 1:
1353  if ((ARR_DIMS(in_array)[0]) % 2)
1354  ereport(ERROR,
1355  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1356  errmsg("array must have even number of elements")));
1357  break;
1358 
1359  case 2:
1360  if ((ARR_DIMS(in_array)[1]) != 2)
1361  ereport(ERROR,
1362  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1363  errmsg("array must have two columns")));
1364  break;
1365 
1366  default:
1367  ereport(ERROR,
1368  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1369  errmsg("wrong number of array subscripts")));
1370  }
1371 
1372  deconstruct_array(in_array,
1373  TEXTOID, -1, false, 'i',
1374  &in_datums, &in_nulls, &in_count);
1375 
1376  count = in_count / 2;
1377 
1378  for (i = 0; i < count; ++i)
1379  {
1380  JsonbValue v;
1381  char *str;
1382  int len;
1383 
1384  if (in_nulls[i * 2])
1385  ereport(ERROR,
1386  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1387  errmsg("null value not allowed for object key")));
1388 
1389  str = TextDatumGetCString(in_datums[i * 2]);
1390  len = strlen(str);
1391 
1392  v.type = jbvString;
1393 
1394  v.val.string.len = len;
1395  v.val.string.val = str;
1396 
1397  (void) pushJsonbValue(&result.parseState, WJB_KEY, &v);
1398 
1399  if (in_nulls[i * 2 + 1])
1400  {
1401  v.type = jbvNull;
1402  }
1403  else
1404  {
1405  str = TextDatumGetCString(in_datums[i * 2 + 1]);
1406  len = strlen(str);
1407 
1408  v.type = jbvString;
1409 
1410  v.val.string.len = len;
1411  v.val.string.val = str;
1412  }
1413 
1414  (void) pushJsonbValue(&result.parseState, WJB_VALUE, &v);
1415  }
1416 
1417  pfree(in_datums);
1418  pfree(in_nulls);
1419 
1420 close_object:
1421  result.res = pushJsonbValue(&result.parseState, WJB_END_OBJECT, NULL);
1422 
1424 }
1425 
1426 /*
1427  * SQL function jsonb_object(text[], text[])
1428  *
1429  * take separate name and value arrays of text to construct a jsonb object
1430  * pairwise.
1431  */
1432 Datum
1434 {
1435  ArrayType *key_array = PG_GETARG_ARRAYTYPE_P(0);
1436  ArrayType *val_array = PG_GETARG_ARRAYTYPE_P(1);
1437  int nkdims = ARR_NDIM(key_array);
1438  int nvdims = ARR_NDIM(val_array);
1439  Datum *key_datums,
1440  *val_datums;
1441  bool *key_nulls,
1442  *val_nulls;
1443  int key_count,
1444  val_count,
1445  i;
1446  JsonbInState result;
1447 
1448  memset(&result, 0, sizeof(JsonbInState));
1449 
1450  (void) pushJsonbValue(&result.parseState, WJB_BEGIN_OBJECT, NULL);
1451 
1452  if (nkdims > 1 || nkdims != nvdims)
1453  ereport(ERROR,
1454  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1455  errmsg("wrong number of array subscripts")));
1456 
1457  if (nkdims == 0)
1458  goto close_object;
1459 
1460  deconstruct_array(key_array,
1461  TEXTOID, -1, false, 'i',
1462  &key_datums, &key_nulls, &key_count);
1463 
1464  deconstruct_array(val_array,
1465  TEXTOID, -1, false, 'i',
1466  &val_datums, &val_nulls, &val_count);
1467 
1468  if (key_count != val_count)
1469  ereport(ERROR,
1470  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1471  errmsg("mismatched array dimensions")));
1472 
1473  for (i = 0; i < key_count; ++i)
1474  {
1475  JsonbValue v;
1476  char *str;
1477  int len;
1478 
1479  if (key_nulls[i])
1480  ereport(ERROR,
1481  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1482  errmsg("null value not allowed for object key")));
1483 
1484  str = TextDatumGetCString(key_datums[i]);
1485  len = strlen(str);
1486 
1487  v.type = jbvString;
1488 
1489  v.val.string.len = len;
1490  v.val.string.val = str;
1491 
1492  (void) pushJsonbValue(&result.parseState, WJB_KEY, &v);
1493 
1494  if (val_nulls[i])
1495  {
1496  v.type = jbvNull;
1497  }
1498  else
1499  {
1500  str = TextDatumGetCString(val_datums[i]);
1501  len = strlen(str);
1502 
1503  v.type = jbvString;
1504 
1505  v.val.string.len = len;
1506  v.val.string.val = str;
1507  }
1508 
1509  (void) pushJsonbValue(&result.parseState, WJB_VALUE, &v);
1510  }
1511 
1512  pfree(key_datums);
1513  pfree(key_nulls);
1514  pfree(val_datums);
1515  pfree(val_nulls);
1516 
1517 close_object:
1518  result.res = pushJsonbValue(&result.parseState, WJB_END_OBJECT, NULL);
1519 
1521 }
1522 
1523 
1524 /*
1525  * shallow clone of a parse state, suitable for use in aggregate
1526  * final functions that will only append to the values rather than
1527  * change them.
1528  */
1529 static JsonbParseState *
1531 {
1532  JsonbParseState *result,
1533  *icursor,
1534  *ocursor;
1535 
1536  if (state == NULL)
1537  return NULL;
1538 
1539  result = palloc(sizeof(JsonbParseState));
1540  icursor = state;
1541  ocursor = result;
1542  for (;;)
1543  {
1544  ocursor->contVal = icursor->contVal;
1545  ocursor->size = icursor->size;
1546  icursor = icursor->next;
1547  if (icursor == NULL)
1548  break;
1549  ocursor->next = palloc(sizeof(JsonbParseState));
1550  ocursor = ocursor->next;
1551  }
1552  ocursor->next = NULL;
1553 
1554  return result;
1555 }
1556 
1557 
1558 /*
1559  * jsonb_agg aggregate function
1560  */
1561 Datum
1563 {
1564  MemoryContext oldcontext,
1565  aggcontext;
1567  JsonbInState elem;
1568  Datum val;
1569  JsonbInState *result;
1570  bool single_scalar = false;
1571  JsonbIterator *it;
1572  Jsonb *jbelem;
1573  JsonbValue v;
1574  JsonbIteratorToken type;
1575 
1576  if (!AggCheckCallContext(fcinfo, &aggcontext))
1577  {
1578  /* cannot be called directly because of internal-type argument */
1579  elog(ERROR, "jsonb_agg_transfn called in non-aggregate context");
1580  }
1581 
1582  /* set up the accumulator on the first go round */
1583 
1584  if (PG_ARGISNULL(0))
1585  {
1586  Oid arg_type = get_fn_expr_argtype(fcinfo->flinfo, 1);
1587 
1588  if (arg_type == InvalidOid)
1589  ereport(ERROR,
1590  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1591  errmsg("could not determine input data type")));
1592 
1593  oldcontext = MemoryContextSwitchTo(aggcontext);
1594  state = palloc(sizeof(JsonbAggState));
1595  result = palloc0(sizeof(JsonbInState));
1596  state->res = result;
1597  result->res = pushJsonbValue(&result->parseState,
1599  MemoryContextSwitchTo(oldcontext);
1600 
1601  jsonb_categorize_type(arg_type, &state->val_category,
1602  &state->val_output_func);
1603  }
1604  else
1605  {
1606  state = (JsonbAggState *) PG_GETARG_POINTER(0);
1607  result = state->res;
1608  }
1609 
1610  /* turn the argument into jsonb in the normal function context */
1611 
1612  val = PG_ARGISNULL(1) ? (Datum) 0 : PG_GETARG_DATUM(1);
1613 
1614  memset(&elem, 0, sizeof(JsonbInState));
1615 
1616  datum_to_jsonb(val, PG_ARGISNULL(1), &elem, state->val_category,
1617  state->val_output_func, false);
1618 
1619  jbelem = JsonbValueToJsonb(elem.res);
1620 
1621  /* switch to the aggregate context for accumulation operations */
1622 
1623  oldcontext = MemoryContextSwitchTo(aggcontext);
1624 
1625  it = JsonbIteratorInit(&jbelem->root);
1626 
1627  while ((type = JsonbIteratorNext(&it, &v, false)) != WJB_DONE)
1628  {
1629  switch (type)
1630  {
1631  case WJB_BEGIN_ARRAY:
1632  if (v.val.array.rawScalar)
1633  single_scalar = true;
1634  else
1635  result->res = pushJsonbValue(&result->parseState,
1636  type, NULL);
1637  break;
1638  case WJB_END_ARRAY:
1639  if (!single_scalar)
1640  result->res = pushJsonbValue(&result->parseState,
1641  type, NULL);
1642  break;
1643  case WJB_BEGIN_OBJECT:
1644  case WJB_END_OBJECT:
1645  result->res = pushJsonbValue(&result->parseState,
1646  type, NULL);
1647  break;
1648  case WJB_ELEM:
1649  case WJB_KEY:
1650  case WJB_VALUE:
1651  if (v.type == jbvString)
1652  {
1653  /* copy string values in the aggregate context */
1654  char *buf = palloc(v.val.string.len + 1);
1655 
1656  snprintf(buf, v.val.string.len + 1, "%s", v.val.string.val);
1657  v.val.string.val = buf;
1658  }
1659  else if (v.type == jbvNumeric)
1660  {
1661  /* same for numeric */
1662  v.val.numeric =
1664  NumericGetDatum(v.val.numeric)));
1665  }
1666  result->res = pushJsonbValue(&result->parseState,
1667  type, &v);
1668  break;
1669  default:
1670  elog(ERROR, "unknown jsonb iterator token type");
1671  }
1672  }
1673 
1674  MemoryContextSwitchTo(oldcontext);
1675 
1676  PG_RETURN_POINTER(state);
1677 }
1678 
1679 Datum
1681 {
1682  JsonbAggState *arg;
1683  JsonbInState result;
1684  Jsonb *out;
1685 
1686  /* cannot be called directly because of internal-type argument */
1687  Assert(AggCheckCallContext(fcinfo, NULL));
1688 
1689  if (PG_ARGISNULL(0))
1690  PG_RETURN_NULL(); /* returns null iff no input values */
1691 
1692  arg = (JsonbAggState *) PG_GETARG_POINTER(0);
1693 
1694  /*
1695  * We need to do a shallow clone of the argument in case the final
1696  * function is called more than once, so we avoid changing the argument. A
1697  * shallow clone is sufficient as we aren't going to change any of the
1698  * values, just add the final array end marker.
1699  */
1700 
1701  result.parseState = clone_parse_state(arg->res->parseState);
1702 
1703  result.res = pushJsonbValue(&result.parseState,
1704  WJB_END_ARRAY, NULL);
1705 
1706  out = JsonbValueToJsonb(result.res);
1707 
1708  PG_RETURN_POINTER(out);
1709 }
1710 
1711 /*
1712  * jsonb_object_agg aggregate function
1713  */
1714 Datum
1716 {
1717  MemoryContext oldcontext,
1718  aggcontext;
1719  JsonbInState elem;
1721  Datum val;
1722  JsonbInState *result;
1723  bool single_scalar;
1724  JsonbIterator *it;
1725  Jsonb *jbkey,
1726  *jbval;
1727  JsonbValue v;
1728  JsonbIteratorToken type;
1729 
1730  if (!AggCheckCallContext(fcinfo, &aggcontext))
1731  {
1732  /* cannot be called directly because of internal-type argument */
1733  elog(ERROR, "jsonb_object_agg_transfn called in non-aggregate context");
1734  }
1735 
1736  /* set up the accumulator on the first go round */
1737 
1738  if (PG_ARGISNULL(0))
1739  {
1740  Oid arg_type;
1741 
1742  oldcontext = MemoryContextSwitchTo(aggcontext);
1743  state = palloc(sizeof(JsonbAggState));
1744  result = palloc0(sizeof(JsonbInState));
1745  state->res = result;
1746  result->res = pushJsonbValue(&result->parseState,
1748  MemoryContextSwitchTo(oldcontext);
1749 
1750  arg_type = get_fn_expr_argtype(fcinfo->flinfo, 1);
1751 
1752  if (arg_type == InvalidOid)
1753  ereport(ERROR,
1754  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1755  errmsg("could not determine input data type")));
1756 
1757  jsonb_categorize_type(arg_type, &state->key_category,
1758  &state->key_output_func);
1759 
1760  arg_type = get_fn_expr_argtype(fcinfo->flinfo, 2);
1761 
1762  if (arg_type == InvalidOid)
1763  ereport(ERROR,
1764  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1765  errmsg("could not determine input data type")));
1766 
1767  jsonb_categorize_type(arg_type, &state->val_category,
1768  &state->val_output_func);
1769  }
1770  else
1771  {
1772  state = (JsonbAggState *) PG_GETARG_POINTER(0);
1773  result = state->res;
1774  }
1775 
1776  /* turn the argument into jsonb in the normal function context */
1777 
1778  if (PG_ARGISNULL(1))
1779  ereport(ERROR,
1780  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1781  errmsg("field name must not be null")));
1782 
1783  val = PG_GETARG_DATUM(1);
1784 
1785  memset(&elem, 0, sizeof(JsonbInState));
1786 
1787  datum_to_jsonb(val, false, &elem, state->key_category,
1788  state->key_output_func, true);
1789 
1790  jbkey = JsonbValueToJsonb(elem.res);
1791 
1792  val = PG_ARGISNULL(2) ? (Datum) 0 : PG_GETARG_DATUM(2);
1793 
1794  memset(&elem, 0, sizeof(JsonbInState));
1795 
1796  datum_to_jsonb(val, PG_ARGISNULL(2), &elem, state->val_category,
1797  state->val_output_func, false);
1798 
1799  jbval = JsonbValueToJsonb(elem.res);
1800 
1801  it = JsonbIteratorInit(&jbkey->root);
1802 
1803  /* switch to the aggregate context for accumulation operations */
1804 
1805  oldcontext = MemoryContextSwitchTo(aggcontext);
1806 
1807  /*
1808  * keys should be scalar, and we should have already checked for that
1809  * above when calling datum_to_jsonb, so we only need to look for these
1810  * things.
1811  */
1812 
1813  while ((type = JsonbIteratorNext(&it, &v, false)) != WJB_DONE)
1814  {
1815  switch (type)
1816  {
1817  case WJB_BEGIN_ARRAY:
1818  if (!v.val.array.rawScalar)
1819  elog(ERROR, "unexpected structure for key");
1820  break;
1821  case WJB_ELEM:
1822  if (v.type == jbvString)
1823  {
1824  /* copy string values in the aggregate context */
1825  char *buf = palloc(v.val.string.len + 1);
1826 
1827  snprintf(buf, v.val.string.len + 1, "%s", v.val.string.val);
1828  v.val.string.val = buf;
1829  }
1830  else
1831  {
1832  ereport(ERROR,
1833  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1834  errmsg("object keys must be strings")));
1835  }
1836  result->res = pushJsonbValue(&result->parseState,
1837  WJB_KEY, &v);
1838  break;
1839  case WJB_END_ARRAY:
1840  break;
1841  default:
1842  elog(ERROR, "unexpected structure for key");
1843  break;
1844  }
1845  }
1846 
1847  it = JsonbIteratorInit(&jbval->root);
1848 
1849  single_scalar = false;
1850 
1851  /*
1852  * values can be anything, including structured and null, so we treat them
1853  * as in json_agg_transfn, except that single scalars are always pushed as
1854  * WJB_VALUE items.
1855  */
1856 
1857  while ((type = JsonbIteratorNext(&it, &v, false)) != WJB_DONE)
1858  {
1859  switch (type)
1860  {
1861  case WJB_BEGIN_ARRAY:
1862  if (v.val.array.rawScalar)
1863  single_scalar = true;
1864  else
1865  result->res = pushJsonbValue(&result->parseState,
1866  type, NULL);
1867  break;
1868  case WJB_END_ARRAY:
1869  if (!single_scalar)
1870  result->res = pushJsonbValue(&result->parseState,
1871  type, NULL);
1872  break;
1873  case WJB_BEGIN_OBJECT:
1874  case WJB_END_OBJECT:
1875  result->res = pushJsonbValue(&result->parseState,
1876  type, NULL);
1877  break;
1878  case WJB_ELEM:
1879  case WJB_KEY:
1880  case WJB_VALUE:
1881  if (v.type == jbvString)
1882  {
1883  /* copy string values in the aggregate context */
1884  char *buf = palloc(v.val.string.len + 1);
1885 
1886  snprintf(buf, v.val.string.len + 1, "%s", v.val.string.val);
1887  v.val.string.val = buf;
1888  }
1889  else if (v.type == jbvNumeric)
1890  {
1891  /* same for numeric */
1892  v.val.numeric =
1894  NumericGetDatum(v.val.numeric)));
1895  }
1896  result->res = pushJsonbValue(&result->parseState,
1897  single_scalar ? WJB_VALUE : type,
1898  &v);
1899  break;
1900  default:
1901  elog(ERROR, "unknown jsonb iterator token type");
1902  }
1903  }
1904 
1905  MemoryContextSwitchTo(oldcontext);
1906 
1907  PG_RETURN_POINTER(state);
1908 }
1909 
1910 Datum
1912 {
1913  JsonbAggState *arg;
1914  JsonbInState result;
1915  Jsonb *out;
1916 
1917  /* cannot be called directly because of internal-type argument */
1918  Assert(AggCheckCallContext(fcinfo, NULL));
1919 
1920  if (PG_ARGISNULL(0))
1921  PG_RETURN_NULL(); /* returns null iff no input values */
1922 
1923  arg = (JsonbAggState *) PG_GETARG_POINTER(0);
1924 
1925  /*
1926  * We need to do a shallow clone of the argument's res field in case the
1927  * final function is called more than once, so we avoid changing the
1928  * aggregate state value. A shallow clone is sufficient as we aren't
1929  * going to change any of the values, just add the final object end
1930  * marker.
1931  */
1932 
1933  result.parseState = clone_parse_state(arg->res->parseState);
1934 
1935  result.res = pushJsonbValue(&result.parseState,
1936  WJB_END_OBJECT, NULL);
1937 
1938  out = JsonbValueToJsonb(result.res);
1939 
1940  PG_RETURN_POINTER(out);
1941 }
#define MAXDATELEN
Definition: datetime.h:203
void EncodeDateOnly(struct pg_tm *tm, int style, char *str)
Definition: datetime.c:3990
json_struct_action array_end
Definition: jsonapi.h:87
#define TIMESTAMPTZOID
Definition: pg_type.h:513
static void array_to_jsonb_internal(Datum array, JsonbInState *result)
Definition: jsonb.c:997
signed short int16
Definition: c.h:252
JsonbParseState * parseState
Definition: jsonb.c:33
JsonbValue * res
Definition: jsonb.c:34
#define PG_RETURN_POINTER(x)
Definition: fmgr.h:305
static void jsonb_in_object_end(void *pstate)
Definition: jsonb.c:273
#define DATEOID
Definition: pg_type.h:499
#define DatumGetDateADT(X)
Definition: date.h:73
#define JB_ROOT_IS_OBJECT(jbp_)
Definition: jsonb.h:224
Datum jsonb_typeof(PG_FUNCTION_ARGS)
Definition: jsonb.c:172
char * pnstrdup(const char *in, Size len)
Definition: mcxt.c:1176
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2600
Jsonb * JsonbValueToJsonb(JsonbValue *val)
Definition: jsonb_util.c:79
Definition: jsonb.h:215
Datum numeric_uplus(PG_FUNCTION_ARGS)
Definition: numeric.c:1148
static Datum jsonb_from_cstring(char *json, int len)
Definition: jsonb.c:226
static char * JsonbToCStringWorker(StringInfo out, JsonbContainer *in, int estimated_len, bool indent)
Definition: jsonb.c:446
void escape_json(StringInfo buf, const char *str)
Definition: json.c:2432
bool get_fn_expr_arg_stable(FmgrInfo *flinfo, int argnum)
Definition: fmgr.c:2291
TupleDesc lookup_rowtype_tupdesc(Oid type_id, int32 typmod)
Definition: typcache.c:1245
double fsec_t
Definition: timestamp.h:53
json_struct_action object_end
Definition: jsonapi.h:85
Datum jsonb_build_object(PG_FUNCTION_ARGS)
Definition: jsonb.c:1171
Datum jsonb_object(PG_FUNCTION_ARGS)
Definition: jsonb.c:1331
int32 DateADT
Definition: date.h:22
static void jsonb_in_array_start(void *pstate)
Definition: jsonb.c:281
#define TEXTOID
Definition: pg_type.h:324
#define VARSIZE(PTR)
Definition: postgres.h:306
Oid get_element_type(Oid typid)
Definition: lsyscache.c:2452
void get_typlenbyvalalign(Oid typid, int16 *typlen, bool *typbyval, char *typalign)
Definition: lsyscache.c:1989
#define PointerGetDatum(X)
Definition: postgres.h:564
#define PG_GETARG_DATUM(n)
Definition: fmgr.h:224
#define NUMERICOID
Definition: pg_type.h:542
void pq_begintypsend(StringInfo buf)
Definition: pqformat.c:359
#define JSONOID
Definition: pg_type.h:356
char * pstrdup(const char *in)
Definition: mcxt.c:1165
char * val
Definition: jsonb.h:259
static JsonbParseState * clone_parse_state(JsonbParseState *state)
Definition: jsonb.c:1530
#define NumericGetDatum(X)
Definition: numeric.h:51
JsonbInState * res
Definition: jsonb.c:56
int timestamp2tm(Timestamp dt, int *tzp, struct pg_tm *tm, fsec_t *fsec, const char **tzn, pg_tz *attimezone)
Definition: timestamp.c:1950
Definition: jsonb.h:234
StringInfo makeStringInfo(void)
Definition: stringinfo.c:29
StringInfoData * StringInfo
Definition: stringinfo.h:46
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:75
Form_pg_attribute * attrs
Definition: tupdesc.h:74
Datum numeric_out(PG_FUNCTION_ARGS)
Definition: numeric.c:641
json_struct_action object_start
Definition: jsonapi.h:84
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static void add_jsonb(Datum val, bool is_null, JsonbInState *result, Oid val_type, bool key_scalar)
Definition: jsonb.c:1117
Definition: jsonb.h:22
#define INT4OID
Definition: pg_type.h:316
int errcode(int sqlerrcode)
Definition: elog.c:575
json_scalar_action scalar
Definition: jsonapi.h:92
Oid key_output_func
Definition: jsonb.c:58
void pq_sendtext(StringInfo buf, const char *str, int slen)
Definition: pqformat.c:163
static void jsonb_in_scalar(void *pstate, char *token, JsonTokenType tokentype)
Definition: jsonb.c:341
#define JENTRY_OFFLENMASK
Definition: jsonb.h:141
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
#define PG_GETARG_POINTER(n)
Definition: fmgr.h:232
Definition: jsonb.h:231
long date
Definition: pgtypes_date.h:8
void EncodeSpecialTimestamp(Timestamp dt, char *str)
Definition: timestamp.c:1640
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:555
#define PG_RETURN_BYTEA_P(x)
Definition: fmgr.h:313
#define JB_ROOT_IS_SCALAR(jbp_)
Definition: jsonb.h:223
Definition: pgtime.h:25
unsigned int Oid
Definition: postgres_ext.h:31
struct JsonbParseState * next
Definition: jsonb.h:308
#define OidIsValid(objectId)
Definition: c.h:533
bytea * pq_endtypsend(StringInfo buf)
Definition: pqformat.c:379
#define DatumGetHeapTupleHeader(X)
Definition: fmgr.h:254
int natts
Definition: tupdesc.h:73
CoercionPathType
Definition: parse_coerce.h:24
#define FirstNormalObjectId
Definition: transam.h:94
signed int int32
Definition: c.h:253
char * JsonbToCStringIndent(StringInfo out, JsonbContainer *in, int estimated_len)
Definition: jsonb.c:437
static void jsonb_in_array_end(void *pstate)
Definition: jsonb.c:289
HeapTupleHeader t_data
Definition: htup.h:67
#define HeapTupleHeaderGetTypMod(tup)
Definition: htup_details.h:455
JsonbTypeCategory val_category
Definition: jsonb.c:59
static void datum_to_jsonb(Datum val, bool is_null, JsonbInState *result, JsonbTypeCategory tcategory, Oid outfuncoid, bool key_scalar)
Definition: jsonb.c:698
JsonbValue * pushJsonbValue(JsonbParseState **pstate, JsonbIteratorToken seq, JsonbValue *jbval)
Definition: jsonb_util.c:517
#define PG_GETARG_ARRAYTYPE_P(n)
Definition: array.h:244
#define DatumGetJsonb(d)
Definition: jsonb.h:68
#define appendStringInfoCharMacro(str, ch)
Definition: stringinfo.h:135
JsonLexContext * makeJsonLexContext(text *json, bool need_escapes)
Definition: json.c:300
#define TIMESTAMP_NOT_FINITE(j)
Definition: timestamp.h:144
double TimestampTz
Definition: timestamp.h:51
void pfree(void *pointer)
Definition: mcxt.c:992
Datum jsonb_send(PG_FUNCTION_ARGS)
Definition: jsonb.c:147
#define TIMESTAMPOID
Definition: pg_type.h:507
Datum jsonb_object_agg_finalfn(PG_FUNCTION_ARGS)
Definition: jsonb.c:1911
#define ERROR
Definition: elog.h:43
Datum jsonb_object_agg_transfn(PG_FUNCTION_ARGS)
Definition: jsonb.c:1715
#define DatumGetCString(X)
Definition: postgres.h:574
Oid get_fn_expr_argtype(FmgrInfo *flinfo, int argnum)
Definition: fmgr.c:2220
Datum jsonb_build_object_noargs(PG_FUNCTION_ARGS)
Definition: jsonb.c:1250
#define ARR_DIMS(a)
Definition: array.h:275
#define JB_ROOT_IS_ARRAY(jbp_)
Definition: jsonb.h:225
#define DATE_NOT_FINITE(j)
Definition: date.h:46
void pg_parse_json(JsonLexContext *lex, JsonSemAction *sem)
Definition: json.c:331
#define OidFunctionCall1(functionId, arg1)
Definition: fmgr.h:593
#define INT2OID
Definition: pg_type.h:308
static size_t checkStringLen(size_t len)
Definition: jsonb.c:252
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:189
uint32 t_len
Definition: htup.h:64
int tm_mday
Definition: pgtime.h:30
static char * buf
Definition: pg_test_fsync.c:65
Datum to_jsonb(PG_FUNCTION_ARGS)
Definition: jsonb.c:1144
int tm_mon
Definition: pgtime.h:31
void check_stack_depth(void)
Definition: postgres.c:3096
#define DatumGetTimestampTz(X)
Definition: timestamp.h:48
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define CStringGetDatum(X)
Definition: postgres.h:586
#define DatumGetBool(X)
Definition: postgres.h:401
void enlargeStringInfo(StringInfo str, int needed)
Definition: stringinfo.c:277
#define JSONBOID
Definition: pg_type.h:626
void EncodeDateTime(struct pg_tm *tm, fsec_t fsec, bool print_tz, int tz, const char *tzn, int style, char *str)
Definition: datetime.c:4105
static void jsonb_categorize_type(Oid typoid, JsonbTypeCategory *tcategory, Oid *outfuncoid)
Definition: jsonb.c:591
void EncodeSpecialDate(DateADT dt, char *str)
Definition: date.c:299
Datum numeric_in(PG_FUNCTION_ARGS)
Definition: numeric.c:559
Definition: jsonb.h:23
bool type_is_rowtype(Oid typid)
Definition: lsyscache.c:2372
Datum jsonb_recv(PG_FUNCTION_ARGS)
Definition: jsonb.c:112
static void array_dim_to_jsonb(JsonbInState *result, int dim, int ndims, int *dims, Datum *vals, bool *nulls, int *valcount, JsonbTypeCategory tcategory, Oid outfuncoid)
Definition: jsonb.c:965
#define ereport(elevel, rest)
Definition: elog.h:122
void j2date(int jd, int *year, int *month, int *day)
Definition: datetime.c:322
JsonbIteratorToken
Definition: jsonb.h:20
struct JsonbAggState JsonbAggState
#define DirectFunctionCall3(func, arg1, arg2, arg3)
Definition: fmgr.h:559
char * pq_getmsgtext(StringInfo msg, int rawbytes, int *nbytes)
Definition: pqformat.c:588
JsonbContainer root
Definition: jsonb.h:218
#define heap_getattr(tup, attnum, tupleDesc, isnull)
Definition: htup_details.h:769
#define TextDatumGetCString(d)
Definition: builtins.h:91
#define FLOAT4OID
Definition: pg_type.h:408
void * palloc0(Size size)
Definition: mcxt.c:920
static void composite_to_jsonb(Datum composite, JsonbInState *result)
Definition: jsonb.c:1045
double Timestamp
Definition: timestamp.h:50
uintptr_t Datum
Definition: postgres.h:374
Datum jsonb_object_two_arg(PG_FUNCTION_ARGS)
Definition: jsonb.c:1433
#define HeapTupleHeaderGetTypeId(tup)
Definition: htup_details.h:445
JsonbValue contVal
Definition: jsonb.h:306
static void jsonb_put_escaped_value(StringInfo out, JsonbValue *scalarVal)
Definition: jsonb.c:311
static void add_indent(StringInfo out, bool indent, int level)
Definition: jsonb.c:570
JsonbTypeCategory
Definition: jsonb.c:38
#define InvalidOid
Definition: postgres_ext.h:36
Datum jsonb_agg_transfn(PG_FUNCTION_ARGS)
Definition: jsonb.c:1562
#define INT8OID
Definition: pg_type.h:304
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:314
text * cstring_to_text(const char *s)
Definition: varlena.c:151
#define PG_ARGISNULL(n)
Definition: fmgr.h:166
#define DatumGetNumeric(X)
Definition: numeric.h:49
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:670
JsonbIterator * JsonbIteratorInit(JsonbContainer *container)
Definition: jsonb_util.c:718
json_struct_action array_start
Definition: jsonapi.h:86
Definition: regguts.h:298
Datum jsonb_out(PG_FUNCTION_ARGS)
Definition: jsonb.c:131
#define PG_RETURN_CSTRING(x)
Definition: fmgr.h:306
char * JsonbToCString(StringInfo out, JsonbContainer *in, int estimated_len)
Definition: jsonb.c:428
struct JsonbInState JsonbInState
#define FLOAT8OID
Definition: pg_type.h:411
JsonLexContext * makeJsonLexContextCstringLen(char *json, int len, bool need_escapes)
Definition: json.c:308
int AggCheckCallContext(FunctionCallInfo fcinfo, MemoryContext *aggcontext)
Definition: nodeAgg.c:3660
Datum jsonb_build_array(PG_FUNCTION_ARGS)
Definition: jsonb.c:1266
#define PG_NARGS()
Definition: fmgr.h:160
#define BOOLOID
Definition: pg_type.h:288
double timestamp
#define ARR_NDIM(a)
Definition: array.h:271
#define UNKNOWNOID
Definition: pg_type.h:423
JsonbTypeCategory key_category
Definition: jsonb.c:57
enum jbvType type
Definition: jsonb.h:250
#define DatumGetTextP(X)
Definition: fmgr.h:248
static void jsonb_in_object_start(void *pstate)
Definition: jsonb.c:265
void deconstruct_array(ArrayType *array, Oid elmtype, int elmlen, bool elmbyval, char elmalign, Datum **elemsp, bool **nullsp, int *nelemsp)
Definition: arrayfuncs.c:3475
Datum jsonb_build_array_noargs(PG_FUNCTION_ARGS)
Definition: jsonb.c:1310
#define PG_GETARG_JSONB(x)
Definition: jsonb.h:70
#define USE_XSD_DATES
Definition: miscadmin.h:213
int tm_year
Definition: pgtime.h:32
Datum jsonb_in(PG_FUNCTION_ARGS)
Definition: jsonb.c:96
char * OidOutputFunctionCall(Oid functionId, Datum val)
Definition: fmgr.c:2006
void * palloc(Size size)
Definition: mcxt.c:891
int errmsg(const char *fmt,...)
Definition: elog.c:797
void pq_sendint(StringInfo buf, int i, int b)
Definition: pqformat.c:236
CoercionPathType find_coercion_pathway(Oid targetTypeId, Oid sourceTypeId, CoercionContext ccontext, Oid *funcid)
Oid val_output_func
Definition: jsonb.c:60
int i
#define NameStr(name)
Definition: c.h:494
#define CStringGetTextDatum(s)
Definition: builtins.h:90
void * arg
#define PG_GETARG_CSTRING(n)
Definition: fmgr.h:233
Definition: c.h:434
#define PG_FUNCTION_ARGS
Definition: fmgr.h:150
unsigned int pq_getmsgint(StringInfo msg, int b)
Definition: pqformat.c:448
#define POSTGRES_EPOCH_JDATE
Definition: timestamp.h:185
json_ofield_action object_field_start
Definition: jsonapi.h:88
#define elog
Definition: elog.h:219
static void jsonb_in_object_field_start(void *pstate, char *fname, bool isnull)
Definition: jsonb.c:297
Datum jsonb_agg_finalfn(PG_FUNCTION_ARGS)
Definition: jsonb.c:1680
#define ReleaseTupleDesc(tupdesc)
Definition: tupdesc.h:107
Oid getBaseType(Oid typid)
Definition: lsyscache.c:2239
#define ARR_ELEMTYPE(a)
Definition: array.h:273
void * semstate
Definition: jsonapi.h:83
void appendBinaryStringInfo(StringInfo str, const char *data, int datalen)
Definition: stringinfo.c:240
long val
Definition: informix.c:689
#define PG_RETURN_NULL()
Definition: fmgr.h:289
JsonbIteratorToken JsonbIteratorNext(JsonbIterator **it, JsonbValue *val, bool skipNested)
Definition: jsonb_util.c:754
Definition: jsonb.h:25
JsonTokenType
Definition: jsonapi.h:19
#define DatumGetTimestamp(X)
Definition: timestamp.h:47
#define HeapTupleHeaderGetDatumLength(tup)
Definition: htup_details.h:439
#define DatumGetArrayTypeP(X)
Definition: array.h:242