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_P(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_P(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_P(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)) || typoid == ANYARRAYOID
648  || typoid == RECORDARRAYOID)
649  *tcategory = JSONBTYPE_ARRAY;
650  else if (type_is_rowtype(typoid)) /* includes RECORDOID */
651  *tcategory = JSONBTYPE_COMPOSITE;
652  else
653  {
654  /* It's probably the general case ... */
655  *tcategory = JSONBTYPE_OTHER;
656 
657  /*
658  * but first let's look for a cast to json (note: not to
659  * jsonb) if it's not built-in.
660  */
661  if (typoid >= FirstNormalObjectId)
662  {
663  Oid castfunc;
664  CoercionPathType ctype;
665 
666  ctype = find_coercion_pathway(JSONOID, typoid,
667  COERCION_EXPLICIT, &castfunc);
668  if (ctype == COERCION_PATH_FUNC && OidIsValid(castfunc))
669  {
670  *tcategory = JSONBTYPE_JSONCAST;
671  *outfuncoid = castfunc;
672  }
673  else
674  {
675  /* not a cast type, so just get the usual output func */
676  getTypeOutputInfo(typoid, outfuncoid, &typisvarlena);
677  }
678  }
679  else
680  {
681  /* any other builtin type */
682  getTypeOutputInfo(typoid, outfuncoid, &typisvarlena);
683  }
684  break;
685  }
686  }
687 }
688 
689 /*
690  * Turn a Datum into jsonb, adding it to the result JsonbInState.
691  *
692  * tcategory and outfuncoid are from a previous call to json_categorize_type,
693  * except that if is_null is true then they can be invalid.
694  *
695  * If key_scalar is true, the value is stored as a key, so insist
696  * it's of an acceptable type, and force it to be a jbvString.
697  */
698 static void
699 datum_to_jsonb(Datum val, bool is_null, JsonbInState *result,
700  JsonbTypeCategory tcategory, Oid outfuncoid,
701  bool key_scalar)
702 {
703  char *outputstr;
704  bool numeric_error;
705  JsonbValue jb;
706  bool scalar_jsonb = false;
707 
709 
710  /* Convert val to a JsonbValue in jb (in most cases) */
711  if (is_null)
712  {
713  Assert(!key_scalar);
714  jb.type = jbvNull;
715  }
716  else if (key_scalar &&
717  (tcategory == JSONBTYPE_ARRAY ||
718  tcategory == JSONBTYPE_COMPOSITE ||
719  tcategory == JSONBTYPE_JSON ||
720  tcategory == JSONBTYPE_JSONB ||
721  tcategory == JSONBTYPE_JSONCAST))
722  {
723  ereport(ERROR,
724  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
725  errmsg("key value must be scalar, not array, composite, or json")));
726  }
727  else
728  {
729  if (tcategory == JSONBTYPE_JSONCAST)
730  val = OidFunctionCall1(outfuncoid, val);
731 
732  switch (tcategory)
733  {
734  case JSONBTYPE_ARRAY:
735  array_to_jsonb_internal(val, result);
736  break;
737  case JSONBTYPE_COMPOSITE:
738  composite_to_jsonb(val, result);
739  break;
740  case JSONBTYPE_BOOL:
741  if (key_scalar)
742  {
743  outputstr = DatumGetBool(val) ? "true" : "false";
744  jb.type = jbvString;
745  jb.val.string.len = strlen(outputstr);
746  jb.val.string.val = outputstr;
747  }
748  else
749  {
750  jb.type = jbvBool;
751  jb.val.boolean = DatumGetBool(val);
752  }
753  break;
754  case JSONBTYPE_NUMERIC:
755  outputstr = OidOutputFunctionCall(outfuncoid, val);
756  if (key_scalar)
757  {
758  /* always quote keys */
759  jb.type = jbvString;
760  jb.val.string.len = strlen(outputstr);
761  jb.val.string.val = outputstr;
762  }
763  else
764  {
765  /*
766  * Make it numeric if it's a valid JSON number, otherwise
767  * a string. Invalid numeric output will always have an
768  * 'N' or 'n' in it (I think).
769  */
770  numeric_error = (strchr(outputstr, 'N') != NULL ||
771  strchr(outputstr, 'n') != NULL);
772  if (!numeric_error)
773  {
774  jb.type = jbvNumeric;
775  jb.val.numeric = DatumGetNumeric(DirectFunctionCall3(numeric_in, CStringGetDatum(outputstr), 0, -1));
776 
777  pfree(outputstr);
778  }
779  else
780  {
781  jb.type = jbvString;
782  jb.val.string.len = strlen(outputstr);
783  jb.val.string.val = outputstr;
784  }
785  }
786  break;
787  case JSONBTYPE_DATE:
788  {
789  DateADT date;
790  struct pg_tm tm;
791  char buf[MAXDATELEN + 1];
792 
793  date = DatumGetDateADT(val);
794  /* Same as date_out(), but forcing DateStyle */
795  if (DATE_NOT_FINITE(date))
796  EncodeSpecialDate(date, buf);
797  else
798  {
800  &(tm.tm_year), &(tm.tm_mon), &(tm.tm_mday));
801  EncodeDateOnly(&tm, USE_XSD_DATES, buf);
802  }
803  jb.type = jbvString;
804  jb.val.string.len = strlen(buf);
805  jb.val.string.val = pstrdup(buf);
806  }
807  break;
808  case JSONBTYPE_TIMESTAMP:
809  {
811  struct pg_tm tm;
812  fsec_t fsec;
813  char buf[MAXDATELEN + 1];
814 
815  timestamp = DatumGetTimestamp(val);
816  /* Same as timestamp_out(), but forcing DateStyle */
817  if (TIMESTAMP_NOT_FINITE(timestamp))
818  EncodeSpecialTimestamp(timestamp, buf);
819  else if (timestamp2tm(timestamp, NULL, &tm, &fsec, NULL, NULL) == 0)
820  EncodeDateTime(&tm, fsec, false, 0, NULL, USE_XSD_DATES, buf);
821  else
822  ereport(ERROR,
823  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
824  errmsg("timestamp out of range")));
825  jb.type = jbvString;
826  jb.val.string.len = strlen(buf);
827  jb.val.string.val = pstrdup(buf);
828  }
829  break;
831  {
833  struct pg_tm tm;
834  int tz;
835  fsec_t fsec;
836  const char *tzn = NULL;
837  char buf[MAXDATELEN + 1];
838 
839  timestamp = DatumGetTimestampTz(val);
840  /* Same as timestamptz_out(), but forcing DateStyle */
841  if (TIMESTAMP_NOT_FINITE(timestamp))
842  EncodeSpecialTimestamp(timestamp, buf);
843  else if (timestamp2tm(timestamp, &tz, &tm, &fsec, &tzn, NULL) == 0)
844  EncodeDateTime(&tm, fsec, true, tz, tzn, USE_XSD_DATES, buf);
845  else
846  ereport(ERROR,
847  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
848  errmsg("timestamp out of range")));
849  jb.type = jbvString;
850  jb.val.string.len = strlen(buf);
851  jb.val.string.val = pstrdup(buf);
852  }
853  break;
854  case JSONBTYPE_JSONCAST:
855  case JSONBTYPE_JSON:
856  {
857  /* parse the json right into the existing result object */
858  JsonLexContext *lex;
859  JsonSemAction sem;
860  text *json = DatumGetTextPP(val);
861 
862  lex = makeJsonLexContext(json, true);
863 
864  memset(&sem, 0, sizeof(sem));
865 
866  sem.semstate = (void *) result;
867 
872  sem.scalar = jsonb_in_scalar;
874 
875  pg_parse_json(lex, &sem);
876 
877  }
878  break;
879  case JSONBTYPE_JSONB:
880  {
881  Jsonb *jsonb = DatumGetJsonbP(val);
882  JsonbIterator *it;
883 
884  it = JsonbIteratorInit(&jsonb->root);
885 
886  if (JB_ROOT_IS_SCALAR(jsonb))
887  {
888  (void) JsonbIteratorNext(&it, &jb, true);
889  Assert(jb.type == jbvArray);
890  (void) JsonbIteratorNext(&it, &jb, true);
891  scalar_jsonb = true;
892  }
893  else
894  {
895  JsonbIteratorToken type;
896 
897  while ((type = JsonbIteratorNext(&it, &jb, false))
898  != WJB_DONE)
899  {
900  if (type == WJB_END_ARRAY || type == WJB_END_OBJECT ||
901  type == WJB_BEGIN_ARRAY || type == WJB_BEGIN_OBJECT)
902  result->res = pushJsonbValue(&result->parseState,
903  type, NULL);
904  else
905  result->res = pushJsonbValue(&result->parseState,
906  type, &jb);
907  }
908  }
909  }
910  break;
911  default:
912  outputstr = OidOutputFunctionCall(outfuncoid, val);
913  jb.type = jbvString;
914  jb.val.string.len = checkStringLen(strlen(outputstr));
915  jb.val.string.val = outputstr;
916  break;
917  }
918  }
919 
920  /* Now insert jb into result, unless we did it recursively */
921  if (!is_null && !scalar_jsonb &&
922  tcategory >= JSONBTYPE_JSON && tcategory <= JSONBTYPE_JSONCAST)
923  {
924  /* work has been done recursively */
925  return;
926  }
927  else if (result->parseState == NULL)
928  {
929  /* single root scalar */
930  JsonbValue va;
931 
932  va.type = jbvArray;
933  va.val.array.rawScalar = true;
934  va.val.array.nElems = 1;
935 
936  result->res = pushJsonbValue(&result->parseState, WJB_BEGIN_ARRAY, &va);
937  result->res = pushJsonbValue(&result->parseState, WJB_ELEM, &jb);
938  result->res = pushJsonbValue(&result->parseState, WJB_END_ARRAY, NULL);
939  }
940  else
941  {
942  JsonbValue *o = &result->parseState->contVal;
943 
944  switch (o->type)
945  {
946  case jbvArray:
947  result->res = pushJsonbValue(&result->parseState, WJB_ELEM, &jb);
948  break;
949  case jbvObject:
950  result->res = pushJsonbValue(&result->parseState,
951  key_scalar ? WJB_KEY : WJB_VALUE,
952  &jb);
953  break;
954  default:
955  elog(ERROR, "unexpected parent of nested structure");
956  }
957  }
958 }
959 
960 /*
961  * Process a single dimension of an array.
962  * If it's the innermost dimension, output the values, otherwise call
963  * ourselves recursively to process the next dimension.
964  */
965 static void
966 array_dim_to_jsonb(JsonbInState *result, int dim, int ndims, int *dims, Datum *vals,
967  bool *nulls, int *valcount, JsonbTypeCategory tcategory,
968  Oid outfuncoid)
969 {
970  int i;
971 
972  Assert(dim < ndims);
973 
974  result->res = pushJsonbValue(&result->parseState, WJB_BEGIN_ARRAY, NULL);
975 
976  for (i = 1; i <= dims[dim]; i++)
977  {
978  if (dim + 1 == ndims)
979  {
980  datum_to_jsonb(vals[*valcount], nulls[*valcount], result, tcategory,
981  outfuncoid, false);
982  (*valcount)++;
983  }
984  else
985  {
986  array_dim_to_jsonb(result, dim + 1, ndims, dims, vals, nulls,
987  valcount, tcategory, outfuncoid);
988  }
989  }
990 
991  result->res = pushJsonbValue(&result->parseState, WJB_END_ARRAY, NULL);
992 }
993 
994 /*
995  * Turn an array into JSON.
996  */
997 static void
999 {
1000  ArrayType *v = DatumGetArrayTypeP(array);
1001  Oid element_type = ARR_ELEMTYPE(v);
1002  int *dim;
1003  int ndim;
1004  int nitems;
1005  int count = 0;
1006  Datum *elements;
1007  bool *nulls;
1008  int16 typlen;
1009  bool typbyval;
1010  char typalign;
1011  JsonbTypeCategory tcategory;
1012  Oid outfuncoid;
1013 
1014  ndim = ARR_NDIM(v);
1015  dim = ARR_DIMS(v);
1016  nitems = ArrayGetNItems(ndim, dim);
1017 
1018  if (nitems <= 0)
1019  {
1020  result->res = pushJsonbValue(&result->parseState, WJB_BEGIN_ARRAY, NULL);
1021  result->res = pushJsonbValue(&result->parseState, WJB_END_ARRAY, NULL);
1022  return;
1023  }
1024 
1025  get_typlenbyvalalign(element_type,
1026  &typlen, &typbyval, &typalign);
1027 
1028  jsonb_categorize_type(element_type,
1029  &tcategory, &outfuncoid);
1030 
1031  deconstruct_array(v, element_type, typlen, typbyval,
1032  typalign, &elements, &nulls,
1033  &nitems);
1034 
1035  array_dim_to_jsonb(result, 0, ndim, dim, elements, nulls, &count, tcategory,
1036  outfuncoid);
1037 
1038  pfree(elements);
1039  pfree(nulls);
1040 }
1041 
1042 /*
1043  * Turn a composite / record into JSON.
1044  */
1045 static void
1047 {
1048  HeapTupleHeader td;
1049  Oid tupType;
1050  int32 tupTypmod;
1051  TupleDesc tupdesc;
1052  HeapTupleData tmptup,
1053  *tuple;
1054  int i;
1055 
1056  td = DatumGetHeapTupleHeader(composite);
1057 
1058  /* Extract rowtype info and find a tupdesc */
1059  tupType = HeapTupleHeaderGetTypeId(td);
1060  tupTypmod = HeapTupleHeaderGetTypMod(td);
1061  tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
1062 
1063  /* Build a temporary HeapTuple control structure */
1064  tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
1065  tmptup.t_data = td;
1066  tuple = &tmptup;
1067 
1068  result->res = pushJsonbValue(&result->parseState, WJB_BEGIN_OBJECT, NULL);
1069 
1070  for (i = 0; i < tupdesc->natts; i++)
1071  {
1072  Datum val;
1073  bool isnull;
1074  char *attname;
1075  JsonbTypeCategory tcategory;
1076  Oid outfuncoid;
1077  JsonbValue v;
1078  Form_pg_attribute att = TupleDescAttr(tupdesc, i);
1079 
1080  if (att->attisdropped)
1081  continue;
1082 
1083  attname = NameStr(att->attname);
1084 
1085  v.type = jbvString;
1086  /* don't need checkStringLen here - can't exceed maximum name length */
1087  v.val.string.len = strlen(attname);
1088  v.val.string.val = attname;
1089 
1090  result->res = pushJsonbValue(&result->parseState, WJB_KEY, &v);
1091 
1092  val = heap_getattr(tuple, i + 1, tupdesc, &isnull);
1093 
1094  if (isnull)
1095  {
1096  tcategory = JSONBTYPE_NULL;
1097  outfuncoid = InvalidOid;
1098  }
1099  else
1100  jsonb_categorize_type(att->atttypid, &tcategory, &outfuncoid);
1101 
1102  datum_to_jsonb(val, isnull, result, tcategory, outfuncoid, false);
1103  }
1104 
1105  result->res = pushJsonbValue(&result->parseState, WJB_END_OBJECT, NULL);
1106  ReleaseTupleDesc(tupdesc);
1107 }
1108 
1109 /*
1110  * Append JSON text for "val" to "result".
1111  *
1112  * This is just a thin wrapper around datum_to_jsonb. If the same type will be
1113  * printed many times, avoid using this; better to do the jsonb_categorize_type
1114  * lookups only once.
1115  */
1116 
1117 static void
1118 add_jsonb(Datum val, bool is_null, JsonbInState *result,
1119  Oid val_type, bool key_scalar)
1120 {
1121  JsonbTypeCategory tcategory;
1122  Oid outfuncoid;
1123 
1124  if (val_type == InvalidOid)
1125  ereport(ERROR,
1126  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1127  errmsg("could not determine input data type")));
1128 
1129  if (is_null)
1130  {
1131  tcategory = JSONBTYPE_NULL;
1132  outfuncoid = InvalidOid;
1133  }
1134  else
1135  jsonb_categorize_type(val_type,
1136  &tcategory, &outfuncoid);
1137 
1138  datum_to_jsonb(val, is_null, result, tcategory, outfuncoid, key_scalar);
1139 }
1140 
1141 /*
1142  * SQL function to_jsonb(anyvalue)
1143  */
1144 Datum
1146 {
1147  Datum val = PG_GETARG_DATUM(0);
1148  Oid val_type = get_fn_expr_argtype(fcinfo->flinfo, 0);
1149  JsonbInState result;
1150  JsonbTypeCategory tcategory;
1151  Oid outfuncoid;
1152 
1153  if (val_type == InvalidOid)
1154  ereport(ERROR,
1155  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1156  errmsg("could not determine input data type")));
1157 
1158  jsonb_categorize_type(val_type,
1159  &tcategory, &outfuncoid);
1160 
1161  memset(&result, 0, sizeof(JsonbInState));
1162 
1163  datum_to_jsonb(val, false, &result, tcategory, outfuncoid, false);
1164 
1166 }
1167 
1168 /*
1169  * SQL function jsonb_build_object(variadic "any")
1170  */
1171 Datum
1173 {
1174  int nargs = PG_NARGS();
1175  int i;
1176  Datum arg;
1177  Oid val_type;
1178  JsonbInState result;
1179 
1180  if (nargs % 2 != 0)
1181  ereport(ERROR,
1182  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1183  errmsg("invalid number of arguments: object must be matched key value pairs")));
1184 
1185  memset(&result, 0, sizeof(JsonbInState));
1186 
1187  result.res = pushJsonbValue(&result.parseState, WJB_BEGIN_OBJECT, NULL);
1188 
1189  for (i = 0; i < nargs; i += 2)
1190  {
1191  /* process key */
1192 
1193  if (PG_ARGISNULL(i))
1194  ereport(ERROR,
1195  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1196  errmsg("argument %d: key must not be null", i + 1)));
1197  val_type = get_fn_expr_argtype(fcinfo->flinfo, i);
1198 
1199  /*
1200  * turn a constant (more or less literal) value that's of unknown type
1201  * into text. Unknowns come in as a cstring pointer.
1202  */
1203  if (val_type == UNKNOWNOID && get_fn_expr_arg_stable(fcinfo->flinfo, i))
1204  {
1205  val_type = TEXTOID;
1207  }
1208  else
1209  {
1210  arg = PG_GETARG_DATUM(i);
1211  }
1212  if (val_type == InvalidOid || val_type == UNKNOWNOID)
1213  ereport(ERROR,
1214  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1215  errmsg("could not determine data type for argument %d", i + 1)));
1216 
1217  add_jsonb(arg, false, &result, val_type, true);
1218 
1219  /* process value */
1220 
1221  val_type = get_fn_expr_argtype(fcinfo->flinfo, i + 1);
1222  /* see comments above */
1223  if (val_type == UNKNOWNOID && get_fn_expr_arg_stable(fcinfo->flinfo, i + 1))
1224  {
1225  val_type = TEXTOID;
1226  if (PG_ARGISNULL(i + 1))
1227  arg = (Datum) 0;
1228  else
1229  arg = CStringGetTextDatum(PG_GETARG_POINTER(i + 1));
1230  }
1231  else
1232  {
1233  arg = PG_GETARG_DATUM(i + 1);
1234  }
1235  if (val_type == InvalidOid || val_type == UNKNOWNOID)
1236  ereport(ERROR,
1237  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1238  errmsg("could not determine data type for argument %d", i + 2)));
1239  add_jsonb(arg, PG_ARGISNULL(i + 1), &result, val_type, false);
1240  }
1241 
1242  result.res = pushJsonbValue(&result.parseState, WJB_END_OBJECT, NULL);
1243 
1245 }
1246 
1247 /*
1248  * degenerate case of jsonb_build_object where it gets 0 arguments.
1249  */
1250 Datum
1252 {
1253  JsonbInState result;
1254 
1255  memset(&result, 0, sizeof(JsonbInState));
1256 
1257  (void) pushJsonbValue(&result.parseState, WJB_BEGIN_OBJECT, NULL);
1258  result.res = pushJsonbValue(&result.parseState, WJB_END_OBJECT, NULL);
1259 
1261 }
1262 
1263 /*
1264  * SQL function jsonb_build_array(variadic "any")
1265  */
1266 Datum
1268 {
1269  int nargs = PG_NARGS();
1270  int i;
1271  Datum arg;
1272  Oid val_type;
1273  JsonbInState result;
1274 
1275  memset(&result, 0, sizeof(JsonbInState));
1276 
1277  result.res = pushJsonbValue(&result.parseState, WJB_BEGIN_ARRAY, NULL);
1278 
1279  for (i = 0; i < nargs; i++)
1280  {
1281  val_type = get_fn_expr_argtype(fcinfo->flinfo, i);
1282  /* see comments in jsonb_build_object above */
1283  if (val_type == UNKNOWNOID && get_fn_expr_arg_stable(fcinfo->flinfo, i))
1284  {
1285  val_type = TEXTOID;
1286  if (PG_ARGISNULL(i))
1287  arg = (Datum) 0;
1288  else
1290  }
1291  else
1292  {
1293  arg = PG_GETARG_DATUM(i);
1294  }
1295  if (val_type == InvalidOid || val_type == UNKNOWNOID)
1296  ereport(ERROR,
1297  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1298  errmsg("could not determine data type for argument %d", i + 1)));
1299  add_jsonb(arg, PG_ARGISNULL(i), &result, val_type, false);
1300  }
1301 
1302  result.res = pushJsonbValue(&result.parseState, WJB_END_ARRAY, NULL);
1303 
1305 }
1306 
1307 /*
1308  * degenerate case of jsonb_build_array where it gets 0 arguments.
1309  */
1310 Datum
1312 {
1313  JsonbInState result;
1314 
1315  memset(&result, 0, sizeof(JsonbInState));
1316 
1317  (void) pushJsonbValue(&result.parseState, WJB_BEGIN_ARRAY, NULL);
1318  result.res = pushJsonbValue(&result.parseState, WJB_END_ARRAY, NULL);
1319 
1321 }
1322 
1323 
1324 /*
1325  * SQL function jsonb_object(text[])
1326  *
1327  * take a one or two dimensional array of text as name value pairs
1328  * for a jsonb object.
1329  *
1330  */
1331 Datum
1333 {
1334  ArrayType *in_array = PG_GETARG_ARRAYTYPE_P(0);
1335  int ndims = ARR_NDIM(in_array);
1336  Datum *in_datums;
1337  bool *in_nulls;
1338  int in_count,
1339  count,
1340  i;
1341  JsonbInState result;
1342 
1343  memset(&result, 0, sizeof(JsonbInState));
1344 
1345  (void) pushJsonbValue(&result.parseState, WJB_BEGIN_OBJECT, NULL);
1346 
1347  switch (ndims)
1348  {
1349  case 0:
1350  goto close_object;
1351  break;
1352 
1353  case 1:
1354  if ((ARR_DIMS(in_array)[0]) % 2)
1355  ereport(ERROR,
1356  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1357  errmsg("array must have even number of elements")));
1358  break;
1359 
1360  case 2:
1361  if ((ARR_DIMS(in_array)[1]) != 2)
1362  ereport(ERROR,
1363  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1364  errmsg("array must have two columns")));
1365  break;
1366 
1367  default:
1368  ereport(ERROR,
1369  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1370  errmsg("wrong number of array subscripts")));
1371  }
1372 
1373  deconstruct_array(in_array,
1374  TEXTOID, -1, false, 'i',
1375  &in_datums, &in_nulls, &in_count);
1376 
1377  count = in_count / 2;
1378 
1379  for (i = 0; i < count; ++i)
1380  {
1381  JsonbValue v;
1382  char *str;
1383  int len;
1384 
1385  if (in_nulls[i * 2])
1386  ereport(ERROR,
1387  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1388  errmsg("null value not allowed for object key")));
1389 
1390  str = TextDatumGetCString(in_datums[i * 2]);
1391  len = strlen(str);
1392 
1393  v.type = jbvString;
1394 
1395  v.val.string.len = len;
1396  v.val.string.val = str;
1397 
1398  (void) pushJsonbValue(&result.parseState, WJB_KEY, &v);
1399 
1400  if (in_nulls[i * 2 + 1])
1401  {
1402  v.type = jbvNull;
1403  }
1404  else
1405  {
1406  str = TextDatumGetCString(in_datums[i * 2 + 1]);
1407  len = strlen(str);
1408 
1409  v.type = jbvString;
1410 
1411  v.val.string.len = len;
1412  v.val.string.val = str;
1413  }
1414 
1415  (void) pushJsonbValue(&result.parseState, WJB_VALUE, &v);
1416  }
1417 
1418  pfree(in_datums);
1419  pfree(in_nulls);
1420 
1421 close_object:
1422  result.res = pushJsonbValue(&result.parseState, WJB_END_OBJECT, NULL);
1423 
1425 }
1426 
1427 /*
1428  * SQL function jsonb_object(text[], text[])
1429  *
1430  * take separate name and value arrays of text to construct a jsonb object
1431  * pairwise.
1432  */
1433 Datum
1435 {
1436  ArrayType *key_array = PG_GETARG_ARRAYTYPE_P(0);
1437  ArrayType *val_array = PG_GETARG_ARRAYTYPE_P(1);
1438  int nkdims = ARR_NDIM(key_array);
1439  int nvdims = ARR_NDIM(val_array);
1440  Datum *key_datums,
1441  *val_datums;
1442  bool *key_nulls,
1443  *val_nulls;
1444  int key_count,
1445  val_count,
1446  i;
1447  JsonbInState result;
1448 
1449  memset(&result, 0, sizeof(JsonbInState));
1450 
1451  (void) pushJsonbValue(&result.parseState, WJB_BEGIN_OBJECT, NULL);
1452 
1453  if (nkdims > 1 || nkdims != nvdims)
1454  ereport(ERROR,
1455  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1456  errmsg("wrong number of array subscripts")));
1457 
1458  if (nkdims == 0)
1459  goto close_object;
1460 
1461  deconstruct_array(key_array,
1462  TEXTOID, -1, false, 'i',
1463  &key_datums, &key_nulls, &key_count);
1464 
1465  deconstruct_array(val_array,
1466  TEXTOID, -1, false, 'i',
1467  &val_datums, &val_nulls, &val_count);
1468 
1469  if (key_count != val_count)
1470  ereport(ERROR,
1471  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1472  errmsg("mismatched array dimensions")));
1473 
1474  for (i = 0; i < key_count; ++i)
1475  {
1476  JsonbValue v;
1477  char *str;
1478  int len;
1479 
1480  if (key_nulls[i])
1481  ereport(ERROR,
1482  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1483  errmsg("null value not allowed for object key")));
1484 
1485  str = TextDatumGetCString(key_datums[i]);
1486  len = strlen(str);
1487 
1488  v.type = jbvString;
1489 
1490  v.val.string.len = len;
1491  v.val.string.val = str;
1492 
1493  (void) pushJsonbValue(&result.parseState, WJB_KEY, &v);
1494 
1495  if (val_nulls[i])
1496  {
1497  v.type = jbvNull;
1498  }
1499  else
1500  {
1501  str = TextDatumGetCString(val_datums[i]);
1502  len = strlen(str);
1503 
1504  v.type = jbvString;
1505 
1506  v.val.string.len = len;
1507  v.val.string.val = str;
1508  }
1509 
1510  (void) pushJsonbValue(&result.parseState, WJB_VALUE, &v);
1511  }
1512 
1513  pfree(key_datums);
1514  pfree(key_nulls);
1515  pfree(val_datums);
1516  pfree(val_nulls);
1517 
1518 close_object:
1519  result.res = pushJsonbValue(&result.parseState, WJB_END_OBJECT, NULL);
1520 
1522 }
1523 
1524 
1525 /*
1526  * shallow clone of a parse state, suitable for use in aggregate
1527  * final functions that will only append to the values rather than
1528  * change them.
1529  */
1530 static JsonbParseState *
1532 {
1533  JsonbParseState *result,
1534  *icursor,
1535  *ocursor;
1536 
1537  if (state == NULL)
1538  return NULL;
1539 
1540  result = palloc(sizeof(JsonbParseState));
1541  icursor = state;
1542  ocursor = result;
1543  for (;;)
1544  {
1545  ocursor->contVal = icursor->contVal;
1546  ocursor->size = icursor->size;
1547  icursor = icursor->next;
1548  if (icursor == NULL)
1549  break;
1550  ocursor->next = palloc(sizeof(JsonbParseState));
1551  ocursor = ocursor->next;
1552  }
1553  ocursor->next = NULL;
1554 
1555  return result;
1556 }
1557 
1558 
1559 /*
1560  * jsonb_agg aggregate function
1561  */
1562 Datum
1564 {
1565  MemoryContext oldcontext,
1566  aggcontext;
1568  JsonbInState elem;
1569  Datum val;
1570  JsonbInState *result;
1571  bool single_scalar = false;
1572  JsonbIterator *it;
1573  Jsonb *jbelem;
1574  JsonbValue v;
1575  JsonbIteratorToken type;
1576 
1577  if (!AggCheckCallContext(fcinfo, &aggcontext))
1578  {
1579  /* cannot be called directly because of internal-type argument */
1580  elog(ERROR, "jsonb_agg_transfn called in non-aggregate context");
1581  }
1582 
1583  /* set up the accumulator on the first go round */
1584 
1585  if (PG_ARGISNULL(0))
1586  {
1587  Oid arg_type = get_fn_expr_argtype(fcinfo->flinfo, 1);
1588 
1589  if (arg_type == InvalidOid)
1590  ereport(ERROR,
1591  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1592  errmsg("could not determine input data type")));
1593 
1594  oldcontext = MemoryContextSwitchTo(aggcontext);
1595  state = palloc(sizeof(JsonbAggState));
1596  result = palloc0(sizeof(JsonbInState));
1597  state->res = result;
1598  result->res = pushJsonbValue(&result->parseState,
1599  WJB_BEGIN_ARRAY, NULL);
1600  MemoryContextSwitchTo(oldcontext);
1601 
1602  jsonb_categorize_type(arg_type, &state->val_category,
1603  &state->val_output_func);
1604  }
1605  else
1606  {
1607  state = (JsonbAggState *) PG_GETARG_POINTER(0);
1608  result = state->res;
1609  }
1610 
1611  /* turn the argument into jsonb in the normal function context */
1612 
1613  val = PG_ARGISNULL(1) ? (Datum) 0 : PG_GETARG_DATUM(1);
1614 
1615  memset(&elem, 0, sizeof(JsonbInState));
1616 
1617  datum_to_jsonb(val, PG_ARGISNULL(1), &elem, state->val_category,
1618  state->val_output_func, false);
1619 
1620  jbelem = JsonbValueToJsonb(elem.res);
1621 
1622  /* switch to the aggregate context for accumulation operations */
1623 
1624  oldcontext = MemoryContextSwitchTo(aggcontext);
1625 
1626  it = JsonbIteratorInit(&jbelem->root);
1627 
1628  while ((type = JsonbIteratorNext(&it, &v, false)) != WJB_DONE)
1629  {
1630  switch (type)
1631  {
1632  case WJB_BEGIN_ARRAY:
1633  if (v.val.array.rawScalar)
1634  single_scalar = true;
1635  else
1636  result->res = pushJsonbValue(&result->parseState,
1637  type, NULL);
1638  break;
1639  case WJB_END_ARRAY:
1640  if (!single_scalar)
1641  result->res = pushJsonbValue(&result->parseState,
1642  type, NULL);
1643  break;
1644  case WJB_BEGIN_OBJECT:
1645  case WJB_END_OBJECT:
1646  result->res = pushJsonbValue(&result->parseState,
1647  type, NULL);
1648  break;
1649  case WJB_ELEM:
1650  case WJB_KEY:
1651  case WJB_VALUE:
1652  if (v.type == jbvString)
1653  {
1654  /* copy string values in the aggregate context */
1655  char *buf = palloc(v.val.string.len + 1);
1656 
1657  snprintf(buf, v.val.string.len + 1, "%s", v.val.string.val);
1658  v.val.string.val = buf;
1659  }
1660  else if (v.type == jbvNumeric)
1661  {
1662  /* same for numeric */
1663  v.val.numeric =
1665  NumericGetDatum(v.val.numeric)));
1666  }
1667  result->res = pushJsonbValue(&result->parseState,
1668  type, &v);
1669  break;
1670  default:
1671  elog(ERROR, "unknown jsonb iterator token type");
1672  }
1673  }
1674 
1675  MemoryContextSwitchTo(oldcontext);
1676 
1677  PG_RETURN_POINTER(state);
1678 }
1679 
1680 Datum
1682 {
1683  JsonbAggState *arg;
1684  JsonbInState result;
1685  Jsonb *out;
1686 
1687  /* cannot be called directly because of internal-type argument */
1688  Assert(AggCheckCallContext(fcinfo, NULL));
1689 
1690  if (PG_ARGISNULL(0))
1691  PG_RETURN_NULL(); /* returns null iff no input values */
1692 
1693  arg = (JsonbAggState *) PG_GETARG_POINTER(0);
1694 
1695  /*
1696  * We need to do a shallow clone of the argument in case the final
1697  * function is called more than once, so we avoid changing the argument. A
1698  * shallow clone is sufficient as we aren't going to change any of the
1699  * values, just add the final array end marker.
1700  */
1701 
1702  result.parseState = clone_parse_state(arg->res->parseState);
1703 
1704  result.res = pushJsonbValue(&result.parseState,
1705  WJB_END_ARRAY, NULL);
1706 
1707  out = JsonbValueToJsonb(result.res);
1708 
1709  PG_RETURN_POINTER(out);
1710 }
1711 
1712 /*
1713  * jsonb_object_agg aggregate function
1714  */
1715 Datum
1717 {
1718  MemoryContext oldcontext,
1719  aggcontext;
1720  JsonbInState elem;
1722  Datum val;
1723  JsonbInState *result;
1724  bool single_scalar;
1725  JsonbIterator *it;
1726  Jsonb *jbkey,
1727  *jbval;
1728  JsonbValue v;
1729  JsonbIteratorToken type;
1730 
1731  if (!AggCheckCallContext(fcinfo, &aggcontext))
1732  {
1733  /* cannot be called directly because of internal-type argument */
1734  elog(ERROR, "jsonb_object_agg_transfn called in non-aggregate context");
1735  }
1736 
1737  /* set up the accumulator on the first go round */
1738 
1739  if (PG_ARGISNULL(0))
1740  {
1741  Oid arg_type;
1742 
1743  oldcontext = MemoryContextSwitchTo(aggcontext);
1744  state = palloc(sizeof(JsonbAggState));
1745  result = palloc0(sizeof(JsonbInState));
1746  state->res = result;
1747  result->res = pushJsonbValue(&result->parseState,
1748  WJB_BEGIN_OBJECT, NULL);
1749  MemoryContextSwitchTo(oldcontext);
1750 
1751  arg_type = get_fn_expr_argtype(fcinfo->flinfo, 1);
1752 
1753  if (arg_type == InvalidOid)
1754  ereport(ERROR,
1755  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1756  errmsg("could not determine input data type")));
1757 
1758  jsonb_categorize_type(arg_type, &state->key_category,
1759  &state->key_output_func);
1760 
1761  arg_type = get_fn_expr_argtype(fcinfo->flinfo, 2);
1762 
1763  if (arg_type == InvalidOid)
1764  ereport(ERROR,
1765  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1766  errmsg("could not determine input data type")));
1767 
1768  jsonb_categorize_type(arg_type, &state->val_category,
1769  &state->val_output_func);
1770  }
1771  else
1772  {
1773  state = (JsonbAggState *) PG_GETARG_POINTER(0);
1774  result = state->res;
1775  }
1776 
1777  /* turn the argument into jsonb in the normal function context */
1778 
1779  if (PG_ARGISNULL(1))
1780  ereport(ERROR,
1781  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1782  errmsg("field name must not be null")));
1783 
1784  val = PG_GETARG_DATUM(1);
1785 
1786  memset(&elem, 0, sizeof(JsonbInState));
1787 
1788  datum_to_jsonb(val, false, &elem, state->key_category,
1789  state->key_output_func, true);
1790 
1791  jbkey = JsonbValueToJsonb(elem.res);
1792 
1793  val = PG_ARGISNULL(2) ? (Datum) 0 : PG_GETARG_DATUM(2);
1794 
1795  memset(&elem, 0, sizeof(JsonbInState));
1796 
1797  datum_to_jsonb(val, PG_ARGISNULL(2), &elem, state->val_category,
1798  state->val_output_func, false);
1799 
1800  jbval = JsonbValueToJsonb(elem.res);
1801 
1802  it = JsonbIteratorInit(&jbkey->root);
1803 
1804  /* switch to the aggregate context for accumulation operations */
1805 
1806  oldcontext = MemoryContextSwitchTo(aggcontext);
1807 
1808  /*
1809  * keys should be scalar, and we should have already checked for that
1810  * above when calling datum_to_jsonb, so we only need to look for these
1811  * things.
1812  */
1813 
1814  while ((type = JsonbIteratorNext(&it, &v, false)) != WJB_DONE)
1815  {
1816  switch (type)
1817  {
1818  case WJB_BEGIN_ARRAY:
1819  if (!v.val.array.rawScalar)
1820  elog(ERROR, "unexpected structure for key");
1821  break;
1822  case WJB_ELEM:
1823  if (v.type == jbvString)
1824  {
1825  /* copy string values in the aggregate context */
1826  char *buf = palloc(v.val.string.len + 1);
1827 
1828  snprintf(buf, v.val.string.len + 1, "%s", v.val.string.val);
1829  v.val.string.val = buf;
1830  }
1831  else
1832  {
1833  ereport(ERROR,
1834  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1835  errmsg("object keys must be strings")));
1836  }
1837  result->res = pushJsonbValue(&result->parseState,
1838  WJB_KEY, &v);
1839  break;
1840  case WJB_END_ARRAY:
1841  break;
1842  default:
1843  elog(ERROR, "unexpected structure for key");
1844  break;
1845  }
1846  }
1847 
1848  it = JsonbIteratorInit(&jbval->root);
1849 
1850  single_scalar = false;
1851 
1852  /*
1853  * values can be anything, including structured and null, so we treat them
1854  * as in json_agg_transfn, except that single scalars are always pushed as
1855  * WJB_VALUE items.
1856  */
1857 
1858  while ((type = JsonbIteratorNext(&it, &v, false)) != WJB_DONE)
1859  {
1860  switch (type)
1861  {
1862  case WJB_BEGIN_ARRAY:
1863  if (v.val.array.rawScalar)
1864  single_scalar = true;
1865  else
1866  result->res = pushJsonbValue(&result->parseState,
1867  type, NULL);
1868  break;
1869  case WJB_END_ARRAY:
1870  if (!single_scalar)
1871  result->res = pushJsonbValue(&result->parseState,
1872  type, NULL);
1873  break;
1874  case WJB_BEGIN_OBJECT:
1875  case WJB_END_OBJECT:
1876  result->res = pushJsonbValue(&result->parseState,
1877  type, NULL);
1878  break;
1879  case WJB_ELEM:
1880  case WJB_KEY:
1881  case WJB_VALUE:
1882  if (v.type == jbvString)
1883  {
1884  /* copy string values in the aggregate context */
1885  char *buf = palloc(v.val.string.len + 1);
1886 
1887  snprintf(buf, v.val.string.len + 1, "%s", v.val.string.val);
1888  v.val.string.val = buf;
1889  }
1890  else if (v.type == jbvNumeric)
1891  {
1892  /* same for numeric */
1893  v.val.numeric =
1895  NumericGetDatum(v.val.numeric)));
1896  }
1897  result->res = pushJsonbValue(&result->parseState,
1898  single_scalar ? WJB_VALUE : type,
1899  &v);
1900  break;
1901  default:
1902  elog(ERROR, "unknown jsonb iterator token type");
1903  }
1904  }
1905 
1906  MemoryContextSwitchTo(oldcontext);
1907 
1908  PG_RETURN_POINTER(state);
1909 }
1910 
1911 Datum
1913 {
1914  JsonbAggState *arg;
1915  JsonbInState result;
1916  Jsonb *out;
1917 
1918  /* cannot be called directly because of internal-type argument */
1919  Assert(AggCheckCallContext(fcinfo, NULL));
1920 
1921  if (PG_ARGISNULL(0))
1922  PG_RETURN_NULL(); /* returns null iff no input values */
1923 
1924  arg = (JsonbAggState *) PG_GETARG_POINTER(0);
1925 
1926  /*
1927  * We need to do a shallow clone of the argument's res field in case the
1928  * final function is called more than once, so we avoid changing the
1929  * aggregate state value. A shallow clone is sufficient as we aren't
1930  * going to change any of the values, just add the final object end
1931  * marker.
1932  */
1933 
1934  result.parseState = clone_parse_state(arg->res->parseState);
1935 
1936  result.res = pushJsonbValue(&result.parseState,
1937  WJB_END_OBJECT, NULL);
1938 
1939  out = JsonbValueToJsonb(result.res);
1940 
1941  PG_RETURN_POINTER(out);
1942 }
#define MAXDATELEN
Definition: datetime.h:203
void EncodeDateOnly(struct pg_tm *tm, int style, char *str)
Definition: datetime.c:3884
json_struct_action array_end
Definition: jsonapi.h:88
#define RECORDARRAYOID
Definition: pg_type.h:682
#define TIMESTAMPTZOID
Definition: pg_type.h:525
static void array_to_jsonb_internal(Datum array, JsonbInState *result)
Definition: jsonb.c:998
signed short int16
Definition: c.h:245
JsonbParseState * parseState
Definition: jsonb.c:33
JsonbValue * res
Definition: jsonb.c:34
#define PG_RETURN_POINTER(x)
Definition: fmgr.h:321
static void jsonb_in_object_end(void *pstate)
Definition: jsonb.c:273
#define DATEOID
Definition: pg_type.h:511
#define DatumGetDateADT(X)
Definition: date.h:52
#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:1087
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2632
Jsonb * JsonbValueToJsonb(JsonbValue *val)
Definition: jsonb_util.c:79
Definition: jsonb.h:215
Datum numeric_uplus(PG_FUNCTION_ARGS)
Definition: numeric.c:1158
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:2433
bool get_fn_expr_arg_stable(FmgrInfo *flinfo, int argnum)
Definition: fmgr.c:1980
TupleDesc lookup_rowtype_tupdesc(Oid type_id, int32 typmod)
Definition: typcache.c:1486
json_struct_action object_end
Definition: jsonapi.h:86
Datum jsonb_build_object(PG_FUNCTION_ARGS)
Definition: jsonb.c:1172
Datum jsonb_object(PG_FUNCTION_ARGS)
Definition: jsonb.c:1332
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:304
#define DatumGetJsonbP(d)
Definition: jsonb.h:68
int64 timestamp
Oid get_element_type(Oid typid)
Definition: lsyscache.c:2484
int64 TimestampTz
Definition: timestamp.h:39
void get_typlenbyvalalign(Oid typid, int16 *typlen, bool *typbyval, char *typalign)
Definition: lsyscache.c:2021
#define PointerGetDatum(X)
Definition: postgres.h:562
#define PG_GETARG_DATUM(n)
Definition: fmgr.h:233
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:84
#define NUMERICOID
Definition: pg_type.h:554
void pq_begintypsend(StringInfo buf)
Definition: pqformat.c:359
#define JSONOID
Definition: pg_type.h:356
char * pstrdup(const char *in)
Definition: mcxt.c:1076
char * val
Definition: jsonb.h:259
static JsonbParseState * clone_parse_state(JsonbParseState *state)
Definition: jsonb.c:1531
#define NumericGetDatum(X)
Definition: numeric.h:51
JsonbInState * res
Definition: jsonb.c:56
#define DatumGetTextPP(X)
Definition: fmgr.h:256
int timestamp2tm(Timestamp dt, int *tzp, struct pg_tm *tm, fsec_t *fsec, const char **tzn, pg_tz *attimezone)
Definition: timestamp.c:1758
Definition: jsonb.h:234
StringInfo makeStringInfo(void)
Definition: stringinfo.c:28
StringInfoData * StringInfo
Definition: stringinfo.h:43
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:75
Datum numeric_out(PG_FUNCTION_ARGS)
Definition: numeric.c:651
json_struct_action object_start
Definition: jsonapi.h:85
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:1118
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:93
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:241
Definition: jsonb.h:231
long date
Definition: pgtypes_date.h:8
void EncodeSpecialTimestamp(Timestamp dt, char *str)
Definition: timestamp.c:1523
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:585
#define PG_RETURN_BYTEA_P(x)
Definition: fmgr.h:330
#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:532
bytea * pq_endtypsend(StringInfo buf)
Definition: pqformat.c:379
#define DatumGetHeapTupleHeader(X)
Definition: fmgr.h:259
int natts
Definition: tupdesc.h:73
CoercionPathType
Definition: parse_coerce.h:24
#define FirstNormalObjectId
Definition: transam.h:94
signed int int32
Definition: c.h:246
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:699
JsonbValue * pushJsonbValue(JsonbParseState **pstate, JsonbIteratorToken seq, JsonbValue *jbval)
Definition: jsonb_util.c:517
#define PG_GETARG_ARRAYTYPE_P(n)
Definition: array.h:244
#define appendStringInfoCharMacro(str, ch)
Definition: stringinfo.h:127
JsonLexContext * makeJsonLexContext(text *json, bool need_escapes)
Definition: json.c:300
#define TIMESTAMP_NOT_FINITE(j)
Definition: timestamp.h:122
void pfree(void *pointer)
Definition: mcxt.c:949
Datum jsonb_send(PG_FUNCTION_ARGS)
Definition: jsonb.c:147
#define TIMESTAMPOID
Definition: pg_type.h:519
Datum jsonb_object_agg_finalfn(PG_FUNCTION_ARGS)
Definition: jsonb.c:1912
#define ERROR
Definition: elog.h:43
Datum jsonb_object_agg_transfn(PG_FUNCTION_ARGS)
Definition: jsonb.c:1716
#define DatumGetCString(X)
Definition: postgres.h:572
Oid get_fn_expr_argtype(FmgrInfo *flinfo, int argnum)
Definition: fmgr.c:1909
Datum jsonb_build_object_noargs(PG_FUNCTION_ARGS)
Definition: jsonb.c:1251
#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:42
void pg_parse_json(JsonLexContext *lex, JsonSemAction *sem)
Definition: json.c:331
#define OidFunctionCall1(functionId, arg1)
Definition: fmgr.h:623
#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:157
uint32 t_len
Definition: htup.h:64
int tm_mday
Definition: pgtime.h:30
static char * buf
Definition: pg_test_fsync.c:67
Datum to_jsonb(PG_FUNCTION_ARGS)
Definition: jsonb.c:1145
int tm_mon
Definition: pgtime.h:31
void check_stack_depth(void)
Definition: postgres.c:3144
#define DatumGetTimestampTz(X)
Definition: timestamp.h:28
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define CStringGetDatum(X)
Definition: postgres.h:584
#define DatumGetBool(X)
Definition: postgres.h:399
void enlargeStringInfo(StringInfo str, int needed)
Definition: stringinfo.c:245
#define JSONBOID
Definition: pg_type.h:638
void EncodeDateTime(struct pg_tm *tm, fsec_t fsec, bool print_tz, int tz, const char *tzn, int style, char *str)
Definition: datetime.c:3999
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:187
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:569
Definition: jsonb.h:23
int32 fsec_t
Definition: timestamp.h:41
bool type_is_rowtype(Oid typid)
Definition: lsyscache.c:2404
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:966
#define ereport(elevel, rest)
Definition: elog.h:122
void j2date(int jd, int *year, int *month, int *day)
Definition: datetime.c:317
JsonbIteratorToken
Definition: jsonb.h:20
struct JsonbAggState JsonbAggState
#define DirectFunctionCall3(func, arg1, arg2, arg3)
Definition: fmgr.h:589
int64 Timestamp
Definition: timestamp.h:38
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:92
#define FLOAT4OID
Definition: pg_type.h:416
#define ANYARRAYOID
Definition: pg_type.h:688
void * palloc0(Size size)
Definition: mcxt.c:877
static void composite_to_jsonb(Datum composite, JsonbInState *result)
Definition: jsonb.c:1046
uintptr_t Datum
Definition: postgres.h:372
Datum jsonb_object_two_arg(PG_FUNCTION_ARGS)
Definition: jsonb.c:1434
#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:1563
#define INT8OID
Definition: pg_type.h:304
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:331
text * cstring_to_text(const char *s)
Definition: varlena.c:149
#define PG_ARGISNULL(n)
Definition: fmgr.h:174
#define DatumGetNumeric(X)
Definition: numeric.h:49
#define Assert(condition)
Definition: c.h:664
JsonbIterator * JsonbIteratorInit(JsonbContainer *container)
Definition: jsonb_util.c:718
json_struct_action array_start
Definition: jsonapi.h:87
Definition: regguts.h:298
Datum jsonb_out(PG_FUNCTION_ARGS)
Definition: jsonb.c:131
#define PG_RETURN_CSTRING(x)
Definition: fmgr.h:322
char * JsonbToCString(StringInfo out, JsonbContainer *in, int estimated_len)
Definition: jsonb.c:428
struct JsonbInState JsonbInState
#define FLOAT8OID
Definition: pg_type.h:419
JsonLexContext * makeJsonLexContextCstringLen(char *json, int len, bool need_escapes)
Definition: json.c:308
int AggCheckCallContext(FunctionCallInfo fcinfo, MemoryContext *aggcontext)
Definition: nodeAgg.c:4031
Datum jsonb_build_array(PG_FUNCTION_ARGS)
Definition: jsonb.c:1267
#define PG_NARGS()
Definition: fmgr.h:168
#define BOOLOID
Definition: pg_type.h:288
#define ARR_NDIM(a)
Definition: array.h:271
#define UNKNOWNOID
Definition: pg_type.h:431
JsonbTypeCategory key_category
Definition: jsonb.c:57
enum jbvType type
Definition: jsonb.h:250
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:3476
Datum jsonb_build_array_noargs(PG_FUNCTION_ARGS)
Definition: jsonb.c:1311
#define USE_XSD_DATES
Definition: miscadmin.h:214
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:1747
void * palloc(Size size)
Definition: mcxt.c:848
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:493
#define CStringGetTextDatum(s)
Definition: builtins.h:91
void * arg
#define PG_GETARG_CSTRING(n)
Definition: fmgr.h:242
Definition: c.h:433
#define PG_FUNCTION_ARGS
Definition: fmgr.h:158
unsigned int pq_getmsgint(StringInfo msg, int b)
Definition: pqformat.c:448
#define POSTGRES_EPOCH_JDATE
Definition: timestamp.h:163
json_ofield_action object_field_start
Definition: jsonapi.h:89
#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:1681
#define ReleaseTupleDesc(tupdesc)
Definition: tupdesc.h:115
Oid getBaseType(Oid typid)
Definition: lsyscache.c:2271
#define ARR_ELEMTYPE(a)
Definition: array.h:273
void * semstate
Definition: jsonapi.h:84
void appendBinaryStringInfo(StringInfo str, const char *data, int datalen)
Definition: stringinfo.c:208
long val
Definition: informix.c:689
#define PG_RETURN_NULL()
Definition: fmgr.h:305
JsonbIteratorToken JsonbIteratorNext(JsonbIterator **it, JsonbValue *val, bool skipNested)
Definition: jsonb_util.c:754
Definition: jsonb.h:25
#define PG_GETARG_JSONB_P(x)
Definition: jsonb.h:70
JsonTokenType
Definition: jsonapi.h:20
#define DatumGetTimestamp(X)
Definition: timestamp.h:27
#define HeapTupleHeaderGetDatumLength(tup)
Definition: htup_details.h:439
#define DatumGetArrayTypeP(X)
Definition: array.h:242