PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
jsonb.c File Reference
#include "postgres.h"
#include "miscadmin.h"
#include "access/htup_details.h"
#include "access/transam.h"
#include "catalog/pg_type.h"
#include "libpq/pqformat.h"
#include "parser/parse_coerce.h"
#include "utils/builtins.h"
#include "utils/date.h"
#include "utils/datetime.h"
#include "utils/lsyscache.h"
#include "utils/json.h"
#include "utils/jsonapi.h"
#include "utils/jsonb.h"
#include "utils/syscache.h"
#include "utils/typcache.h"
Include dependency graph for jsonb.c:

Go to the source code of this file.

Data Structures

struct  JsonbInState
 
struct  JsonbAggState
 

Typedefs

typedef struct JsonbInState JsonbInState
 
typedef struct JsonbAggState JsonbAggState
 

Enumerations

enum  JsonbTypeCategory {
  JSONBTYPE_NULL, JSONBTYPE_BOOL, JSONBTYPE_NUMERIC, JSONBTYPE_DATE,
  JSONBTYPE_TIMESTAMP, JSONBTYPE_TIMESTAMPTZ, JSONBTYPE_JSON, JSONBTYPE_JSONB,
  JSONBTYPE_ARRAY, JSONBTYPE_COMPOSITE, JSONBTYPE_JSONCAST, JSONBTYPE_OTHER
}
 

Functions

static Datum jsonb_from_cstring (char *json, int len)
 
static size_t checkStringLen (size_t len)
 
static void jsonb_in_object_start (void *pstate)
 
static void jsonb_in_object_end (void *pstate)
 
static void jsonb_in_array_start (void *pstate)
 
static void jsonb_in_array_end (void *pstate)
 
static void jsonb_in_object_field_start (void *pstate, char *fname, bool isnull)
 
static void jsonb_put_escaped_value (StringInfo out, JsonbValue *scalarVal)
 
static void jsonb_in_scalar (void *pstate, char *token, JsonTokenType tokentype)
 
static void jsonb_categorize_type (Oid typoid, JsonbTypeCategory *tcategory, Oid *outfuncoid)
 
static void composite_to_jsonb (Datum composite, JsonbInState *result)
 
static void array_dim_to_jsonb (JsonbInState *result, int dim, int ndims, int *dims, Datum *vals, bool *nulls, int *valcount, JsonbTypeCategory tcategory, Oid outfuncoid)
 
static void array_to_jsonb_internal (Datum array, JsonbInState *result)
 
static void datum_to_jsonb (Datum val, bool is_null, JsonbInState *result, JsonbTypeCategory tcategory, Oid outfuncoid, bool key_scalar)
 
static void add_jsonb (Datum val, bool is_null, JsonbInState *result, Oid val_type, bool key_scalar)
 
static JsonbParseStateclone_parse_state (JsonbParseState *state)
 
static char * JsonbToCStringWorker (StringInfo out, JsonbContainer *in, int estimated_len, bool indent)
 
static void add_indent (StringInfo out, bool indent, int level)
 
Datum jsonb_in (PG_FUNCTION_ARGS)
 
Datum jsonb_recv (PG_FUNCTION_ARGS)
 
Datum jsonb_out (PG_FUNCTION_ARGS)
 
Datum jsonb_send (PG_FUNCTION_ARGS)
 
Datum jsonb_typeof (PG_FUNCTION_ARGS)
 
char * JsonbToCString (StringInfo out, JsonbContainer *in, int estimated_len)
 
char * JsonbToCStringIndent (StringInfo out, JsonbContainer *in, int estimated_len)
 
Datum to_jsonb (PG_FUNCTION_ARGS)
 
Datum jsonb_build_object (PG_FUNCTION_ARGS)
 
Datum jsonb_build_object_noargs (PG_FUNCTION_ARGS)
 
Datum jsonb_build_array (PG_FUNCTION_ARGS)
 
Datum jsonb_build_array_noargs (PG_FUNCTION_ARGS)
 
Datum jsonb_object (PG_FUNCTION_ARGS)
 
Datum jsonb_object_two_arg (PG_FUNCTION_ARGS)
 
Datum jsonb_agg_transfn (PG_FUNCTION_ARGS)
 
Datum jsonb_agg_finalfn (PG_FUNCTION_ARGS)
 
Datum jsonb_object_agg_transfn (PG_FUNCTION_ARGS)
 
Datum jsonb_object_agg_finalfn (PG_FUNCTION_ARGS)
 

Typedef Documentation

Enumeration Type Documentation

Enumerator
JSONBTYPE_NULL 
JSONBTYPE_BOOL 
JSONBTYPE_NUMERIC 
JSONBTYPE_DATE 
JSONBTYPE_TIMESTAMP 
JSONBTYPE_TIMESTAMPTZ 
JSONBTYPE_JSON 
JSONBTYPE_JSONB 
JSONBTYPE_ARRAY 
JSONBTYPE_COMPOSITE 
JSONBTYPE_JSONCAST 
JSONBTYPE_OTHER 

Definition at line 38 of file jsonb.c.

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 */
JsonbTypeCategory
Definition: jsonb.c:38

Function Documentation

static void add_indent ( StringInfo  out,
bool  indent,
int  level 
)
static

Definition at line 570 of file jsonb.c.

References appendBinaryStringInfo(), appendStringInfoCharMacro, and i.

Referenced by JsonbToCStringWorker().

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 }
#define appendStringInfoCharMacro(str, ch)
Definition: stringinfo.h:135
int i
void appendBinaryStringInfo(StringInfo str, const char *data, int datalen)
Definition: stringinfo.c:240
static void add_jsonb ( Datum  val,
bool  is_null,
JsonbInState result,
Oid  val_type,
bool  key_scalar 
)
static

Definition at line 1118 of file jsonb.c.

References datum_to_jsonb(), ereport, errcode(), errmsg(), ERROR, InvalidOid, jsonb_categorize_type(), and JSONBTYPE_NULL.

Referenced by jsonb_build_array(), and jsonb_build_object().

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 }
int errcode(int sqlerrcode)
Definition: elog.c:575
unsigned int Oid
Definition: postgres_ext.h:31
static void datum_to_jsonb(Datum val, bool is_null, JsonbInState *result, JsonbTypeCategory tcategory, Oid outfuncoid, bool key_scalar)
Definition: jsonb.c:699
#define ERROR
Definition: elog.h:43
static void jsonb_categorize_type(Oid typoid, JsonbTypeCategory *tcategory, Oid *outfuncoid)
Definition: jsonb.c:591
#define ereport(elevel, rest)
Definition: elog.h:122
JsonbTypeCategory
Definition: jsonb.c:38
#define InvalidOid
Definition: postgres_ext.h:36
int errmsg(const char *fmt,...)
Definition: elog.c:797
long val
Definition: informix.c:689
static void array_dim_to_jsonb ( JsonbInState result,
int  dim,
int  ndims,
int *  dims,
Datum vals,
bool nulls,
int *  valcount,
JsonbTypeCategory  tcategory,
Oid  outfuncoid 
)
static

Definition at line 966 of file jsonb.c.

References Assert, datum_to_jsonb(), i, NULL, JsonbInState::parseState, pushJsonbValue(), JsonbInState::res, WJB_BEGIN_ARRAY, and WJB_END_ARRAY.

Referenced by array_to_jsonb_internal().

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 }
JsonbParseState * parseState
Definition: jsonb.c:33
JsonbValue * res
Definition: jsonb.c:34
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
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 NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
int i
static void array_to_jsonb_internal ( Datum  array,
JsonbInState result 
)
static

Definition at line 998 of file jsonb.c.

References ARR_DIMS, ARR_ELEMTYPE, ARR_NDIM, array_dim_to_jsonb(), ArrayGetNItems(), DatumGetArrayTypeP, deconstruct_array(), get_typlenbyvalalign(), jsonb_categorize_type(), NULL, JsonbInState::parseState, pfree(), pushJsonbValue(), JsonbInState::res, WJB_BEGIN_ARRAY, and WJB_END_ARRAY.

Referenced by datum_to_jsonb().

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 }
signed short int16
Definition: c.h:255
JsonbParseState * parseState
Definition: jsonb.c:33
JsonbValue * res
Definition: jsonb.c:34
void get_typlenbyvalalign(Oid typid, int16 *typlen, bool *typbyval, char *typalign)
Definition: lsyscache.c:1989
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:75
unsigned int Oid
Definition: postgres_ext.h:31
JsonbValue * pushJsonbValue(JsonbParseState **pstate, JsonbIteratorToken seq, JsonbValue *jbval)
Definition: jsonb_util.c:517
void pfree(void *pointer)
Definition: mcxt.c:950
#define ARR_DIMS(a)
Definition: array.h:275
static void jsonb_categorize_type(Oid typoid, JsonbTypeCategory *tcategory, Oid *outfuncoid)
Definition: jsonb.c:591
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
uintptr_t Datum
Definition: postgres.h:372
JsonbTypeCategory
Definition: jsonb.c:38
#define NULL
Definition: c.h:229
#define ARR_NDIM(a)
Definition: array.h:271
void deconstruct_array(ArrayType *array, Oid elmtype, int elmlen, bool elmbyval, char elmalign, Datum **elemsp, bool **nullsp, int *nelemsp)
Definition: arrayfuncs.c:3475
#define ARR_ELEMTYPE(a)
Definition: array.h:273
#define DatumGetArrayTypeP(X)
Definition: array.h:242
static size_t checkStringLen ( size_t  len)
static

Definition at line 252 of file jsonb.c.

References ereport, errcode(), errdetail(), errmsg(), ERROR, and JENTRY_OFFLENMASK.

Referenced by datum_to_jsonb(), jsonb_in_object_field_start(), and jsonb_in_scalar().

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 }
int errcode(int sqlerrcode)
Definition: elog.c:575
#define JENTRY_OFFLENMASK
Definition: jsonb.h:141
#define ERROR
Definition: elog.h:43
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define ereport(elevel, rest)
Definition: elog.h:122
int errmsg(const char *fmt,...)
Definition: elog.c:797
static JsonbParseState * clone_parse_state ( JsonbParseState state)
static

Definition at line 1531 of file jsonb.c.

References JsonbParseState::contVal, JsonbParseState::next, NULL, palloc(), result, and JsonbParseState::size.

Referenced by jsonb_agg_finalfn(), and jsonb_object_agg_finalfn().

1532 {
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 }
return result
Definition: formatting.c:1618
struct JsonbParseState * next
Definition: jsonb.h:308
JsonbValue contVal
Definition: jsonb.h:306
#define NULL
Definition: c.h:229
void * palloc(Size size)
Definition: mcxt.c:849
static void composite_to_jsonb ( Datum  composite,
JsonbInState result 
)
static

Definition at line 1046 of file jsonb.c.

References tupleDesc::attrs, datum_to_jsonb(), DatumGetHeapTupleHeader, heap_getattr, HeapTupleHeaderGetDatumLength, HeapTupleHeaderGetTypeId, HeapTupleHeaderGetTypMod, i, InvalidOid, jbvString, jsonb_categorize_type(), JSONBTYPE_NULL, lookup_rowtype_tupdesc(), NameStr, tupleDesc::natts, NULL, JsonbInState::parseState, pushJsonbValue(), ReleaseTupleDesc, JsonbInState::res, HeapTupleData::t_data, HeapTupleData::t_len, JsonbValue::type, JsonbValue::val, val, WJB_BEGIN_OBJECT, WJB_END_OBJECT, and WJB_KEY.

Referenced by datum_to_jsonb().

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 
1079  if (tupdesc->attrs[i]->attisdropped)
1080  continue;
1081 
1082  attname = NameStr(tupdesc->attrs[i]->attname);
1083 
1084  v.type = jbvString;
1085  /* don't need checkStringLen here - can't exceed maximum name length */
1086  v.val.string.len = strlen(attname);
1087  v.val.string.val = attname;
1088 
1089  result->res = pushJsonbValue(&result->parseState, WJB_KEY, &v);
1090 
1091  val = heap_getattr(tuple, i + 1, tupdesc, &isnull);
1092 
1093  if (isnull)
1094  {
1095  tcategory = JSONBTYPE_NULL;
1096  outfuncoid = InvalidOid;
1097  }
1098  else
1099  jsonb_categorize_type(tupdesc->attrs[i]->atttypid,
1100  &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 }
JsonbParseState * parseState
Definition: jsonb.c:33
JsonbValue * res
Definition: jsonb.c:34
TupleDesc lookup_rowtype_tupdesc(Oid type_id, int32 typmod)
Definition: typcache.c:1245
char * val
Definition: jsonb.h:259
Form_pg_attribute * attrs
Definition: tupdesc.h:74
unsigned int Oid
Definition: postgres_ext.h:31
#define DatumGetHeapTupleHeader(X)
Definition: fmgr.h:251
int natts
Definition: tupdesc.h:73
signed int int32
Definition: c.h:256
HeapTupleHeader t_data
Definition: htup.h:67
#define HeapTupleHeaderGetTypMod(tup)
Definition: htup_details.h:455
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
uint32 t_len
Definition: htup.h:64
static void jsonb_categorize_type(Oid typoid, JsonbTypeCategory *tcategory, Oid *outfuncoid)
Definition: jsonb.c:591
Definition: jsonb.h:23
#define heap_getattr(tup, attnum, tupleDesc, isnull)
Definition: htup_details.h:769
uintptr_t Datum
Definition: postgres.h:372
#define HeapTupleHeaderGetTypeId(tup)
Definition: htup_details.h:445
JsonbTypeCategory
Definition: jsonb.c:38
#define InvalidOid
Definition: postgres_ext.h:36
#define NULL
Definition: c.h:229
enum jbvType type
Definition: jsonb.h:250
int i
#define NameStr(name)
Definition: c.h:499
#define ReleaseTupleDesc(tupdesc)
Definition: tupdesc.h:107
long val
Definition: informix.c:689
#define HeapTupleHeaderGetDatumLength(tup)
Definition: htup_details.h:439
static void datum_to_jsonb ( Datum  val,
bool  is_null,
JsonbInState result,
JsonbTypeCategory  tcategory,
Oid  outfuncoid,
bool  key_scalar 
)
static

Definition at line 699 of file jsonb.c.

References JsonSemAction::array_end, JsonSemAction::array_start, array_to_jsonb_internal(), Assert, buf, check_stack_depth(), checkStringLen(), composite_to_jsonb(), JsonbParseState::contVal, CStringGetDatum, DATE_NOT_FINITE, DatumGetBool, DatumGetDateADT, DatumGetJsonb, DatumGetNumeric, DatumGetTextPP, DatumGetTimestamp, DatumGetTimestampTz, DirectFunctionCall3, elog, EncodeDateOnly(), EncodeDateTime(), EncodeSpecialDate(), EncodeSpecialTimestamp(), ereport, errcode(), errmsg(), ERROR, j2date(), JB_ROOT_IS_SCALAR, jbvArray, jbvBool, jbvNull, jbvNumeric, jbvObject, jbvString, jsonb_in_array_end(), jsonb_in_array_start(), jsonb_in_object_end(), jsonb_in_object_field_start(), jsonb_in_object_start(), jsonb_in_scalar(), JsonbIteratorInit(), JsonbIteratorNext(), JSONBTYPE_ARRAY, JSONBTYPE_BOOL, JSONBTYPE_COMPOSITE, JSONBTYPE_DATE, JSONBTYPE_JSON, JSONBTYPE_JSONB, JSONBTYPE_JSONCAST, JSONBTYPE_NUMERIC, JSONBTYPE_TIMESTAMP, JSONBTYPE_TIMESTAMPTZ, makeJsonLexContext(), MAXDATELEN, NULL, numeric_in(), JsonSemAction::object_end, JsonSemAction::object_field_start, JsonSemAction::object_start, OidFunctionCall1, OidOutputFunctionCall(), JsonbInState::parseState, pfree(), pg_parse_json(), POSTGRES_EPOCH_JDATE, pstrdup(), pushJsonbValue(), JsonbInState::res, Jsonb::root, JsonSemAction::scalar, JsonSemAction::semstate, timestamp2tm(), TIMESTAMP_NOT_FINITE, pg_tm::tm_mday, pg_tm::tm_mon, pg_tm::tm_year, JsonbValue::type, USE_XSD_DATES, JsonbValue::val, WJB_BEGIN_ARRAY, WJB_BEGIN_OBJECT, WJB_DONE, WJB_ELEM, WJB_END_ARRAY, WJB_END_OBJECT, WJB_KEY, and WJB_VALUE.

Referenced by add_jsonb(), array_dim_to_jsonb(), composite_to_jsonb(), jsonb_agg_transfn(), jsonb_object_agg_transfn(), and to_jsonb().

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));
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 = DatumGetJsonb(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 }
#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:87
static void array_to_jsonb_internal(Datum array, JsonbInState *result)
Definition: jsonb.c:998
JsonbParseState * parseState
Definition: jsonb.c:33
JsonbValue * res
Definition: jsonb.c:34
static void jsonb_in_object_end(void *pstate)
Definition: jsonb.c:273
#define DatumGetDateADT(X)
Definition: date.h:52
Definition: jsonb.h:215
json_struct_action object_end
Definition: jsonapi.h:85
int32 DateADT
Definition: date.h:22
static void jsonb_in_array_start(void *pstate)
Definition: jsonb.c:281
int64 timestamp
int64 TimestampTz
Definition: timestamp.h:39
char * pstrdup(const char *in)
Definition: mcxt.c:1077
char * val
Definition: jsonb.h:259
#define DatumGetTextPP(X)
Definition: fmgr.h:248
int timestamp2tm(Timestamp dt, int *tzp, struct pg_tm *tm, fsec_t *fsec, const char **tzn, pg_tz *attimezone)
Definition: timestamp.c:1757
Definition: jsonb.h:234
json_struct_action object_start
Definition: jsonapi.h:84
Definition: jsonb.h:22
int errcode(int sqlerrcode)
Definition: elog.c:575
json_scalar_action scalar
Definition: jsonapi.h:92
static void jsonb_in_scalar(void *pstate, char *token, JsonTokenType tokentype)
Definition: jsonb.c:341
Definition: jsonb.h:231
long date
Definition: pgtypes_date.h:8
void EncodeSpecialTimestamp(Timestamp dt, char *str)
Definition: timestamp.c:1522
#define JB_ROOT_IS_SCALAR(jbp_)
Definition: jsonb.h:223
Definition: pgtime.h:25
static void jsonb_in_array_end(void *pstate)
Definition: jsonb.c:289
static struct pg_tm tm
Definition: localtime.c:103
JsonbValue * pushJsonbValue(JsonbParseState **pstate, JsonbIteratorToken seq, JsonbValue *jbval)
Definition: jsonb_util.c:517
#define DatumGetJsonb(d)
Definition: jsonb.h:68
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:950
#define ERROR
Definition: elog.h:43
#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:614
static size_t checkStringLen(size_t len)
Definition: jsonb.c:252
int tm_mday
Definition: pgtime.h:30
static char * buf
Definition: pg_test_fsync.c:65
int tm_mon
Definition: pgtime.h:31
void check_stack_depth(void)
Definition: postgres.c:3098
#define DatumGetTimestampTz(X)
Definition: timestamp.h:28
#define CStringGetDatum(X)
Definition: postgres.h:584
#define DatumGetBool(X)
Definition: postgres.h:399
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
void EncodeSpecialDate(DateADT dt, char *str)
Definition: date.c:299
Datum numeric_in(PG_FUNCTION_ARGS)
Definition: numeric.c:559
Definition: jsonb.h:23
int32 fsec_t
Definition: timestamp.h:41
#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
#define DirectFunctionCall3(func, arg1, arg2, arg3)
Definition: fmgr.h:580
int64 Timestamp
Definition: timestamp.h:38
JsonbContainer root
Definition: jsonb.h:218
static void composite_to_jsonb(Datum composite, JsonbInState *result)
Definition: jsonb.c:1046
JsonbValue contVal
Definition: jsonb.h:306
#define DatumGetNumeric(X)
Definition: numeric.h:49
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
JsonbIterator * JsonbIteratorInit(JsonbContainer *container)
Definition: jsonb_util.c:718
json_struct_action array_start
Definition: jsonapi.h:86
enum jbvType type
Definition: jsonb.h:250
static void jsonb_in_object_start(void *pstate)
Definition: jsonb.c:265
#define USE_XSD_DATES
Definition: miscadmin.h:213
int tm_year
Definition: pgtime.h:32
char * OidOutputFunctionCall(Oid functionId, Datum val)
Definition: fmgr.c:2056
int errmsg(const char *fmt,...)
Definition: elog.c:797
Definition: c.h:439
#define POSTGRES_EPOCH_JDATE
Definition: timestamp.h:163
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
void * semstate
Definition: jsonapi.h:83
long val
Definition: informix.c:689
JsonbIteratorToken JsonbIteratorNext(JsonbIterator **it, JsonbValue *val, bool skipNested)
Definition: jsonb_util.c:754
Definition: jsonb.h:25
#define DatumGetTimestamp(X)
Definition: timestamp.h:27
Datum jsonb_agg_finalfn ( PG_FUNCTION_ARGS  )

Definition at line 1681 of file jsonb.c.

References AggCheckCallContext(), arg, Assert, clone_parse_state(), JsonbValueToJsonb(), NULL, JsonbInState::parseState, PG_ARGISNULL, PG_GETARG_POINTER, PG_RETURN_NULL, PG_RETURN_POINTER, pushJsonbValue(), JsonbInState::res, JsonbAggState::res, result, and WJB_END_ARRAY.

1682 {
1683  JsonbAggState *arg;
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 }
JsonbParseState * parseState
Definition: jsonb.c:33
JsonbValue * res
Definition: jsonb.c:34
#define PG_RETURN_POINTER(x)
Definition: fmgr.h:313
Jsonb * JsonbValueToJsonb(JsonbValue *val)
Definition: jsonb_util.c:79
Definition: jsonb.h:215
static JsonbParseState * clone_parse_state(JsonbParseState *state)
Definition: jsonb.c:1531
JsonbInState * res
Definition: jsonb.c:56
return result
Definition: formatting.c:1618
#define PG_GETARG_POINTER(n)
Definition: fmgr.h:233
JsonbValue * pushJsonbValue(JsonbParseState **pstate, JsonbIteratorToken seq, JsonbValue *jbval)
Definition: jsonb_util.c:517
#define PG_ARGISNULL(n)
Definition: fmgr.h:166
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
int AggCheckCallContext(FunctionCallInfo fcinfo, MemoryContext *aggcontext)
Definition: nodeAgg.c:3660
void * arg
#define PG_RETURN_NULL()
Definition: fmgr.h:297
Datum jsonb_agg_transfn ( PG_FUNCTION_ARGS  )

Definition at line 1563 of file jsonb.c.

References AggCheckCallContext(), buf, datum_to_jsonb(), DatumGetNumeric, DirectFunctionCall1, elog, ereport, errcode(), errmsg(), ERROR, get_fn_expr_argtype(), InvalidOid, jbvNumeric, jbvString, jsonb_categorize_type(), JsonbIteratorInit(), JsonbIteratorNext(), JsonbValueToJsonb(), MemoryContextSwitchTo(), NULL, numeric_uplus(), NumericGetDatum, palloc(), palloc0(), JsonbInState::parseState, PG_ARGISNULL, PG_GETARG_DATUM, PG_GETARG_POINTER, PG_RETURN_POINTER, pushJsonbValue(), JsonbInState::res, JsonbAggState::res, result, Jsonb::root, snprintf(), JsonbValue::type, JsonbValue::val, val, JsonbAggState::val_category, JsonbAggState::val_output_func, WJB_BEGIN_ARRAY, WJB_BEGIN_OBJECT, WJB_DONE, WJB_ELEM, WJB_END_ARRAY, WJB_END_OBJECT, WJB_KEY, and WJB_VALUE.

1564 {
1565  MemoryContext oldcontext,
1566  aggcontext;
1568  JsonbInState elem;
1569  Datum val;
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,
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 }
JsonbParseState * parseState
Definition: jsonb.c:33
JsonbValue * res
Definition: jsonb.c:34
#define PG_RETURN_POINTER(x)
Definition: fmgr.h:313
Jsonb * JsonbValueToJsonb(JsonbValue *val)
Definition: jsonb_util.c:79
Definition: jsonb.h:215
Datum numeric_uplus(PG_FUNCTION_ARGS)
Definition: numeric.c:1148
#define PG_GETARG_DATUM(n)
Definition: fmgr.h:225
char * val
Definition: jsonb.h:259
#define NumericGetDatum(X)
Definition: numeric.h:51
JsonbInState * res
Definition: jsonb.c:56
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Definition: jsonb.h:22
int errcode(int sqlerrcode)
Definition: elog.c:575
return result
Definition: formatting.c:1618
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
#define PG_GETARG_POINTER(n)
Definition: fmgr.h:233
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:576
unsigned int Oid
Definition: postgres_ext.h:31
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 ERROR
Definition: elog.h:43
Oid get_fn_expr_argtype(FmgrInfo *flinfo, int argnum)
Definition: fmgr.c:2270
static char * buf
Definition: pg_test_fsync.c:65
static void jsonb_categorize_type(Oid typoid, JsonbTypeCategory *tcategory, Oid *outfuncoid)
Definition: jsonb.c:591
Definition: jsonb.h:23
#define ereport(elevel, rest)
Definition: elog.h:122
JsonbIteratorToken
Definition: jsonb.h:20
JsonbContainer root
Definition: jsonb.h:218
void * palloc0(Size size)
Definition: mcxt.c:878
uintptr_t Datum
Definition: postgres.h:372
#define InvalidOid
Definition: postgres_ext.h:36
#define PG_ARGISNULL(n)
Definition: fmgr.h:166
#define DatumGetNumeric(X)
Definition: numeric.h:49
#define NULL
Definition: c.h:229
JsonbIterator * JsonbIteratorInit(JsonbContainer *container)
Definition: jsonb_util.c:718
Definition: regguts.h:298
int AggCheckCallContext(FunctionCallInfo fcinfo, MemoryContext *aggcontext)
Definition: nodeAgg.c:3660
enum jbvType type
Definition: jsonb.h:250
void * palloc(Size size)
Definition: mcxt.c:849
int errmsg(const char *fmt,...)
Definition: elog.c:797
Oid val_output_func
Definition: jsonb.c:60
#define elog
Definition: elog.h:219
long val
Definition: informix.c:689
JsonbIteratorToken JsonbIteratorNext(JsonbIterator **it, JsonbValue *val, bool skipNested)
Definition: jsonb_util.c:754
Definition: jsonb.h:25
Datum jsonb_build_array ( PG_FUNCTION_ARGS  )

Definition at line 1267 of file jsonb.c.

References add_jsonb(), arg, CStringGetTextDatum, ereport, errcode(), errmsg(), ERROR, get_fn_expr_arg_stable(), get_fn_expr_argtype(), i, InvalidOid, JsonbValueToJsonb(), NULL, JsonbInState::parseState, PG_ARGISNULL, PG_GETARG_DATUM, PG_GETARG_POINTER, PG_NARGS, PG_RETURN_POINTER, pushJsonbValue(), JsonbInState::res, result, TEXTOID, UNKNOWNOID, WJB_BEGIN_ARRAY, and WJB_END_ARRAY.

1268 {
1269  int nargs = PG_NARGS();
1270  int i;
1271  Datum arg;
1272  Oid val_type;
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("argument %d: could not determine data type", 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 }
JsonbParseState * parseState
Definition: jsonb.c:33
JsonbValue * res
Definition: jsonb.c:34
#define PG_RETURN_POINTER(x)
Definition: fmgr.h:313
Jsonb * JsonbValueToJsonb(JsonbValue *val)
Definition: jsonb_util.c:79
bool get_fn_expr_arg_stable(FmgrInfo *flinfo, int argnum)
Definition: fmgr.c:2341
#define TEXTOID
Definition: pg_type.h:324
#define PG_GETARG_DATUM(n)
Definition: fmgr.h:225
static void add_jsonb(Datum val, bool is_null, JsonbInState *result, Oid val_type, bool key_scalar)
Definition: jsonb.c:1118
int errcode(int sqlerrcode)
Definition: elog.c:575
return result
Definition: formatting.c:1618
#define PG_GETARG_POINTER(n)
Definition: fmgr.h:233
unsigned int Oid
Definition: postgres_ext.h:31
JsonbValue * pushJsonbValue(JsonbParseState **pstate, JsonbIteratorToken seq, JsonbValue *jbval)
Definition: jsonb_util.c:517
#define ERROR
Definition: elog.h:43
Oid get_fn_expr_argtype(FmgrInfo *flinfo, int argnum)
Definition: fmgr.c:2270
#define ereport(elevel, rest)
Definition: elog.h:122
uintptr_t Datum
Definition: postgres.h:372
#define InvalidOid
Definition: postgres_ext.h:36
#define PG_ARGISNULL(n)
Definition: fmgr.h:166
#define NULL
Definition: c.h:229
#define PG_NARGS()
Definition: fmgr.h:160
#define UNKNOWNOID
Definition: pg_type.h:423
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
#define CStringGetTextDatum(s)
Definition: builtins.h:91
void * arg
Datum jsonb_build_array_noargs ( PG_FUNCTION_ARGS  )

Definition at line 1311 of file jsonb.c.

References JsonbValueToJsonb(), NULL, JsonbInState::parseState, PG_RETURN_POINTER, pushJsonbValue(), JsonbInState::res, result, WJB_BEGIN_ARRAY, and WJB_END_ARRAY.

1312 {
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 }
JsonbParseState * parseState
Definition: jsonb.c:33
JsonbValue * res
Definition: jsonb.c:34
#define PG_RETURN_POINTER(x)
Definition: fmgr.h:313
Jsonb * JsonbValueToJsonb(JsonbValue *val)
Definition: jsonb_util.c:79
return result
Definition: formatting.c:1618
JsonbValue * pushJsonbValue(JsonbParseState **pstate, JsonbIteratorToken seq, JsonbValue *jbval)
Definition: jsonb_util.c:517
#define NULL
Definition: c.h:229
Datum jsonb_build_object ( PG_FUNCTION_ARGS  )

Definition at line 1172 of file jsonb.c.

References add_jsonb(), arg, CStringGetTextDatum, ereport, errcode(), errmsg(), ERROR, get_fn_expr_arg_stable(), get_fn_expr_argtype(), i, InvalidOid, JsonbValueToJsonb(), NULL, JsonbInState::parseState, PG_ARGISNULL, PG_GETARG_DATUM, PG_GETARG_POINTER, PG_NARGS, PG_RETURN_POINTER, pushJsonbValue(), JsonbInState::res, result, TEXTOID, UNKNOWNOID, WJB_BEGIN_OBJECT, and WJB_END_OBJECT.

1173 {
1174  int nargs = PG_NARGS();
1175  int i;
1176  Datum arg;
1177  Oid val_type;
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("argument %d: could not determine data type", 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("argument %d: could not determine data type", 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 }
JsonbParseState * parseState
Definition: jsonb.c:33
JsonbValue * res
Definition: jsonb.c:34
#define PG_RETURN_POINTER(x)
Definition: fmgr.h:313
Jsonb * JsonbValueToJsonb(JsonbValue *val)
Definition: jsonb_util.c:79
bool get_fn_expr_arg_stable(FmgrInfo *flinfo, int argnum)
Definition: fmgr.c:2341
#define TEXTOID
Definition: pg_type.h:324
#define PG_GETARG_DATUM(n)
Definition: fmgr.h:225
static void add_jsonb(Datum val, bool is_null, JsonbInState *result, Oid val_type, bool key_scalar)
Definition: jsonb.c:1118
int errcode(int sqlerrcode)
Definition: elog.c:575
return result
Definition: formatting.c:1618
#define PG_GETARG_POINTER(n)
Definition: fmgr.h:233
unsigned int Oid
Definition: postgres_ext.h:31
JsonbValue * pushJsonbValue(JsonbParseState **pstate, JsonbIteratorToken seq, JsonbValue *jbval)
Definition: jsonb_util.c:517
#define ERROR
Definition: elog.h:43
Oid get_fn_expr_argtype(FmgrInfo *flinfo, int argnum)
Definition: fmgr.c:2270
#define ereport(elevel, rest)
Definition: elog.h:122
uintptr_t Datum
Definition: postgres.h:372
#define InvalidOid
Definition: postgres_ext.h:36
#define PG_ARGISNULL(n)
Definition: fmgr.h:166
#define NULL
Definition: c.h:229
#define PG_NARGS()
Definition: fmgr.h:160
#define UNKNOWNOID
Definition: pg_type.h:423
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
#define CStringGetTextDatum(s)
Definition: builtins.h:91
void * arg
Datum jsonb_build_object_noargs ( PG_FUNCTION_ARGS  )

Definition at line 1251 of file jsonb.c.

References JsonbValueToJsonb(), NULL, JsonbInState::parseState, PG_RETURN_POINTER, pushJsonbValue(), JsonbInState::res, result, WJB_BEGIN_OBJECT, and WJB_END_OBJECT.

1252 {
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 }
JsonbParseState * parseState
Definition: jsonb.c:33
JsonbValue * res
Definition: jsonb.c:34
#define PG_RETURN_POINTER(x)
Definition: fmgr.h:313
Jsonb * JsonbValueToJsonb(JsonbValue *val)
Definition: jsonb_util.c:79
return result
Definition: formatting.c:1618
JsonbValue * pushJsonbValue(JsonbParseState **pstate, JsonbIteratorToken seq, JsonbValue *jbval)
Definition: jsonb_util.c:517
#define NULL
Definition: c.h:229
static void jsonb_categorize_type ( Oid  typoid,
JsonbTypeCategory tcategory,
Oid outfuncoid 
)
static

Definition at line 591 of file jsonb.c.

References ANYARRAYOID, BOOLOID, COERCION_EXPLICIT, COERCION_PATH_FUNC, DATEOID, find_coercion_pathway(), FirstNormalObjectId, FLOAT4OID, FLOAT8OID, get_element_type(), getBaseType(), getTypeOutputInfo(), INT2OID, INT4OID, INT8OID, InvalidOid, JSONBOID, JSONBTYPE_ARRAY, JSONBTYPE_BOOL, JSONBTYPE_COMPOSITE, JSONBTYPE_DATE, JSONBTYPE_JSON, JSONBTYPE_JSONB, JSONBTYPE_JSONCAST, JSONBTYPE_NUMERIC, JSONBTYPE_OTHER, JSONBTYPE_TIMESTAMP, JSONBTYPE_TIMESTAMPTZ, JSONOID, NUMERICOID, OidIsValid, RECORDARRAYOID, TIMESTAMPOID, TIMESTAMPTZOID, and type_is_rowtype().

Referenced by add_jsonb(), array_to_jsonb_internal(), composite_to_jsonb(), jsonb_agg_transfn(), jsonb_object_agg_transfn(), and to_jsonb().

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 }
#define RECORDARRAYOID
Definition: pg_type.h:674
#define TIMESTAMPTZOID
Definition: pg_type.h:517
#define DATEOID
Definition: pg_type.h:503
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2600
Oid get_element_type(Oid typid)
Definition: lsyscache.c:2452
#define NUMERICOID
Definition: pg_type.h:546
#define JSONOID
Definition: pg_type.h:356
#define INT4OID
Definition: pg_type.h:316
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:538
CoercionPathType
Definition: parse_coerce.h:24
#define FirstNormalObjectId
Definition: transam.h:94
#define TIMESTAMPOID
Definition: pg_type.h:511
#define INT2OID
Definition: pg_type.h:308
#define JSONBOID
Definition: pg_type.h:630
bool type_is_rowtype(Oid typid)
Definition: lsyscache.c:2372
#define FLOAT4OID
Definition: pg_type.h:408
#define ANYARRAYOID
Definition: pg_type.h:680
#define InvalidOid
Definition: postgres_ext.h:36
#define INT8OID
Definition: pg_type.h:304
#define FLOAT8OID
Definition: pg_type.h:411
#define BOOLOID
Definition: pg_type.h:288
CoercionPathType find_coercion_pathway(Oid targetTypeId, Oid sourceTypeId, CoercionContext ccontext, Oid *funcid)
Oid getBaseType(Oid typid)
Definition: lsyscache.c:2239
static Datum jsonb_from_cstring ( char *  json,
int  len 
)
inlinestatic

Definition at line 226 of file jsonb.c.

References JsonSemAction::array_end, JsonSemAction::array_start, jsonb_in_array_end(), jsonb_in_array_start(), jsonb_in_object_end(), jsonb_in_object_field_start(), jsonb_in_object_start(), jsonb_in_scalar(), JsonbValueToJsonb(), makeJsonLexContextCstringLen(), JsonSemAction::object_end, JsonSemAction::object_field_start, JsonSemAction::object_start, pg_parse_json(), PG_RETURN_POINTER, JsonbInState::res, JsonSemAction::scalar, and JsonSemAction::semstate.

Referenced by jsonb_in(), and jsonb_recv().

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 }
json_struct_action array_end
Definition: jsonapi.h:87
JsonbValue * res
Definition: jsonb.c:34
#define PG_RETURN_POINTER(x)
Definition: fmgr.h:313
static void jsonb_in_object_end(void *pstate)
Definition: jsonb.c:273
Jsonb * JsonbValueToJsonb(JsonbValue *val)
Definition: jsonb_util.c:79
json_struct_action object_end
Definition: jsonapi.h:85
static void jsonb_in_array_start(void *pstate)
Definition: jsonb.c:281
json_struct_action object_start
Definition: jsonapi.h:84
json_scalar_action scalar
Definition: jsonapi.h:92
static void jsonb_in_scalar(void *pstate, char *token, JsonTokenType tokentype)
Definition: jsonb.c:341
static void jsonb_in_array_end(void *pstate)
Definition: jsonb.c:289
void pg_parse_json(JsonLexContext *lex, JsonSemAction *sem)
Definition: json.c:331
json_struct_action array_start
Definition: jsonapi.h:86
Definition: regguts.h:298
JsonLexContext * makeJsonLexContextCstringLen(char *json, int len, bool need_escapes)
Definition: json.c:308
static void jsonb_in_object_start(void *pstate)
Definition: jsonb.c:265
json_ofield_action object_field_start
Definition: jsonapi.h:88
static void jsonb_in_object_field_start(void *pstate, char *fname, bool isnull)
Definition: jsonb.c:297
void * semstate
Definition: jsonapi.h:83
Datum jsonb_in ( PG_FUNCTION_ARGS  )

Definition at line 96 of file jsonb.c.

References jsonb_from_cstring(), and PG_GETARG_CSTRING.

97 {
98  char *json = PG_GETARG_CSTRING(0);
99 
100  return jsonb_from_cstring(json, strlen(json));
101 }
static Datum jsonb_from_cstring(char *json, int len)
Definition: jsonb.c:226
#define PG_GETARG_CSTRING(n)
Definition: fmgr.h:234
static void jsonb_in_array_end ( void *  pstate)
static

Definition at line 289 of file jsonb.c.

References NULL, JsonbInState::parseState, pushJsonbValue(), JsonbInState::res, and WJB_END_ARRAY.

Referenced by datum_to_jsonb(), and jsonb_from_cstring().

290 {
291  JsonbInState *_state = (JsonbInState *) pstate;
292 
293  _state->res = pushJsonbValue(&_state->parseState, WJB_END_ARRAY, NULL);
294 }
JsonbParseState * parseState
Definition: jsonb.c:33
JsonbValue * res
Definition: jsonb.c:34
JsonbValue * pushJsonbValue(JsonbParseState **pstate, JsonbIteratorToken seq, JsonbValue *jbval)
Definition: jsonb_util.c:517
#define NULL
Definition: c.h:229
static void jsonb_in_array_start ( void *  pstate)
static

Definition at line 281 of file jsonb.c.

References NULL, JsonbInState::parseState, pushJsonbValue(), JsonbInState::res, and WJB_BEGIN_ARRAY.

Referenced by datum_to_jsonb(), and jsonb_from_cstring().

282 {
283  JsonbInState *_state = (JsonbInState *) pstate;
284 
285  _state->res = pushJsonbValue(&_state->parseState, WJB_BEGIN_ARRAY, NULL);
286 }
JsonbParseState * parseState
Definition: jsonb.c:33
JsonbValue * res
Definition: jsonb.c:34
JsonbValue * pushJsonbValue(JsonbParseState **pstate, JsonbIteratorToken seq, JsonbValue *jbval)
Definition: jsonb_util.c:517
#define NULL
Definition: c.h:229
static void jsonb_in_object_end ( void *  pstate)
static

Definition at line 273 of file jsonb.c.

References NULL, JsonbInState::parseState, pushJsonbValue(), JsonbInState::res, and WJB_END_OBJECT.

Referenced by datum_to_jsonb(), and jsonb_from_cstring().

274 {
275  JsonbInState *_state = (JsonbInState *) pstate;
276 
277  _state->res = pushJsonbValue(&_state->parseState, WJB_END_OBJECT, NULL);
278 }
JsonbParseState * parseState
Definition: jsonb.c:33
JsonbValue * res
Definition: jsonb.c:34
JsonbValue * pushJsonbValue(JsonbParseState **pstate, JsonbIteratorToken seq, JsonbValue *jbval)
Definition: jsonb_util.c:517
#define NULL
Definition: c.h:229
static void jsonb_in_object_field_start ( void *  pstate,
char *  fname,
bool  isnull 
)
static

Definition at line 297 of file jsonb.c.

References Assert, checkStringLen(), jbvString, NULL, JsonbInState::parseState, pushJsonbValue(), JsonbInState::res, JsonbValue::type, JsonbValue::val, and WJB_KEY.

Referenced by datum_to_jsonb(), and jsonb_from_cstring().

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 }
JsonbParseState * parseState
Definition: jsonb.c:33
JsonbValue * res
Definition: jsonb.c:34
char * val
Definition: jsonb.h:259
JsonbValue * pushJsonbValue(JsonbParseState **pstate, JsonbIteratorToken seq, JsonbValue *jbval)
Definition: jsonb_util.c:517
static size_t checkStringLen(size_t len)
Definition: jsonb.c:252
Definition: jsonb.h:23
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
enum jbvType type
Definition: jsonb.h:250
static void jsonb_in_object_start ( void *  pstate)
static

Definition at line 265 of file jsonb.c.

References NULL, JsonbInState::parseState, pushJsonbValue(), JsonbInState::res, and WJB_BEGIN_OBJECT.

Referenced by datum_to_jsonb(), and jsonb_from_cstring().

266 {
267  JsonbInState *_state = (JsonbInState *) pstate;
268 
269  _state->res = pushJsonbValue(&_state->parseState, WJB_BEGIN_OBJECT, NULL);
270 }
JsonbParseState * parseState
Definition: jsonb.c:33
JsonbValue * res
Definition: jsonb.c:34
JsonbValue * pushJsonbValue(JsonbParseState **pstate, JsonbIteratorToken seq, JsonbValue *jbval)
Definition: jsonb_util.c:517
#define NULL
Definition: c.h:229
static void jsonb_in_scalar ( void *  pstate,
char *  token,
JsonTokenType  tokentype 
)
static

Definition at line 341 of file jsonb.c.

References Assert, checkStringLen(), JsonbParseState::contVal, CStringGetDatum, DatumGetNumeric, DirectFunctionCall3, elog, ERROR, jbvArray, jbvBool, jbvNull, jbvNumeric, jbvObject, jbvString, JSON_TOKEN_FALSE, JSON_TOKEN_NULL, JSON_TOKEN_NUMBER, JSON_TOKEN_STRING, JSON_TOKEN_TRUE, NULL, numeric_in(), JsonbInState::parseState, pushJsonbValue(), JsonbInState::res, JsonbValue::type, JsonbValue::val, WJB_BEGIN_ARRAY, WJB_ELEM, WJB_END_ARRAY, and WJB_VALUE.

Referenced by datum_to_jsonb(), and jsonb_from_cstring().

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 }
JsonbParseState * parseState
Definition: jsonb.c:33
JsonbValue * res
Definition: jsonb.c:34
char * val
Definition: jsonb.h:259
Definition: jsonb.h:234
Definition: jsonb.h:231
JsonbValue * pushJsonbValue(JsonbParseState **pstate, JsonbIteratorToken seq, JsonbValue *jbval)
Definition: jsonb_util.c:517
#define ERROR
Definition: elog.h:43
static size_t checkStringLen(size_t len)
Definition: jsonb.c:252
#define CStringGetDatum(X)
Definition: postgres.h:584
Datum numeric_in(PG_FUNCTION_ARGS)
Definition: numeric.c:559
#define DirectFunctionCall3(func, arg1, arg2, arg3)
Definition: fmgr.h:580
JsonbValue contVal
Definition: jsonb.h:306
#define DatumGetNumeric(X)
Definition: numeric.h:49
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
enum jbvType type
Definition: jsonb.h:250
#define elog
Definition: elog.h:219
Definition: jsonb.h:25
Datum jsonb_object ( PG_FUNCTION_ARGS  )

Definition at line 1332 of file jsonb.c.

References ARR_DIMS, ARR_NDIM, deconstruct_array(), ereport, errcode(), errmsg(), ERROR, i, jbvNull, jbvString, JsonbValueToJsonb(), NULL, JsonbInState::parseState, pfree(), PG_GETARG_ARRAYTYPE_P, PG_RETURN_POINTER, pushJsonbValue(), JsonbInState::res, result, TextDatumGetCString, TEXTOID, JsonbValue::type, JsonbValue::val, WJB_BEGIN_OBJECT, WJB_END_OBJECT, WJB_KEY, and WJB_VALUE.

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;
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 }
JsonbParseState * parseState
Definition: jsonb.c:33
JsonbValue * res
Definition: jsonb.c:34
#define PG_RETURN_POINTER(x)
Definition: fmgr.h:313
Jsonb * JsonbValueToJsonb(JsonbValue *val)
Definition: jsonb_util.c:79
#define TEXTOID
Definition: pg_type.h:324
char * val
Definition: jsonb.h:259
int errcode(int sqlerrcode)
Definition: elog.c:575
return result
Definition: formatting.c:1618
Definition: jsonb.h:231
JsonbValue * pushJsonbValue(JsonbParseState **pstate, JsonbIteratorToken seq, JsonbValue *jbval)
Definition: jsonb_util.c:517
#define PG_GETARG_ARRAYTYPE_P(n)
Definition: array.h:244
void pfree(void *pointer)
Definition: mcxt.c:950
#define ERROR
Definition: elog.h:43
#define ARR_DIMS(a)
Definition: array.h:275
Definition: jsonb.h:23
#define ereport(elevel, rest)
Definition: elog.h:122
#define TextDatumGetCString(d)
Definition: builtins.h:92
uintptr_t Datum
Definition: postgres.h:372
#define NULL
Definition: c.h:229
#define ARR_NDIM(a)
Definition: array.h:271
enum jbvType type
Definition: jsonb.h:250
void deconstruct_array(ArrayType *array, Oid elmtype, int elmlen, bool elmbyval, char elmalign, Datum **elemsp, bool **nullsp, int *nelemsp)
Definition: arrayfuncs.c:3475
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
Datum jsonb_object_agg_finalfn ( PG_FUNCTION_ARGS  )

Definition at line 1912 of file jsonb.c.

References AggCheckCallContext(), arg, Assert, clone_parse_state(), JsonbValueToJsonb(), NULL, JsonbInState::parseState, PG_ARGISNULL, PG_GETARG_POINTER, PG_RETURN_NULL, PG_RETURN_POINTER, pushJsonbValue(), JsonbInState::res, JsonbAggState::res, result, and WJB_END_OBJECT.

1913 {
1914  JsonbAggState *arg;
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 }
JsonbParseState * parseState
Definition: jsonb.c:33
JsonbValue * res
Definition: jsonb.c:34
#define PG_RETURN_POINTER(x)
Definition: fmgr.h:313
Jsonb * JsonbValueToJsonb(JsonbValue *val)
Definition: jsonb_util.c:79
Definition: jsonb.h:215
static JsonbParseState * clone_parse_state(JsonbParseState *state)
Definition: jsonb.c:1531
JsonbInState * res
Definition: jsonb.c:56
return result
Definition: formatting.c:1618
#define PG_GETARG_POINTER(n)
Definition: fmgr.h:233
JsonbValue * pushJsonbValue(JsonbParseState **pstate, JsonbIteratorToken seq, JsonbValue *jbval)
Definition: jsonb_util.c:517
#define PG_ARGISNULL(n)
Definition: fmgr.h:166
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
int AggCheckCallContext(FunctionCallInfo fcinfo, MemoryContext *aggcontext)
Definition: nodeAgg.c:3660
void * arg
#define PG_RETURN_NULL()
Definition: fmgr.h:297
Datum jsonb_object_agg_transfn ( PG_FUNCTION_ARGS  )

Definition at line 1716 of file jsonb.c.

References AggCheckCallContext(), buf, datum_to_jsonb(), DatumGetNumeric, DirectFunctionCall1, elog, ereport, errcode(), errmsg(), ERROR, get_fn_expr_argtype(), InvalidOid, jbvNumeric, jbvString, jsonb_categorize_type(), JsonbIteratorInit(), JsonbIteratorNext(), JsonbValueToJsonb(), JsonbAggState::key_category, JsonbAggState::key_output_func, MemoryContextSwitchTo(), NULL, numeric_uplus(), NumericGetDatum, palloc(), palloc0(), JsonbInState::parseState, PG_ARGISNULL, PG_GETARG_DATUM, PG_GETARG_POINTER, PG_RETURN_POINTER, pushJsonbValue(), JsonbInState::res, JsonbAggState::res, result, Jsonb::root, snprintf(), JsonbValue::type, JsonbValue::val, val, JsonbAggState::val_category, JsonbAggState::val_output_func, WJB_BEGIN_ARRAY, WJB_BEGIN_OBJECT, WJB_DONE, WJB_ELEM, WJB_END_ARRAY, WJB_END_OBJECT, WJB_KEY, and WJB_VALUE.

1717 {
1718  MemoryContext oldcontext,
1719  aggcontext;
1720  JsonbInState elem;
1722  Datum val;
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,
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 }
JsonbParseState * parseState
Definition: jsonb.c:33
JsonbValue * res
Definition: jsonb.c:34
#define PG_RETURN_POINTER(x)
Definition: fmgr.h:313
Jsonb * JsonbValueToJsonb(JsonbValue *val)
Definition: jsonb_util.c:79
Definition: jsonb.h:215
Datum numeric_uplus(PG_FUNCTION_ARGS)
Definition: numeric.c:1148
#define PG_GETARG_DATUM(n)
Definition: fmgr.h:225
char * val
Definition: jsonb.h:259
#define NumericGetDatum(X)
Definition: numeric.h:51
JsonbInState * res
Definition: jsonb.c:56
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Definition: jsonb.h:22
int errcode(int sqlerrcode)
Definition: elog.c:575
Oid key_output_func
Definition: jsonb.c:58
return result
Definition: formatting.c:1618
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
#define PG_GETARG_POINTER(n)
Definition: fmgr.h:233
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:576
unsigned int Oid
Definition: postgres_ext.h:31
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 ERROR
Definition: elog.h:43
Oid get_fn_expr_argtype(FmgrInfo *flinfo, int argnum)
Definition: fmgr.c:2270
static char * buf
Definition: pg_test_fsync.c:65
static void jsonb_categorize_type(Oid typoid, JsonbTypeCategory *tcategory, Oid *outfuncoid)
Definition: jsonb.c:591
Definition: jsonb.h:23
#define ereport(elevel, rest)
Definition: elog.h:122
JsonbIteratorToken
Definition: jsonb.h:20
JsonbContainer root
Definition: jsonb.h:218
void * palloc0(Size size)
Definition: mcxt.c:878
uintptr_t Datum
Definition: postgres.h:372
#define InvalidOid
Definition: postgres_ext.h:36
#define PG_ARGISNULL(n)
Definition: fmgr.h:166
#define DatumGetNumeric(X)
Definition: numeric.h:49
#define NULL
Definition: c.h:229
JsonbIterator * JsonbIteratorInit(JsonbContainer *container)
Definition: jsonb_util.c:718
Definition: regguts.h:298
int AggCheckCallContext(FunctionCallInfo fcinfo, MemoryContext *aggcontext)
Definition: nodeAgg.c:3660
JsonbTypeCategory key_category
Definition: jsonb.c:57
enum jbvType type
Definition: jsonb.h:250
void * palloc(Size size)
Definition: mcxt.c:849
int errmsg(const char *fmt,...)
Definition: elog.c:797
Oid val_output_func
Definition: jsonb.c:60
#define elog
Definition: elog.h:219
long val
Definition: informix.c:689
JsonbIteratorToken JsonbIteratorNext(JsonbIterator **it, JsonbValue *val, bool skipNested)
Definition: jsonb_util.c:754
Definition: jsonb.h:25
Datum jsonb_object_two_arg ( PG_FUNCTION_ARGS  )

Definition at line 1434 of file jsonb.c.

References ARR_NDIM, deconstruct_array(), ereport, errcode(), errmsg(), ERROR, i, jbvNull, jbvString, JsonbValueToJsonb(), NULL, JsonbInState::parseState, pfree(), PG_GETARG_ARRAYTYPE_P, PG_RETURN_POINTER, pushJsonbValue(), JsonbInState::res, result, TextDatumGetCString, TEXTOID, JsonbValue::type, JsonbValue::val, WJB_BEGIN_OBJECT, WJB_END_OBJECT, WJB_KEY, and WJB_VALUE.

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;
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 }
JsonbParseState * parseState
Definition: jsonb.c:33
JsonbValue * res
Definition: jsonb.c:34
#define PG_RETURN_POINTER(x)
Definition: fmgr.h:313
Jsonb * JsonbValueToJsonb(JsonbValue *val)
Definition: jsonb_util.c:79
#define TEXTOID
Definition: pg_type.h:324
char * val
Definition: jsonb.h:259
int errcode(int sqlerrcode)
Definition: elog.c:575
return result
Definition: formatting.c:1618
Definition: jsonb.h:231
JsonbValue * pushJsonbValue(JsonbParseState **pstate, JsonbIteratorToken seq, JsonbValue *jbval)
Definition: jsonb_util.c:517
#define PG_GETARG_ARRAYTYPE_P(n)
Definition: array.h:244
void pfree(void *pointer)
Definition: mcxt.c:950
#define ERROR
Definition: elog.h:43
Definition: jsonb.h:23
#define ereport(elevel, rest)
Definition: elog.h:122
#define TextDatumGetCString(d)
Definition: builtins.h:92
uintptr_t Datum
Definition: postgres.h:372
#define NULL
Definition: c.h:229
#define ARR_NDIM(a)
Definition: array.h:271
enum jbvType type
Definition: jsonb.h:250
void deconstruct_array(ArrayType *array, Oid elmtype, int elmlen, bool elmbyval, char elmalign, Datum **elemsp, bool **nullsp, int *nelemsp)
Definition: arrayfuncs.c:3475
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
Datum jsonb_out ( PG_FUNCTION_ARGS  )

Definition at line 131 of file jsonb.c.

References JsonbToCString(), NULL, PG_GETARG_JSONB, PG_RETURN_CSTRING, Jsonb::root, and VARSIZE.

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 }
Definition: jsonb.h:215
#define VARSIZE(PTR)
Definition: postgres.h:304
JsonbContainer root
Definition: jsonb.h:218
#define NULL
Definition: c.h:229
#define PG_RETURN_CSTRING(x)
Definition: fmgr.h:314
char * JsonbToCString(StringInfo out, JsonbContainer *in, int estimated_len)
Definition: jsonb.c:428
#define PG_GETARG_JSONB(x)
Definition: jsonb.h:70
static void jsonb_put_escaped_value ( StringInfo  out,
JsonbValue scalarVal 
)
static

Definition at line 311 of file jsonb.c.

References appendBinaryStringInfo(), appendStringInfoString(), DatumGetCString, DirectFunctionCall1, elog, ERROR, escape_json(), jbvBool, jbvNull, jbvNumeric, jbvString, numeric_out(), pnstrdup(), PointerGetDatum, JsonbValue::type, and JsonbValue::val.

Referenced by JsonbToCStringWorker().

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 }
char * pnstrdup(const char *in, Size len)
Definition: mcxt.c:1088
void escape_json(StringInfo buf, const char *str)
Definition: json.c:2433
#define PointerGetDatum(X)
Definition: postgres.h:562
char * val
Definition: jsonb.h:259
Definition: jsonb.h:234
Datum numeric_out(PG_FUNCTION_ARGS)
Definition: numeric.c:641
Definition: jsonb.h:231
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:576
#define ERROR
Definition: elog.h:43
#define DatumGetCString(X)
Definition: postgres.h:572
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:189
enum jbvType type
Definition: jsonb.h:250
#define elog
Definition: elog.h:219
void appendBinaryStringInfo(StringInfo str, const char *data, int datalen)
Definition: stringinfo.c:240
Datum jsonb_recv ( PG_FUNCTION_ARGS  )

Definition at line 112 of file jsonb.c.

References buf, StringInfoData::cursor, elog, ERROR, jsonb_from_cstring(), StringInfoData::len, PG_GETARG_POINTER, pq_getmsgint(), and pq_getmsgtext().

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 }
static Datum jsonb_from_cstring(char *json, int len)
Definition: jsonb.c:226
StringInfoData * StringInfo
Definition: stringinfo.h:46
#define PG_GETARG_POINTER(n)
Definition: fmgr.h:233
#define ERROR
Definition: elog.h:43
static char * buf
Definition: pg_test_fsync.c:65
char * pq_getmsgtext(StringInfo msg, int rawbytes, int *nbytes)
Definition: pqformat.c:588
unsigned int pq_getmsgint(StringInfo msg, int b)
Definition: pqformat.c:448
#define elog
Definition: elog.h:219
Datum jsonb_send ( PG_FUNCTION_ARGS  )

Definition at line 147 of file jsonb.c.

References buf, StringInfoData::data, JsonbToCString(), StringInfoData::len, makeStringInfo(), pfree(), PG_GETARG_JSONB, PG_RETURN_BYTEA_P, pq_begintypsend(), pq_endtypsend(), pq_sendint(), pq_sendtext(), Jsonb::root, and VARSIZE.

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 }
Definition: jsonb.h:215
#define VARSIZE(PTR)
Definition: postgres.h:304
void pq_begintypsend(StringInfo buf)
Definition: pqformat.c:359
StringInfo makeStringInfo(void)
Definition: stringinfo.c:29
void pq_sendtext(StringInfo buf, const char *str, int slen)
Definition: pqformat.c:163
#define PG_RETURN_BYTEA_P(x)
Definition: fmgr.h:321
bytea * pq_endtypsend(StringInfo buf)
Definition: pqformat.c:379
void pfree(void *pointer)
Definition: mcxt.c:950
static char * buf
Definition: pg_test_fsync.c:65
JsonbContainer root
Definition: jsonb.h:218
char * JsonbToCString(StringInfo out, JsonbContainer *in, int estimated_len)
Definition: jsonb.c:428
#define PG_GETARG_JSONB(x)
Definition: jsonb.h:70
void pq_sendint(StringInfo buf, int i, int b)
Definition: pqformat.c:236
Datum jsonb_typeof ( PG_FUNCTION_ARGS  )

Definition at line 172 of file jsonb.c.

References Assert, cstring_to_text(), elog, ERROR, JB_ROOT_IS_ARRAY, JB_ROOT_IS_OBJECT, JB_ROOT_IS_SCALAR, jbvArray, jbvBool, jbvNull, jbvNumeric, jbvString, JsonbIteratorInit(), JsonbIteratorNext(), PG_GETARG_JSONB, PG_RETURN_TEXT_P, result, Jsonb::root, and JsonbValue::type.

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 }
#define JB_ROOT_IS_OBJECT(jbp_)
Definition: jsonb.h:224
Definition: jsonb.h:215
Definition: jsonb.h:234
return result
Definition: formatting.c:1618
Definition: jsonb.h:231
#define JB_ROOT_IS_SCALAR(jbp_)
Definition: jsonb.h:223
#define ERROR
Definition: elog.h:43
#define JB_ROOT_IS_ARRAY(jbp_)
Definition: jsonb.h:225
JsonbContainer root
Definition: jsonb.h:218
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:322
text * cstring_to_text(const char *s)
Definition: varlena.c:149
#define Assert(condition)
Definition: c.h:675
JsonbIterator * JsonbIteratorInit(JsonbContainer *container)
Definition: jsonb_util.c:718
enum jbvType type
Definition: jsonb.h:250
#define PG_GETARG_JSONB(x)
Definition: jsonb.h:70
#define elog
Definition: elog.h:219
JsonbIteratorToken JsonbIteratorNext(JsonbIterator **it, JsonbValue *val, bool skipNested)
Definition: jsonb_util.c:754
char* JsonbToCString ( StringInfo  out,
JsonbContainer in,
int  estimated_len 
)

Definition at line 428 of file jsonb.c.

References JsonbToCStringWorker().

Referenced by each_worker_jsonb(), elements_worker_jsonb(), get_jsonb_path_all(), jsonb_array_element_text(), jsonb_object_field_text(), jsonb_out(), jsonb_send(), make_row_from_rec_and_jsonb(), and populate_record_worker().

429 {
430  return JsonbToCStringWorker(out, in, estimated_len, false);
431 }
static char * JsonbToCStringWorker(StringInfo out, JsonbContainer *in, int estimated_len, bool indent)
Definition: jsonb.c:446
char* JsonbToCStringIndent ( StringInfo  out,
JsonbContainer in,
int  estimated_len 
)

Definition at line 437 of file jsonb.c.

References JsonbToCStringWorker().

Referenced by jsonb_pretty().

438 {
439  return JsonbToCStringWorker(out, in, estimated_len, true);
440 }
static char * JsonbToCStringWorker(StringInfo out, JsonbContainer *in, int estimated_len, bool indent)
Definition: jsonb.c:446
static char * JsonbToCStringWorker ( StringInfo  out,
JsonbContainer in,
int  estimated_len,
bool  indent 
)
static

Definition at line 446 of file jsonb.c.

References add_indent(), appendBinaryStringInfo(), appendStringInfoCharMacro, Assert, StringInfoData::data, elog, enlargeStringInfo(), ERROR, jsonb_put_escaped_value(), JsonbIteratorInit(), JsonbIteratorNext(), makeStringInfo(), NULL, JsonbValue::val, WJB_BEGIN_ARRAY, WJB_BEGIN_OBJECT, WJB_DONE, WJB_ELEM, WJB_END_ARRAY, WJB_END_OBJECT, WJB_KEY, and WJB_VALUE.

Referenced by JsonbToCString(), and JsonbToCStringIndent().

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 }
char * val
Definition: jsonb.h:259
StringInfo makeStringInfo(void)
Definition: stringinfo.c:29
Definition: jsonb.h:22
#define appendStringInfoCharMacro(str, ch)
Definition: stringinfo.h:135
#define ERROR
Definition: elog.h:43
void enlargeStringInfo(StringInfo str, int needed)
Definition: stringinfo.c:277
Definition: jsonb.h:23
JsonbIteratorToken
Definition: jsonb.h:20
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
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
JsonbIterator * JsonbIteratorInit(JsonbContainer *container)
Definition: jsonb_util.c:718
#define elog
Definition: elog.h:219
void appendBinaryStringInfo(StringInfo str, const char *data, int datalen)
Definition: stringinfo.c:240
JsonbIteratorToken JsonbIteratorNext(JsonbIterator **it, JsonbValue *val, bool skipNested)
Definition: jsonb_util.c:754
Definition: jsonb.h:25
Datum to_jsonb ( PG_FUNCTION_ARGS  )

Definition at line 1145 of file jsonb.c.

References datum_to_jsonb(), ereport, errcode(), errmsg(), ERROR, get_fn_expr_argtype(), InvalidOid, jsonb_categorize_type(), JsonbValueToJsonb(), PG_GETARG_DATUM, PG_RETURN_POINTER, JsonbInState::res, result, and val.

1146 {
1147  Datum val = PG_GETARG_DATUM(0);
1148  Oid val_type = get_fn_expr_argtype(fcinfo->flinfo, 0);
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 }
JsonbValue * res
Definition: jsonb.c:34
#define PG_RETURN_POINTER(x)
Definition: fmgr.h:313
Jsonb * JsonbValueToJsonb(JsonbValue *val)
Definition: jsonb_util.c:79
#define PG_GETARG_DATUM(n)
Definition: fmgr.h:225
int errcode(int sqlerrcode)
Definition: elog.c:575
return result
Definition: formatting.c:1618
unsigned int Oid
Definition: postgres_ext.h:31
static void datum_to_jsonb(Datum val, bool is_null, JsonbInState *result, JsonbTypeCategory tcategory, Oid outfuncoid, bool key_scalar)
Definition: jsonb.c:699
#define ERROR
Definition: elog.h:43
Oid get_fn_expr_argtype(FmgrInfo *flinfo, int argnum)
Definition: fmgr.c:2270
static void jsonb_categorize_type(Oid typoid, JsonbTypeCategory *tcategory, Oid *outfuncoid)
Definition: jsonb.c:591
#define ereport(elevel, rest)
Definition: elog.h:122
uintptr_t Datum
Definition: postgres.h:372
JsonbTypeCategory
Definition: jsonb.c:38
#define InvalidOid
Definition: postgres_ext.h:36
int errmsg(const char *fmt,...)
Definition: elog.c:797
long val
Definition: informix.c:689