PostgreSQL Source Code git master
json.c File Reference
#include "postgres.h"
#include "access/htup_details.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"
#include "common/hashfn.h"
#include "funcapi.h"
#include "libpq/pqformat.h"
#include "miscadmin.h"
#include "port/simd.h"
#include "utils/array.h"
#include "utils/builtins.h"
#include "utils/date.h"
#include "utils/datetime.h"
#include "utils/fmgroids.h"
#include "utils/json.h"
#include "utils/jsonfuncs.h"
#include "utils/lsyscache.h"
#include "utils/typcache.h"
Include dependency graph for json.c:

Go to the source code of this file.

Data Structures

struct  JsonUniqueHashEntry
 
struct  JsonUniqueStackEntry
 
struct  JsonUniqueParsingState
 
struct  JsonUniqueBuilderState
 
struct  JsonAggState
 

Macros

#define ESCAPE_JSON_FLUSH_AFTER   512
 

Typedefs

typedef struct HTABJsonUniqueCheckState
 
typedef struct JsonUniqueHashEntry JsonUniqueHashEntry
 
typedef struct JsonUniqueStackEntry JsonUniqueStackEntry
 
typedef struct JsonUniqueParsingState JsonUniqueParsingState
 
typedef struct JsonUniqueBuilderState JsonUniqueBuilderState
 
typedef struct JsonAggState JsonAggState
 

Functions

static void composite_to_json (Datum composite, StringInfo result, bool use_line_feeds)
 
static void array_dim_to_json (StringInfo result, int dim, int ndims, int *dims, const Datum *vals, const bool *nulls, int *valcount, JsonTypeCategory tcategory, Oid outfuncoid, bool use_line_feeds)
 
static void array_to_json_internal (Datum array, StringInfo result, bool use_line_feeds)
 
static void datum_to_json_internal (Datum val, bool is_null, StringInfo result, JsonTypeCategory tcategory, Oid outfuncoid, bool key_scalar)
 
static void add_json (Datum val, bool is_null, StringInfo result, Oid val_type, bool key_scalar)
 
static textcatenate_stringinfo_string (StringInfo buffer, const char *addon)
 
Datum json_in (PG_FUNCTION_ARGS)
 
Datum json_out (PG_FUNCTION_ARGS)
 
Datum json_send (PG_FUNCTION_ARGS)
 
Datum json_recv (PG_FUNCTION_ARGS)
 
char * JsonEncodeDateTime (char *buf, Datum value, Oid typid, const int *tzp)
 
Datum array_to_json (PG_FUNCTION_ARGS)
 
Datum array_to_json_pretty (PG_FUNCTION_ARGS)
 
Datum row_to_json (PG_FUNCTION_ARGS)
 
Datum row_to_json_pretty (PG_FUNCTION_ARGS)
 
bool to_json_is_immutable (Oid typoid)
 
Datum to_json (PG_FUNCTION_ARGS)
 
Datum datum_to_json (Datum val, JsonTypeCategory tcategory, Oid outfuncoid)
 
static Datum json_agg_transfn_worker (FunctionCallInfo fcinfo, bool absent_on_null)
 
Datum json_agg_transfn (PG_FUNCTION_ARGS)
 
Datum json_agg_strict_transfn (PG_FUNCTION_ARGS)
 
Datum json_agg_finalfn (PG_FUNCTION_ARGS)
 
static uint32 json_unique_hash (const void *key, Size keysize)
 
static int json_unique_hash_match (const void *key1, const void *key2, Size keysize)
 
static void json_unique_check_init (JsonUniqueCheckState *cxt)
 
static void json_unique_builder_init (JsonUniqueBuilderState *cxt)
 
static bool json_unique_check_key (JsonUniqueCheckState *cxt, const char *key, int object_id)
 
static StringInfo json_unique_builder_get_throwawaybuf (JsonUniqueBuilderState *cxt)
 
static Datum json_object_agg_transfn_worker (FunctionCallInfo fcinfo, bool absent_on_null, bool unique_keys)
 
Datum json_object_agg_transfn (PG_FUNCTION_ARGS)
 
Datum json_object_agg_strict_transfn (PG_FUNCTION_ARGS)
 
Datum json_object_agg_unique_transfn (PG_FUNCTION_ARGS)
 
Datum json_object_agg_unique_strict_transfn (PG_FUNCTION_ARGS)
 
Datum json_object_agg_finalfn (PG_FUNCTION_ARGS)
 
Datum json_build_object_worker (int nargs, const Datum *args, const bool *nulls, const Oid *types, bool absent_on_null, bool unique_keys)
 
Datum json_build_object (PG_FUNCTION_ARGS)
 
Datum json_build_object_noargs (PG_FUNCTION_ARGS)
 
Datum json_build_array_worker (int nargs, const Datum *args, const bool *nulls, const Oid *types, bool absent_on_null)
 
Datum json_build_array (PG_FUNCTION_ARGS)
 
Datum json_build_array_noargs (PG_FUNCTION_ARGS)
 
Datum json_object (PG_FUNCTION_ARGS)
 
Datum json_object_two_arg (PG_FUNCTION_ARGS)
 
static pg_attribute_always_inline void escape_json_char (StringInfo buf, char c)
 
void escape_json (StringInfo buf, const char *str)
 
void escape_json_with_len (StringInfo buf, const char *str, int len)
 
void escape_json_text (StringInfo buf, const text *txt)
 
static JsonParseErrorType json_unique_object_start (void *_state)
 
static JsonParseErrorType json_unique_object_end (void *_state)
 
static JsonParseErrorType json_unique_object_field_start (void *_state, char *field, bool isnull)
 
bool json_validate (text *json, bool check_unique_keys, bool throw_error)
 
Datum json_typeof (PG_FUNCTION_ARGS)
 

Macro Definition Documentation

◆ ESCAPE_JSON_FLUSH_AFTER

#define ESCAPE_JSON_FLUSH_AFTER   512

Definition at line 1624 of file json.c.

Typedef Documentation

◆ JsonAggState

typedef struct JsonAggState JsonAggState

◆ JsonUniqueBuilderState

◆ JsonUniqueCheckState

typedef struct HTAB* JsonUniqueCheckState

Definition at line 42 of file json.c.

◆ JsonUniqueHashEntry

◆ JsonUniqueParsingState

◆ JsonUniqueStackEntry

Function Documentation

◆ add_json()

static void add_json ( Datum  val,
bool  is_null,
StringInfo  result,
Oid  val_type,
bool  key_scalar 
)
static

Definition at line 603 of file json.c.

605{
606 JsonTypeCategory tcategory;
607 Oid outfuncoid;
608
609 if (val_type == InvalidOid)
611 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
612 errmsg("could not determine input data type")));
613
614 if (is_null)
615 {
616 tcategory = JSONTYPE_NULL;
617 outfuncoid = InvalidOid;
618 }
619 else
620 json_categorize_type(val_type, false,
621 &tcategory, &outfuncoid);
622
623 datum_to_json_internal(val, is_null, result, tcategory, outfuncoid,
624 key_scalar);
625}
int errcode(int sqlerrcode)
Definition: elog.c:863
int errmsg(const char *fmt,...)
Definition: elog.c:1080
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:150
long val
Definition: informix.c:689
static void datum_to_json_internal(Datum val, bool is_null, StringInfo result, JsonTypeCategory tcategory, Oid outfuncoid, bool key_scalar)
Definition: json.c:180
void json_categorize_type(Oid typoid, bool is_jsonb, JsonTypeCategory *tcategory, Oid *outfuncoid)
Definition: jsonfuncs.c:6005
JsonTypeCategory
Definition: jsonfuncs.h:69
@ JSONTYPE_NULL
Definition: jsonfuncs.h:70
#define InvalidOid
Definition: postgres_ext.h:37
unsigned int Oid
Definition: postgres_ext.h:32

References datum_to_json_internal(), ereport, errcode(), errmsg(), ERROR, InvalidOid, json_categorize_type(), JSONTYPE_NULL, and val.

Referenced by json_build_array_worker(), and json_build_object_worker().

◆ array_dim_to_json()

static void array_dim_to_json ( StringInfo  result,
int  dim,
int  ndims,
int *  dims,
const Datum vals,
const bool *  nulls,
int *  valcount,
JsonTypeCategory  tcategory,
Oid  outfuncoid,
bool  use_line_feeds 
)
static

Definition at line 432 of file json.c.

435{
436 int i;
437 const char *sep;
438
439 Assert(dim < ndims);
440
441 sep = use_line_feeds ? ",\n " : ",";
442
443 appendStringInfoChar(result, '[');
444
445 for (i = 1; i <= dims[dim]; i++)
446 {
447 if (i > 1)
448 appendStringInfoString(result, sep);
449
450 if (dim + 1 == ndims)
451 {
452 datum_to_json_internal(vals[*valcount], nulls[*valcount],
453 result, tcategory,
454 outfuncoid, false);
455 (*valcount)++;
456 }
457 else
458 {
459 /*
460 * Do we want line feeds on inner dimensions of arrays? For now
461 * we'll say no.
462 */
463 array_dim_to_json(result, dim + 1, ndims, dims, vals, nulls,
464 valcount, tcategory, outfuncoid, false);
465 }
466 }
467
468 appendStringInfoChar(result, ']');
469}
Assert(PointerIsAligned(start, uint64))
int i
Definition: isn.c:77
static void array_dim_to_json(StringInfo result, int dim, int ndims, int *dims, const Datum *vals, const bool *nulls, int *valcount, JsonTypeCategory tcategory, Oid outfuncoid, bool use_line_feeds)
Definition: json.c:432
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:230
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:242

References appendStringInfoChar(), appendStringInfoString(), array_dim_to_json(), Assert(), datum_to_json_internal(), and i.

Referenced by array_dim_to_json(), and array_to_json_internal().

◆ array_to_json()

Datum array_to_json ( PG_FUNCTION_ARGS  )

Definition at line 631 of file json.c.

632{
633 Datum array = PG_GETARG_DATUM(0);
634 StringInfoData result;
635
636 initStringInfo(&result);
637
638 array_to_json_internal(array, &result, false);
639
641}
#define PG_GETARG_DATUM(n)
Definition: fmgr.h:268
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:372
static void array_to_json_internal(Datum array, StringInfo result, bool use_line_feeds)
Definition: json.c:475
uint64_t Datum
Definition: postgres.h:70
void initStringInfo(StringInfo str)
Definition: stringinfo.c:97
text * cstring_to_text_with_len(const char *s, int len)
Definition: varlena.c:193

References array_to_json_internal(), cstring_to_text_with_len(), StringInfoData::data, initStringInfo(), StringInfoData::len, PG_GETARG_DATUM, and PG_RETURN_TEXT_P.

◆ array_to_json_internal()

static void array_to_json_internal ( Datum  array,
StringInfo  result,
bool  use_line_feeds 
)
static

Definition at line 475 of file json.c.

476{
477 ArrayType *v = DatumGetArrayTypeP(array);
478 Oid element_type = ARR_ELEMTYPE(v);
479 int *dim;
480 int ndim;
481 int nitems;
482 int count = 0;
483 Datum *elements;
484 bool *nulls;
485 int16 typlen;
486 bool typbyval;
487 char typalign;
488 JsonTypeCategory tcategory;
489 Oid outfuncoid;
490
491 ndim = ARR_NDIM(v);
492 dim = ARR_DIMS(v);
493 nitems = ArrayGetNItems(ndim, dim);
494
495 if (nitems <= 0)
496 {
497 appendStringInfoString(result, "[]");
498 return;
499 }
500
501 get_typlenbyvalalign(element_type,
502 &typlen, &typbyval, &typalign);
503
504 json_categorize_type(element_type, false,
505 &tcategory, &outfuncoid);
506
507 deconstruct_array(v, element_type, typlen, typbyval,
508 typalign, &elements, &nulls,
509 &nitems);
510
511 array_dim_to_json(result, 0, ndim, dim, elements, nulls, &count, tcategory,
512 outfuncoid, use_line_feeds);
513
514 pfree(elements);
515 pfree(nulls);
516}
#define ARR_NDIM(a)
Definition: array.h:290
#define DatumGetArrayTypeP(X)
Definition: array.h:261
#define ARR_ELEMTYPE(a)
Definition: array.h:292
#define ARR_DIMS(a)
Definition: array.h:294
void deconstruct_array(const ArrayType *array, Oid elmtype, int elmlen, bool elmbyval, char elmalign, Datum **elemsp, bool **nullsp, int *nelemsp)
Definition: arrayfuncs.c:3632
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:57
int16_t int16
Definition: c.h:538
#define nitems(x)
Definition: indent.h:31
void get_typlenbyvalalign(Oid typid, int16 *typlen, bool *typbyval, char *typalign)
Definition: lsyscache.c:2438
void pfree(void *pointer)
Definition: mcxt.c:1594
char typalign
Definition: pg_type.h:176

References appendStringInfoString(), ARR_DIMS, ARR_ELEMTYPE, ARR_NDIM, array_dim_to_json(), ArrayGetNItems(), DatumGetArrayTypeP, deconstruct_array(), get_typlenbyvalalign(), json_categorize_type(), nitems, pfree(), and typalign.

Referenced by array_to_json(), array_to_json_pretty(), and datum_to_json_internal().

◆ array_to_json_pretty()

Datum array_to_json_pretty ( PG_FUNCTION_ARGS  )

Definition at line 647 of file json.c.

648{
649 Datum array = PG_GETARG_DATUM(0);
650 bool use_line_feeds = PG_GETARG_BOOL(1);
651 StringInfoData result;
652
653 initStringInfo(&result);
654
655 array_to_json_internal(array, &result, use_line_feeds);
656
658}
#define PG_GETARG_BOOL(n)
Definition: fmgr.h:274

References array_to_json_internal(), cstring_to_text_with_len(), StringInfoData::data, initStringInfo(), StringInfoData::len, PG_GETARG_BOOL, PG_GETARG_DATUM, and PG_RETURN_TEXT_P.

◆ catenate_stringinfo_string()

static text * catenate_stringinfo_string ( StringInfo  buffer,
const char *  addon 
)
static

Definition at line 1211 of file json.c.

1212{
1213 /* custom version of cstring_to_text_with_len */
1214 int buflen = buffer->len;
1215 int addlen = strlen(addon);
1216 text *result = (text *) palloc(buflen + addlen + VARHDRSZ);
1217
1218 SET_VARSIZE(result, buflen + addlen + VARHDRSZ);
1219 memcpy(VARDATA(result), buffer->data, buflen);
1220 memcpy(VARDATA(result) + buflen, addon, addlen);
1221
1222 return result;
1223}
#define VARHDRSZ
Definition: c.h:702
void * palloc(Size size)
Definition: mcxt.c:1365
Definition: c.h:697
static char * VARDATA(const void *PTR)
Definition: varatt.h:305
static void SET_VARSIZE(void *PTR, Size len)
Definition: varatt.h:432

References StringInfoData::data, StringInfoData::len, palloc(), SET_VARSIZE(), VARDATA(), and VARHDRSZ.

Referenced by json_agg_finalfn(), and json_object_agg_finalfn().

◆ composite_to_json()

static void composite_to_json ( Datum  composite,
StringInfo  result,
bool  use_line_feeds 
)
static

Definition at line 522 of file json.c.

523{
525 Oid tupType;
526 int32 tupTypmod;
527 TupleDesc tupdesc;
528 HeapTupleData tmptup,
529 *tuple;
530 int i;
531 bool needsep = false;
532 const char *sep;
533 int seplen;
534
535 /*
536 * We can avoid expensive strlen() calls by precalculating the separator
537 * length.
538 */
539 sep = use_line_feeds ? ",\n " : ",";
540 seplen = use_line_feeds ? strlen(",\n ") : strlen(",");
541
542 td = DatumGetHeapTupleHeader(composite);
543
544 /* Extract rowtype info and find a tupdesc */
545 tupType = HeapTupleHeaderGetTypeId(td);
546 tupTypmod = HeapTupleHeaderGetTypMod(td);
547 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
548
549 /* Build a temporary HeapTuple control structure */
551 tmptup.t_data = td;
552 tuple = &tmptup;
553
554 appendStringInfoChar(result, '{');
555
556 for (i = 0; i < tupdesc->natts; i++)
557 {
558 Datum val;
559 bool isnull;
560 char *attname;
561 JsonTypeCategory tcategory;
562 Oid outfuncoid;
563 Form_pg_attribute att = TupleDescAttr(tupdesc, i);
564
565 if (att->attisdropped)
566 continue;
567
568 if (needsep)
569 appendBinaryStringInfo(result, sep, seplen);
570 needsep = true;
571
572 attname = NameStr(att->attname);
573 escape_json(result, attname);
574 appendStringInfoChar(result, ':');
575
576 val = heap_getattr(tuple, i + 1, tupdesc, &isnull);
577
578 if (isnull)
579 {
580 tcategory = JSONTYPE_NULL;
581 outfuncoid = InvalidOid;
582 }
583 else
584 json_categorize_type(att->atttypid, false, &tcategory,
585 &outfuncoid);
586
587 datum_to_json_internal(val, isnull, result, tcategory, outfuncoid,
588 false);
589 }
590
591 appendStringInfoChar(result, '}');
592 ReleaseTupleDesc(tupdesc);
593}
#define NameStr(name)
Definition: c.h:756
int32_t int32
Definition: c.h:539
#define DatumGetHeapTupleHeader(X)
Definition: fmgr.h:295
static Datum heap_getattr(HeapTuple tup, int attnum, TupleDesc tupleDesc, bool *isnull)
Definition: htup_details.h:904
static int32 HeapTupleHeaderGetTypMod(const HeapTupleHeaderData *tup)
Definition: htup_details.h:516
static uint32 HeapTupleHeaderGetDatumLength(const HeapTupleHeaderData *tup)
Definition: htup_details.h:492
static Oid HeapTupleHeaderGetTypeId(const HeapTupleHeaderData *tup)
Definition: htup_details.h:504
void escape_json(StringInfo buf, const char *str)
Definition: json.c:1604
NameData attname
Definition: pg_attribute.h:41
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:202
void appendBinaryStringInfo(StringInfo str, const void *data, int datalen)
Definition: stringinfo.c:281
uint32 t_len
Definition: htup.h:64
HeapTupleHeader t_data
Definition: htup.h:68
#define ReleaseTupleDesc(tupdesc)
Definition: tupdesc.h:219
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)
Definition: tupdesc.h:160
TupleDesc lookup_rowtype_tupdesc(Oid type_id, int32 typmod)
Definition: typcache.c:1921

References appendBinaryStringInfo(), appendStringInfoChar(), attname, datum_to_json_internal(), DatumGetHeapTupleHeader, escape_json(), heap_getattr(), HeapTupleHeaderGetDatumLength(), HeapTupleHeaderGetTypeId(), HeapTupleHeaderGetTypMod(), i, InvalidOid, json_categorize_type(), JSONTYPE_NULL, lookup_rowtype_tupdesc(), NameStr, TupleDescData::natts, ReleaseTupleDesc, HeapTupleData::t_data, HeapTupleData::t_len, TupleDescAttr(), and val.

Referenced by datum_to_json_internal(), row_to_json(), and row_to_json_pretty().

◆ datum_to_json()

Datum datum_to_json ( Datum  val,
JsonTypeCategory  tcategory,
Oid  outfuncoid 
)

Definition at line 764 of file json.c.

765{
766 StringInfoData result;
767
768 initStringInfo(&result);
769 datum_to_json_internal(val, false, &result, tcategory, outfuncoid,
770 false);
771
772 return PointerGetDatum(cstring_to_text_with_len(result.data, result.len));
773}
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:332

References cstring_to_text_with_len(), StringInfoData::data, datum_to_json_internal(), initStringInfo(), StringInfoData::len, PointerGetDatum(), and val.

Referenced by ExecEvalJsonConstructor(), and to_json().

◆ datum_to_json_internal()

static void datum_to_json_internal ( Datum  val,
bool  is_null,
StringInfo  result,
JsonTypeCategory  tcategory,
Oid  outfuncoid,
bool  key_scalar 
)
static

Definition at line 180 of file json.c.

183{
184 char *outputstr;
185 text *jsontext;
186
188
189 /* callers are expected to ensure that null keys are not passed in */
190 Assert(!(key_scalar && is_null));
191
192 if (is_null)
193 {
194 appendBinaryStringInfo(result, "null", strlen("null"));
195 return;
196 }
197
198 if (key_scalar &&
199 (tcategory == JSONTYPE_ARRAY ||
200 tcategory == JSONTYPE_COMPOSITE ||
201 tcategory == JSONTYPE_JSON ||
202 tcategory == JSONTYPE_CAST))
204 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
205 errmsg("key value must be scalar, not array, composite, or json")));
206
207 switch (tcategory)
208 {
209 case JSONTYPE_ARRAY:
210 array_to_json_internal(val, result, false);
211 break;
213 composite_to_json(val, result, false);
214 break;
215 case JSONTYPE_BOOL:
216 if (key_scalar)
217 appendStringInfoChar(result, '"');
218 if (DatumGetBool(val))
219 appendBinaryStringInfo(result, "true", strlen("true"));
220 else
221 appendBinaryStringInfo(result, "false", strlen("false"));
222 if (key_scalar)
223 appendStringInfoChar(result, '"');
224 break;
225 case JSONTYPE_NUMERIC:
226 outputstr = OidOutputFunctionCall(outfuncoid, val);
227
228 /*
229 * Don't quote a non-key if it's a valid JSON number (i.e., not
230 * "Infinity", "-Infinity", or "NaN"). Since we know this is a
231 * numeric data type's output, we simplify and open-code the
232 * validation for better performance.
233 */
234 if (!key_scalar &&
235 ((*outputstr >= '0' && *outputstr <= '9') ||
236 (*outputstr == '-' &&
237 (outputstr[1] >= '0' && outputstr[1] <= '9'))))
238 appendStringInfoString(result, outputstr);
239 else
240 {
241 appendStringInfoChar(result, '"');
242 appendStringInfoString(result, outputstr);
243 appendStringInfoChar(result, '"');
244 }
245 pfree(outputstr);
246 break;
247 case JSONTYPE_DATE:
248 {
249 char buf[MAXDATELEN + 1];
250
251 JsonEncodeDateTime(buf, val, DATEOID, NULL);
252 appendStringInfoChar(result, '"');
254 appendStringInfoChar(result, '"');
255 }
256 break;
258 {
259 char buf[MAXDATELEN + 1];
260
261 JsonEncodeDateTime(buf, val, TIMESTAMPOID, NULL);
262 appendStringInfoChar(result, '"');
264 appendStringInfoChar(result, '"');
265 }
266 break;
268 {
269 char buf[MAXDATELEN + 1];
270
271 JsonEncodeDateTime(buf, val, TIMESTAMPTZOID, NULL);
272 appendStringInfoChar(result, '"');
274 appendStringInfoChar(result, '"');
275 }
276 break;
277 case JSONTYPE_JSON:
278 /* JSON and JSONB output will already be escaped */
279 outputstr = OidOutputFunctionCall(outfuncoid, val);
280 appendStringInfoString(result, outputstr);
281 pfree(outputstr);
282 break;
283 case JSONTYPE_CAST:
284 /* outfuncoid refers to a cast function, not an output function */
285 jsontext = DatumGetTextPP(OidFunctionCall1(outfuncoid, val));
286 appendBinaryStringInfo(result, VARDATA_ANY(jsontext),
287 VARSIZE_ANY_EXHDR(jsontext));
288 pfree(jsontext);
289 break;
290 default:
291 /* special-case text types to save useless palloc/memcpy cycles */
292 if (outfuncoid == F_TEXTOUT || outfuncoid == F_VARCHAROUT ||
293 outfuncoid == F_BPCHAROUT)
295 else
296 {
297 outputstr = OidOutputFunctionCall(outfuncoid, val);
298 escape_json(result, outputstr);
299 pfree(outputstr);
300 }
301 break;
302 }
303}
char * OidOutputFunctionCall(Oid functionId, Datum val)
Definition: fmgr.c:1763
#define OidFunctionCall1(functionId, arg1)
Definition: fmgr.h:720
#define DatumGetTextPP(X)
Definition: fmgr.h:292
#define MAXDATELEN
Definition: datetime.h:200
void escape_json_text(StringInfo buf, const text *txt)
Definition: json.c:1738
char * JsonEncodeDateTime(char *buf, Datum value, Oid typid, const int *tzp)
Definition: json.c:311
static void composite_to_json(Datum composite, StringInfo result, bool use_line_feeds)
Definition: json.c:522
@ JSONTYPE_JSON
Definition: jsonfuncs.h:76
@ JSONTYPE_TIMESTAMP
Definition: jsonfuncs.h:74
@ JSONTYPE_NUMERIC
Definition: jsonfuncs.h:72
@ JSONTYPE_DATE
Definition: jsonfuncs.h:73
@ JSONTYPE_BOOL
Definition: jsonfuncs.h:71
@ JSONTYPE_CAST
Definition: jsonfuncs.h:80
@ JSONTYPE_COMPOSITE
Definition: jsonfuncs.h:79
@ JSONTYPE_ARRAY
Definition: jsonfuncs.h:78
@ JSONTYPE_TIMESTAMPTZ
Definition: jsonfuncs.h:75
static char * buf
Definition: pg_test_fsync.c:72
static bool DatumGetBool(Datum X)
Definition: postgres.h:100
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:322
void check_stack_depth(void)
Definition: stack_depth.c:95
static Size VARSIZE_ANY_EXHDR(const void *PTR)
Definition: varatt.h:472
static char * VARDATA_ANY(const void *PTR)
Definition: varatt.h:486

References appendBinaryStringInfo(), appendStringInfoChar(), appendStringInfoString(), array_to_json_internal(), Assert(), buf, check_stack_depth(), composite_to_json(), DatumGetBool(), DatumGetPointer(), DatumGetTextPP, ereport, errcode(), errmsg(), ERROR, escape_json(), escape_json_text(), JsonEncodeDateTime(), JSONTYPE_ARRAY, JSONTYPE_BOOL, JSONTYPE_CAST, JSONTYPE_COMPOSITE, JSONTYPE_DATE, JSONTYPE_JSON, JSONTYPE_NUMERIC, JSONTYPE_TIMESTAMP, JSONTYPE_TIMESTAMPTZ, MAXDATELEN, OidFunctionCall1, OidOutputFunctionCall(), pfree(), val, VARDATA_ANY(), and VARSIZE_ANY_EXHDR().

Referenced by add_json(), array_dim_to_json(), composite_to_json(), datum_to_json(), json_agg_transfn_worker(), and json_object_agg_transfn_worker().

◆ escape_json()

static void escape_json ( StringInfo  buf,
const char *  str 
)

◆ escape_json_char()

static pg_attribute_always_inline void escape_json_char ( StringInfo  buf,
char  c 
)
static

Definition at line 1564 of file json.c.

1565{
1566 switch (c)
1567 {
1568 case '\b':
1570 break;
1571 case '\f':
1573 break;
1574 case '\n':
1576 break;
1577 case '\r':
1579 break;
1580 case '\t':
1582 break;
1583 case '"':
1584 appendStringInfoString(buf, "\\\"");
1585 break;
1586 case '\\':
1587 appendStringInfoString(buf, "\\\\");
1588 break;
1589 default:
1590 if ((unsigned char) c < ' ')
1591 appendStringInfo(buf, "\\u%04x", (int) c);
1592 else
1594 break;
1595 }
1596}
char * c
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:145

References appendStringInfo(), appendStringInfoCharMacro, appendStringInfoString(), and buf.

Referenced by escape_json(), and escape_json_with_len().

◆ escape_json_text()

void escape_json_text ( StringInfo  buf,
const text txt 
)

Definition at line 1738 of file json.c.

1739{
1740 /* must cast away the const, unfortunately */
1741 text *tunpacked = pg_detoast_datum_packed(unconstify(text *, txt));
1742 int len = VARSIZE_ANY_EXHDR(tunpacked);
1743 char *str;
1744
1745 str = VARDATA_ANY(tunpacked);
1746
1748
1749 /* pfree any detoasted values */
1750 if (tunpacked != txt)
1751 pfree(tunpacked);
1752}
#define unconstify(underlying_type, expr)
Definition: c.h:1245
struct varlena * pg_detoast_datum_packed(struct varlena *datum)
Definition: fmgr.c:1829
void escape_json_with_len(StringInfo buf, const char *str, int len)
Definition: json.c:1633
const void size_t len

References buf, escape_json_with_len(), len, pfree(), pg_detoast_datum_packed(), str, unconstify, VARDATA_ANY(), and VARSIZE_ANY_EXHDR().

Referenced by datum_to_json_internal(), json_object(), json_object_two_arg(), and transform_string_values_scalar().

◆ escape_json_with_len()

void escape_json_with_len ( StringInfo  buf,
const char *  str,
int  len 
)

Definition at line 1633 of file json.c.

1634{
1635 int vlen;
1636
1637 Assert(len >= 0);
1638
1639 /*
1640 * Since we know the minimum length we'll need to append, let's just
1641 * enlarge the buffer now rather than incrementally making more space when
1642 * we run out. Add two extra bytes for the enclosing quotes.
1643 */
1645
1646 /*
1647 * Figure out how many bytes to process using SIMD. Round 'len' down to
1648 * the previous multiple of sizeof(Vector8), assuming that's a power-of-2.
1649 */
1650 vlen = len & (int) (~(sizeof(Vector8) - 1));
1651
1653
1654 for (int i = 0, copypos = 0;;)
1655 {
1656 /*
1657 * To speed this up, try searching sizeof(Vector8) bytes at once for
1658 * special characters that we need to escape. When we find one, we
1659 * fall out of the Vector8 loop and copy the portion we've vector
1660 * searched and then we process sizeof(Vector8) bytes one byte at a
1661 * time. Once done, come back and try doing vector searching again.
1662 * We'll also process any remaining bytes at the tail end of the
1663 * string byte-by-byte. This optimization assumes that most chunks of
1664 * sizeof(Vector8) bytes won't contain any special characters.
1665 */
1666 for (; i < vlen; i += sizeof(Vector8))
1667 {
1668 Vector8 chunk;
1669
1670 vector8_load(&chunk, (const uint8 *) &str[i]);
1671
1672 /*
1673 * Break on anything less than ' ' or if we find a '"' or '\\'.
1674 * Those need special handling. That's done in the per-byte loop.
1675 */
1676 if (vector8_has_le(chunk, (unsigned char) 0x1F) ||
1677 vector8_has(chunk, (unsigned char) '"') ||
1678 vector8_has(chunk, (unsigned char) '\\'))
1679 break;
1680
1681#ifdef ESCAPE_JSON_FLUSH_AFTER
1682
1683 /*
1684 * Flush what's been checked so far out to the destination buffer
1685 * every so often to avoid having to re-read cachelines when
1686 * escaping large strings.
1687 */
1688 if (i - copypos >= ESCAPE_JSON_FLUSH_AFTER)
1689 {
1690 appendBinaryStringInfo(buf, &str[copypos], i - copypos);
1691 copypos = i;
1692 }
1693#endif
1694 }
1695
1696 /*
1697 * Write to the destination up to the point that we've vector searched
1698 * so far. Do this only when switching into per-byte mode rather than
1699 * once every sizeof(Vector8) bytes.
1700 */
1701 if (copypos < i)
1702 {
1703 appendBinaryStringInfo(buf, &str[copypos], i - copypos);
1704 copypos = i;
1705 }
1706
1707 /*
1708 * Per-byte loop for Vector8s containing special chars and for
1709 * processing the tail of the string.
1710 */
1711 for (int b = 0; b < sizeof(Vector8); b++)
1712 {
1713 /* check if we've finished */
1714 if (i == len)
1715 goto done;
1716
1717 Assert(i < len);
1718
1720 }
1721
1722 copypos = i;
1723 /* We're not done yet. Try the vector search again. */
1724 }
1725
1726done:
1728}
uint8_t uint8
Definition: c.h:541
int b
Definition: isn.c:74
#define ESCAPE_JSON_FLUSH_AFTER
Definition: json.c:1624
static bool vector8_has_le(const Vector8 v, const uint8 c)
Definition: simd.h:227
static void vector8_load(Vector8 *v, const uint8 *s)
Definition: simd.h:107
uint64 Vector8
Definition: simd.h:60
static bool vector8_has(const Vector8 v, const uint8 c)
Definition: simd.h:176
void enlargeStringInfo(StringInfo str, int needed)
Definition: stringinfo.c:337

References appendBinaryStringInfo(), appendStringInfoCharMacro, Assert(), b, buf, enlargeStringInfo(), escape_json_char(), ESCAPE_JSON_FLUSH_AFTER, i, len, str, vector8_has(), vector8_has_le(), and vector8_load().

Referenced by AddFileToBackupManifest(), escape_json_text(), hstore_to_json(), hstore_to_json_loose(), jsonb_put_escaped_value(), populate_scalar(), and printJsonPathItem().

◆ json_agg_finalfn()

Datum json_agg_finalfn ( PG_FUNCTION_ARGS  )

Definition at line 881 of file json.c.

882{
884
885 /* cannot be called directly because of internal-type argument */
886 Assert(AggCheckCallContext(fcinfo, NULL));
887
888 state = PG_ARGISNULL(0) ?
889 NULL :
891
892 /* NULL result for no rows in, as is standard with aggregates */
893 if (state == NULL)
895
896 /* Else return state with appropriate array terminator added */
898}
#define PG_GETARG_POINTER(n)
Definition: fmgr.h:276
#define PG_ARGISNULL(n)
Definition: fmgr.h:209
#define PG_RETURN_NULL()
Definition: fmgr.h:345
static text * catenate_stringinfo_string(StringInfo buffer, const char *addon)
Definition: json.c:1211
int AggCheckCallContext(FunctionCallInfo fcinfo, MemoryContext *aggcontext)
Definition: nodeAgg.c:4613
Definition: regguts.h:323

References AggCheckCallContext(), Assert(), catenate_stringinfo_string(), PG_ARGISNULL, PG_GETARG_POINTER, PG_RETURN_NULL, and PG_RETURN_TEXT_P.

◆ json_agg_strict_transfn()

Datum json_agg_strict_transfn ( PG_FUNCTION_ARGS  )

Definition at line 872 of file json.c.

873{
874 return json_agg_transfn_worker(fcinfo, true);
875}
static Datum json_agg_transfn_worker(FunctionCallInfo fcinfo, bool absent_on_null)
Definition: json.c:781

References json_agg_transfn_worker().

◆ json_agg_transfn()

Datum json_agg_transfn ( PG_FUNCTION_ARGS  )

Definition at line 863 of file json.c.

864{
865 return json_agg_transfn_worker(fcinfo, false);
866}

References json_agg_transfn_worker().

◆ json_agg_transfn_worker()

static Datum json_agg_transfn_worker ( FunctionCallInfo  fcinfo,
bool  absent_on_null 
)
static

Definition at line 781 of file json.c.

782{
783 MemoryContext aggcontext,
784 oldcontext;
786 Datum val;
787
788 if (!AggCheckCallContext(fcinfo, &aggcontext))
789 {
790 /* cannot be called directly because of internal-type argument */
791 elog(ERROR, "json_agg_transfn called in non-aggregate context");
792 }
793
794 if (PG_ARGISNULL(0))
795 {
796 Oid arg_type = get_fn_expr_argtype(fcinfo->flinfo, 1);
797
798 if (arg_type == InvalidOid)
800 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
801 errmsg("could not determine input data type")));
802
803 /*
804 * Make this state object in a context where it will persist for the
805 * duration of the aggregate call. MemoryContextSwitchTo is only
806 * needed the first time, as the StringInfo routines make sure they
807 * use the right context to enlarge the object if necessary.
808 */
809 oldcontext = MemoryContextSwitchTo(aggcontext);
810 state = (JsonAggState *) palloc(sizeof(JsonAggState));
811 state->str = makeStringInfo();
812 MemoryContextSwitchTo(oldcontext);
813
814 appendStringInfoChar(state->str, '[');
815 json_categorize_type(arg_type, false, &state->val_category,
816 &state->val_output_func);
817 }
818 else
819 {
821 }
822
823 if (absent_on_null && PG_ARGISNULL(1))
825
826 if (state->str->len > 1)
827 appendStringInfoString(state->str, ", ");
828
829 /* fast path for NULLs */
830 if (PG_ARGISNULL(1))
831 {
833 InvalidOid, false);
835 }
836
837 val = PG_GETARG_DATUM(1);
838
839 /* add some whitespace if structured type and not first item */
840 if (!PG_ARGISNULL(0) && state->str->len > 1 &&
841 (state->val_category == JSONTYPE_ARRAY ||
842 state->val_category == JSONTYPE_COMPOSITE))
843 {
844 appendStringInfoString(state->str, "\n ");
845 }
846
847 datum_to_json_internal(val, false, state->str, state->val_category,
848 state->val_output_func, false);
849
850 /*
851 * The transition type for json_agg() is declared to be "internal", which
852 * is a pass-by-value type the same size as a pointer. So we can safely
853 * pass the JsonAggState pointer through nodeAgg.c's machinations.
854 */
856}
#define elog(elevel,...)
Definition: elog.h:226
Oid get_fn_expr_argtype(FmgrInfo *flinfo, int argnum)
Definition: fmgr.c:1875
#define PG_RETURN_POINTER(x)
Definition: fmgr.h:361
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:124
StringInfo makeStringInfo(void)
Definition: stringinfo.c:72
FmgrInfo * flinfo
Definition: fmgr.h:87

References AggCheckCallContext(), appendStringInfoChar(), appendStringInfoString(), datum_to_json_internal(), elog, ereport, errcode(), errmsg(), ERROR, FunctionCallInfoBaseData::flinfo, get_fn_expr_argtype(), InvalidOid, json_categorize_type(), JSONTYPE_ARRAY, JSONTYPE_COMPOSITE, JSONTYPE_NULL, makeStringInfo(), MemoryContextSwitchTo(), palloc(), PG_ARGISNULL, PG_GETARG_DATUM, PG_GETARG_POINTER, PG_RETURN_POINTER, and val.

Referenced by json_agg_strict_transfn(), and json_agg_transfn().

◆ json_build_array()

Datum json_build_array ( PG_FUNCTION_ARGS  )

Definition at line 1376 of file json.c.

1377{
1378 Datum *args;
1379 bool *nulls;
1380 Oid *types;
1381
1382 /* build argument values to build the object */
1383 int nargs = extract_variadic_args(fcinfo, 0, true,
1384 &args, &types, &nulls);
1385
1386 if (nargs < 0)
1388
1389 PG_RETURN_DATUM(json_build_array_worker(nargs, args, nulls, types, false));
1390}
struct typedefs * types
Definition: ecpg.c:30
#define PG_RETURN_DATUM(x)
Definition: fmgr.h:353
int extract_variadic_args(FunctionCallInfo fcinfo, int variadic_start, bool convert_unknown, Datum **args, Oid **types, bool **nulls)
Definition: funcapi.c:2005
Datum json_build_array_worker(int nargs, const Datum *args, const bool *nulls, const Oid *types, bool absent_on_null)
Definition: json.c:1346

References generate_unaccent_rules::args, extract_variadic_args(), json_build_array_worker(), PG_RETURN_DATUM, PG_RETURN_NULL, and types.

◆ json_build_array_noargs()

Datum json_build_array_noargs ( PG_FUNCTION_ARGS  )

Definition at line 1396 of file json.c.

1397{
1399}

References cstring_to_text_with_len(), and PG_RETURN_TEXT_P.

◆ json_build_array_worker()

Datum json_build_array_worker ( int  nargs,
const Datum args,
const bool *  nulls,
const Oid types,
bool  absent_on_null 
)

Definition at line 1346 of file json.c.

1348{
1349 int i;
1350 const char *sep = "";
1351 StringInfoData result;
1352
1353 initStringInfo(&result);
1354
1355 appendStringInfoChar(&result, '[');
1356
1357 for (i = 0; i < nargs; i++)
1358 {
1359 if (absent_on_null && nulls[i])
1360 continue;
1361
1362 appendStringInfoString(&result, sep);
1363 sep = ", ";
1364 add_json(args[i], nulls[i], &result, types[i], false);
1365 }
1366
1367 appendStringInfoChar(&result, ']');
1368
1369 return PointerGetDatum(cstring_to_text_with_len(result.data, result.len));
1370}
static void add_json(Datum val, bool is_null, StringInfo result, Oid val_type, bool key_scalar)
Definition: json.c:603

References add_json(), appendStringInfoChar(), appendStringInfoString(), generate_unaccent_rules::args, cstring_to_text_with_len(), StringInfoData::data, i, initStringInfo(), StringInfoData::len, PointerGetDatum(), and types.

Referenced by ExecEvalJsonConstructor(), and json_build_array().

◆ json_build_object()

Datum json_build_object ( PG_FUNCTION_ARGS  )

Definition at line 1320 of file json.c.

1321{
1322 Datum *args;
1323 bool *nulls;
1324 Oid *types;
1325
1326 /* build argument values to build the object */
1327 int nargs = extract_variadic_args(fcinfo, 0, true,
1328 &args, &types, &nulls);
1329
1330 if (nargs < 0)
1332
1333 PG_RETURN_DATUM(json_build_object_worker(nargs, args, nulls, types, false, false));
1334}
Datum json_build_object_worker(int nargs, const Datum *args, const bool *nulls, const Oid *types, bool absent_on_null, bool unique_keys)
Definition: json.c:1226

References generate_unaccent_rules::args, extract_variadic_args(), json_build_object_worker(), PG_RETURN_DATUM, PG_RETURN_NULL, and types.

◆ json_build_object_noargs()

Datum json_build_object_noargs ( PG_FUNCTION_ARGS  )

Definition at line 1340 of file json.c.

1341{
1343}

References cstring_to_text_with_len(), and PG_RETURN_TEXT_P.

◆ json_build_object_worker()

Datum json_build_object_worker ( int  nargs,
const Datum args,
const bool *  nulls,
const Oid types,
bool  absent_on_null,
bool  unique_keys 
)

Definition at line 1226 of file json.c.

1228{
1229 int i;
1230 const char *sep = "";
1231 StringInfo result;
1232 JsonUniqueBuilderState unique_check;
1233
1234 if (nargs % 2 != 0)
1235 ereport(ERROR,
1236 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1237 errmsg("argument list must have even number of elements"),
1238 /* translator: %s is a SQL function name */
1239 errhint("The arguments of %s must consist of alternating keys and values.",
1240 "json_build_object()")));
1241
1242 result = makeStringInfo();
1243
1244 appendStringInfoChar(result, '{');
1245
1246 if (unique_keys)
1247 json_unique_builder_init(&unique_check);
1248
1249 for (i = 0; i < nargs; i += 2)
1250 {
1251 StringInfo out;
1252 bool skip;
1253 int key_offset;
1254
1255 /* Skip null values if absent_on_null */
1256 skip = absent_on_null && nulls[i + 1];
1257
1258 if (skip)
1259 {
1260 /* If key uniqueness check is needed we must save skipped keys */
1261 if (!unique_keys)
1262 continue;
1263
1264 out = json_unique_builder_get_throwawaybuf(&unique_check);
1265 }
1266 else
1267 {
1268 appendStringInfoString(result, sep);
1269 sep = ", ";
1270 out = result;
1271 }
1272
1273 /* process key */
1274 if (nulls[i])
1275 ereport(ERROR,
1276 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1277 errmsg("null value not allowed for object key")));
1278
1279 /* save key offset before appending it */
1280 key_offset = out->len;
1281
1282 add_json(args[i], false, out, types[i], true);
1283
1284 if (unique_keys)
1285 {
1286 /*
1287 * check key uniqueness after key appending
1288 *
1289 * Copy the key first, instead of pointing into the buffer. It
1290 * will be added to the hash table, but the buffer may get
1291 * reallocated as we're appending more data to it. That would
1292 * invalidate pointers to keys in the current buffer.
1293 */
1294 const char *key = pstrdup(&out->data[key_offset]);
1295
1296 if (!json_unique_check_key(&unique_check.check, key, 0))
1297 ereport(ERROR,
1298 errcode(ERRCODE_DUPLICATE_JSON_OBJECT_KEY_VALUE),
1299 errmsg("duplicate JSON object key value: %s", key));
1300
1301 if (skip)
1302 continue;
1303 }
1304
1305 appendStringInfoString(result, " : ");
1306
1307 /* process value */
1308 add_json(args[i + 1], nulls[i + 1], result, types[i + 1], false);
1309 }
1310
1311 appendStringInfoChar(result, '}');
1312
1313 return PointerGetDatum(cstring_to_text_with_len(result->data, result->len));
1314}
int errhint(const char *fmt,...)
Definition: elog.c:1330
static StringInfo json_unique_builder_get_throwawaybuf(JsonUniqueBuilderState *cxt)
Definition: json.c:980
static bool json_unique_check_key(JsonUniqueCheckState *cxt, const char *key, int object_id)
Definition: json.c:960
static void json_unique_builder_init(JsonUniqueBuilderState *cxt)
Definition: json.c:952
char * pstrdup(const char *in)
Definition: mcxt.c:1759
static const struct exclude_list_item skip[]
Definition: pg_checksums.c:108
JsonUniqueCheckState check
Definition: json.c:72

References add_json(), appendStringInfoChar(), appendStringInfoString(), generate_unaccent_rules::args, JsonUniqueBuilderState::check, cstring_to_text_with_len(), StringInfoData::data, ereport, errcode(), errhint(), errmsg(), ERROR, i, json_unique_builder_get_throwawaybuf(), json_unique_builder_init(), json_unique_check_key(), sort-test::key, StringInfoData::len, makeStringInfo(), PointerGetDatum(), pstrdup(), skip, and types.

Referenced by ExecEvalJsonConstructor(), and json_build_object().

◆ json_in()

Datum json_in ( PG_FUNCTION_ARGS  )

Definition at line 108 of file json.c.

109{
110 char *json = PG_GETARG_CSTRING(0);
111 text *result = cstring_to_text(json);
112 JsonLexContext lex;
113
114 /* validate it */
115 makeJsonLexContext(&lex, result, false);
116 if (!pg_parse_json_or_errsave(&lex, &nullSemAction, fcinfo->context))
118
119 /* Internal representation is the same as text */
120 PG_RETURN_TEXT_P(result);
121}
#define PG_GETARG_CSTRING(n)
Definition: fmgr.h:277
const JsonSemAction nullSemAction
Definition: jsonapi.c:287
JsonLexContext * makeJsonLexContext(JsonLexContext *lex, text *json, bool need_escapes)
Definition: jsonfuncs.c:540
bool pg_parse_json_or_errsave(JsonLexContext *lex, const JsonSemAction *sem, Node *escontext)
Definition: jsonfuncs.c:519
text * cstring_to_text(const char *s)
Definition: varlena.c:181

References cstring_to_text(), makeJsonLexContext(), nullSemAction, PG_GETARG_CSTRING, pg_parse_json_or_errsave(), PG_RETURN_NULL, and PG_RETURN_TEXT_P.

◆ json_object()

Datum json_object ( PG_FUNCTION_ARGS  )

Definition at line 1408 of file json.c.

1409{
1410 ArrayType *in_array = PG_GETARG_ARRAYTYPE_P(0);
1411 int ndims = ARR_NDIM(in_array);
1412 StringInfoData result;
1413 Datum *in_datums;
1414 bool *in_nulls;
1415 int in_count,
1416 count,
1417 i;
1418 text *rval;
1419
1420 switch (ndims)
1421 {
1422 case 0:
1424 break;
1425
1426 case 1:
1427 if ((ARR_DIMS(in_array)[0]) % 2)
1428 ereport(ERROR,
1429 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1430 errmsg("array must have even number of elements")));
1431 break;
1432
1433 case 2:
1434 if ((ARR_DIMS(in_array)[1]) != 2)
1435 ereport(ERROR,
1436 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1437 errmsg("array must have two columns")));
1438 break;
1439
1440 default:
1441 ereport(ERROR,
1442 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1443 errmsg("wrong number of array subscripts")));
1444 }
1445
1446 deconstruct_array_builtin(in_array, TEXTOID, &in_datums, &in_nulls, &in_count);
1447
1448 count = in_count / 2;
1449
1450 initStringInfo(&result);
1451
1452 appendStringInfoChar(&result, '{');
1453
1454 for (i = 0; i < count; ++i)
1455 {
1456 if (in_nulls[i * 2])
1457 ereport(ERROR,
1458 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1459 errmsg("null value not allowed for object key")));
1460
1461 if (i > 0)
1462 appendStringInfoString(&result, ", ");
1463 escape_json_text(&result, (text *) DatumGetPointer(in_datums[i * 2]));
1464 appendStringInfoString(&result, " : ");
1465 if (in_nulls[i * 2 + 1])
1466 appendStringInfoString(&result, "null");
1467 else
1468 {
1469 escape_json_text(&result,
1470 (text *) DatumGetPointer(in_datums[i * 2 + 1]));
1471 }
1472 }
1473
1474 appendStringInfoChar(&result, '}');
1475
1476 pfree(in_datums);
1477 pfree(in_nulls);
1478
1479 rval = cstring_to_text_with_len(result.data, result.len);
1480 pfree(result.data);
1481
1482 PG_RETURN_TEXT_P(rval);
1483}
#define PG_GETARG_ARRAYTYPE_P(n)
Definition: array.h:263
void deconstruct_array_builtin(const ArrayType *array, Oid elmtype, Datum **elemsp, bool **nullsp, int *nelemsp)
Definition: arrayfuncs.c:3698
#define CStringGetTextDatum(s)
Definition: builtins.h:97

References appendStringInfoChar(), appendStringInfoString(), ARR_DIMS, ARR_NDIM, cstring_to_text_with_len(), CStringGetTextDatum, StringInfoData::data, DatumGetPointer(), deconstruct_array_builtin(), ereport, errcode(), errmsg(), ERROR, escape_json_text(), i, initStringInfo(), StringInfoData::len, pfree(), PG_GETARG_ARRAYTYPE_P, PG_RETURN_DATUM, and PG_RETURN_TEXT_P.

◆ json_object_agg_finalfn()

Datum json_object_agg_finalfn ( PG_FUNCTION_ARGS  )

Definition at line 1188 of file json.c.

1189{
1191
1192 /* cannot be called directly because of internal-type argument */
1193 Assert(AggCheckCallContext(fcinfo, NULL));
1194
1195 state = PG_ARGISNULL(0) ? NULL : (JsonAggState *) PG_GETARG_POINTER(0);
1196
1197 /* NULL result for no rows in, as is standard with aggregates */
1198 if (state == NULL)
1200
1201 /* Else return state with appropriate object terminator added */
1203}

References AggCheckCallContext(), Assert(), catenate_stringinfo_string(), PG_ARGISNULL, PG_GETARG_POINTER, PG_RETURN_NULL, and PG_RETURN_TEXT_P.

◆ json_object_agg_strict_transfn()

Datum json_object_agg_strict_transfn ( PG_FUNCTION_ARGS  )

Definition at line 1161 of file json.c.

1162{
1163 return json_object_agg_transfn_worker(fcinfo, true, false);
1164}
static Datum json_object_agg_transfn_worker(FunctionCallInfo fcinfo, bool absent_on_null, bool unique_keys)
Definition: json.c:1004

References json_object_agg_transfn_worker().

◆ json_object_agg_transfn()

Datum json_object_agg_transfn ( PG_FUNCTION_ARGS  )

Definition at line 1152 of file json.c.

1153{
1154 return json_object_agg_transfn_worker(fcinfo, false, false);
1155}

References json_object_agg_transfn_worker().

◆ json_object_agg_transfn_worker()

static Datum json_object_agg_transfn_worker ( FunctionCallInfo  fcinfo,
bool  absent_on_null,
bool  unique_keys 
)
static

Definition at line 1004 of file json.c.

1006{
1007 MemoryContext aggcontext,
1008 oldcontext;
1010 StringInfo out;
1011 Datum arg;
1012 bool skip;
1013 int key_offset;
1014
1015 if (!AggCheckCallContext(fcinfo, &aggcontext))
1016 {
1017 /* cannot be called directly because of internal-type argument */
1018 elog(ERROR, "json_object_agg_transfn called in non-aggregate context");
1019 }
1020
1021 if (PG_ARGISNULL(0))
1022 {
1023 Oid arg_type;
1024
1025 /*
1026 * Make the StringInfo in a context where it will persist for the
1027 * duration of the aggregate call. Switching context is only needed
1028 * for this initial step, as the StringInfo and dynahash routines make
1029 * sure they use the right context to enlarge the object if necessary.
1030 */
1031 oldcontext = MemoryContextSwitchTo(aggcontext);
1032 state = (JsonAggState *) palloc(sizeof(JsonAggState));
1033 state->str = makeStringInfo();
1034 if (unique_keys)
1035 json_unique_builder_init(&state->unique_check);
1036 else
1037 memset(&state->unique_check, 0, sizeof(state->unique_check));
1038 MemoryContextSwitchTo(oldcontext);
1039
1040 arg_type = get_fn_expr_argtype(fcinfo->flinfo, 1);
1041
1042 if (arg_type == InvalidOid)
1043 ereport(ERROR,
1044 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1045 errmsg("could not determine data type for argument %d", 1)));
1046
1047 json_categorize_type(arg_type, false, &state->key_category,
1048 &state->key_output_func);
1049
1050 arg_type = get_fn_expr_argtype(fcinfo->flinfo, 2);
1051
1052 if (arg_type == InvalidOid)
1053 ereport(ERROR,
1054 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1055 errmsg("could not determine data type for argument %d", 2)));
1056
1057 json_categorize_type(arg_type, false, &state->val_category,
1058 &state->val_output_func);
1059
1060 appendStringInfoString(state->str, "{ ");
1061 }
1062 else
1063 {
1065 }
1066
1067 /*
1068 * Note: since json_object_agg() is declared as taking type "any", the
1069 * parser will not do any type conversion on unknown-type literals (that
1070 * is, undecorated strings or NULLs). Such values will arrive here as
1071 * type UNKNOWN, which fortunately does not matter to us, since
1072 * unknownout() works fine.
1073 */
1074
1075 if (PG_ARGISNULL(1))
1076 ereport(ERROR,
1077 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1078 errmsg("null value not allowed for object key")));
1079
1080 /* Skip null values if absent_on_null */
1081 skip = absent_on_null && PG_ARGISNULL(2);
1082
1083 if (skip)
1084 {
1085 /*
1086 * We got a NULL value and we're not storing those; if we're not
1087 * testing key uniqueness, we're done. If we are, use the throwaway
1088 * buffer to store the key name so that we can check it.
1089 */
1090 if (!unique_keys)
1092
1093 out = json_unique_builder_get_throwawaybuf(&state->unique_check);
1094 }
1095 else
1096 {
1097 out = state->str;
1098
1099 /*
1100 * Append comma delimiter only if we have already output some fields
1101 * after the initial string "{ ".
1102 */
1103 if (out->len > 2)
1104 appendStringInfoString(out, ", ");
1105 }
1106
1107 arg = PG_GETARG_DATUM(1);
1108
1109 key_offset = out->len;
1110
1111 datum_to_json_internal(arg, false, out, state->key_category,
1112 state->key_output_func, true);
1113
1114 if (unique_keys)
1115 {
1116 /*
1117 * Copy the key first, instead of pointing into the buffer. It will be
1118 * added to the hash table, but the buffer may get reallocated as
1119 * we're appending more data to it. That would invalidate pointers to
1120 * keys in the current buffer.
1121 */
1122 const char *key = MemoryContextStrdup(aggcontext,
1123 &out->data[key_offset]);
1124
1125 if (!json_unique_check_key(&state->unique_check.check, key, 0))
1126 ereport(ERROR,
1127 errcode(ERRCODE_DUPLICATE_JSON_OBJECT_KEY_VALUE),
1128 errmsg("duplicate JSON object key value: %s", key));
1129
1130 if (skip)
1132 }
1133
1134 appendStringInfoString(state->str, " : ");
1135
1136 if (PG_ARGISNULL(2))
1137 arg = (Datum) 0;
1138 else
1139 arg = PG_GETARG_DATUM(2);
1140
1142 state->val_category,
1143 state->val_output_func, false);
1144
1146}
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1746
void * arg

References AggCheckCallContext(), appendStringInfoString(), arg, StringInfoData::data, datum_to_json_internal(), elog, ereport, errcode(), errmsg(), ERROR, FunctionCallInfoBaseData::flinfo, get_fn_expr_argtype(), InvalidOid, json_categorize_type(), json_unique_builder_get_throwawaybuf(), json_unique_builder_init(), json_unique_check_key(), sort-test::key, StringInfoData::len, makeStringInfo(), MemoryContextStrdup(), MemoryContextSwitchTo(), palloc(), PG_ARGISNULL, PG_GETARG_DATUM, PG_GETARG_POINTER, PG_RETURN_POINTER, and skip.

Referenced by json_object_agg_strict_transfn(), json_object_agg_transfn(), json_object_agg_unique_strict_transfn(), and json_object_agg_unique_transfn().

◆ json_object_agg_unique_strict_transfn()

Datum json_object_agg_unique_strict_transfn ( PG_FUNCTION_ARGS  )

Definition at line 1179 of file json.c.

1180{
1181 return json_object_agg_transfn_worker(fcinfo, true, true);
1182}

References json_object_agg_transfn_worker().

◆ json_object_agg_unique_transfn()

Datum json_object_agg_unique_transfn ( PG_FUNCTION_ARGS  )

Definition at line 1170 of file json.c.

1171{
1172 return json_object_agg_transfn_worker(fcinfo, false, true);
1173}

References json_object_agg_transfn_worker().

◆ json_object_two_arg()

Datum json_object_two_arg ( PG_FUNCTION_ARGS  )

Definition at line 1492 of file json.c.

1493{
1494 ArrayType *key_array = PG_GETARG_ARRAYTYPE_P(0);
1495 ArrayType *val_array = PG_GETARG_ARRAYTYPE_P(1);
1496 int nkdims = ARR_NDIM(key_array);
1497 int nvdims = ARR_NDIM(val_array);
1498 StringInfoData result;
1499 Datum *key_datums,
1500 *val_datums;
1501 bool *key_nulls,
1502 *val_nulls;
1503 int key_count,
1504 val_count,
1505 i;
1506 text *rval;
1507
1508 if (nkdims > 1 || nkdims != nvdims)
1509 ereport(ERROR,
1510 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1511 errmsg("wrong number of array subscripts")));
1512
1513 if (nkdims == 0)
1515
1516 deconstruct_array_builtin(key_array, TEXTOID, &key_datums, &key_nulls, &key_count);
1517 deconstruct_array_builtin(val_array, TEXTOID, &val_datums, &val_nulls, &val_count);
1518
1519 if (key_count != val_count)
1520 ereport(ERROR,
1521 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1522 errmsg("mismatched array dimensions")));
1523
1524 initStringInfo(&result);
1525
1526 appendStringInfoChar(&result, '{');
1527
1528 for (i = 0; i < key_count; ++i)
1529 {
1530 if (key_nulls[i])
1531 ereport(ERROR,
1532 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1533 errmsg("null value not allowed for object key")));
1534
1535 if (i > 0)
1536 appendStringInfoString(&result, ", ");
1537 escape_json_text(&result, (text *) DatumGetPointer(key_datums[i]));
1538 appendStringInfoString(&result, " : ");
1539 if (val_nulls[i])
1540 appendStringInfoString(&result, "null");
1541 else
1542 escape_json_text(&result,
1543 (text *) DatumGetPointer(val_datums[i]));
1544 }
1545
1546 appendStringInfoChar(&result, '}');
1547
1548 pfree(key_datums);
1549 pfree(key_nulls);
1550 pfree(val_datums);
1551 pfree(val_nulls);
1552
1553 rval = cstring_to_text_with_len(result.data, result.len);
1554 pfree(result.data);
1555
1556 PG_RETURN_TEXT_P(rval);
1557}

References appendStringInfoChar(), appendStringInfoString(), ARR_NDIM, cstring_to_text_with_len(), CStringGetTextDatum, StringInfoData::data, DatumGetPointer(), deconstruct_array_builtin(), ereport, errcode(), errmsg(), ERROR, escape_json_text(), i, initStringInfo(), StringInfoData::len, pfree(), PG_GETARG_ARRAYTYPE_P, PG_RETURN_DATUM, and PG_RETURN_TEXT_P.

◆ json_out()

Datum json_out ( PG_FUNCTION_ARGS  )

Definition at line 127 of file json.c.

128{
129 /* we needn't detoast because text_to_cstring will handle that */
130 Datum txt = PG_GETARG_DATUM(0);
131
133}
#define TextDatumGetCString(d)
Definition: builtins.h:98
#define PG_RETURN_CSTRING(x)
Definition: fmgr.h:362

References PG_GETARG_DATUM, PG_RETURN_CSTRING, and TextDatumGetCString.

◆ json_recv()

Datum json_recv ( PG_FUNCTION_ARGS  )

Definition at line 153 of file json.c.

154{
156 char *str;
157 int nbytes;
158 JsonLexContext lex;
159
160 str = pq_getmsgtext(buf, buf->len - buf->cursor, &nbytes);
161
162 /* Validate it. */
164 false);
166
168}
JsonLexContext * makeJsonLexContextCstringLen(JsonLexContext *lex, const char *json, size_t len, int encoding, bool need_escapes)
Definition: jsonapi.c:392
#define pg_parse_json_or_ereport(lex, sem)
Definition: jsonfuncs.h:47
int GetDatabaseEncoding(void)
Definition: mbutils.c:1262
char * pq_getmsgtext(StringInfo msg, int rawbytes, int *nbytes)
Definition: pqformat.c:546
struct StringInfoData * StringInfo
Definition: string.h:15

References buf, cstring_to_text_with_len(), GetDatabaseEncoding(), makeJsonLexContextCstringLen(), nullSemAction, PG_GETARG_POINTER, pg_parse_json_or_ereport, PG_RETURN_TEXT_P, pq_getmsgtext(), and str.

◆ json_send()

Datum json_send ( PG_FUNCTION_ARGS  )

Definition at line 139 of file json.c.

140{
141 text *t = PG_GETARG_TEXT_PP(0);
143
147}
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:309
#define PG_RETURN_BYTEA_P(x)
Definition: fmgr.h:371
void pq_sendtext(StringInfo buf, const char *str, int slen)
Definition: pqformat.c:172
void pq_begintypsend(StringInfo buf)
Definition: pqformat.c:326
bytea * pq_endtypsend(StringInfo buf)
Definition: pqformat.c:346

References buf, PG_GETARG_TEXT_PP, PG_RETURN_BYTEA_P, pq_begintypsend(), pq_endtypsend(), pq_sendtext(), VARDATA_ANY(), and VARSIZE_ANY_EXHDR().

◆ json_typeof()

Datum json_typeof ( PG_FUNCTION_ARGS  )

Definition at line 1876 of file json.c.

1877{
1878 text *json = PG_GETARG_TEXT_PP(0);
1879 JsonLexContext lex;
1880 char *type;
1881 JsonParseErrorType result;
1882
1883 /* Lex exactly one token from the input and check its type. */
1884 makeJsonLexContext(&lex, json, false);
1885 result = json_lex(&lex);
1886 if (result != JSON_SUCCESS)
1887 json_errsave_error(result, &lex, NULL);
1888
1889 switch (lex.token_type)
1890 {
1892 type = "object";
1893 break;
1895 type = "array";
1896 break;
1897 case JSON_TOKEN_STRING:
1898 type = "string";
1899 break;
1900 case JSON_TOKEN_NUMBER:
1901 type = "number";
1902 break;
1903 case JSON_TOKEN_TRUE:
1904 case JSON_TOKEN_FALSE:
1905 type = "boolean";
1906 break;
1907 case JSON_TOKEN_NULL:
1908 type = "null";
1909 break;
1910 default:
1911 elog(ERROR, "unexpected json token: %d", lex.token_type);
1912 }
1913
1915}
JsonParseErrorType json_lex(JsonLexContext *lex)
Definition: jsonapi.c:1588
JsonParseErrorType
Definition: jsonapi.h:35
@ JSON_SUCCESS
Definition: jsonapi.h:36
@ JSON_TOKEN_FALSE
Definition: jsonapi.h:29
@ JSON_TOKEN_TRUE
Definition: jsonapi.h:28
@ JSON_TOKEN_NULL
Definition: jsonapi.h:30
@ JSON_TOKEN_OBJECT_START
Definition: jsonapi.h:22
@ JSON_TOKEN_NUMBER
Definition: jsonapi.h:21
@ JSON_TOKEN_STRING
Definition: jsonapi.h:20
@ JSON_TOKEN_ARRAY_START
Definition: jsonapi.h:24
void json_errsave_error(JsonParseErrorType error, JsonLexContext *lex, Node *escontext)
Definition: jsonfuncs.c:641
JsonTokenType token_type
Definition: jsonapi.h:109
const char * type

References cstring_to_text(), elog, ERROR, json_errsave_error(), json_lex(), JSON_SUCCESS, JSON_TOKEN_ARRAY_START, JSON_TOKEN_FALSE, JSON_TOKEN_NULL, JSON_TOKEN_NUMBER, JSON_TOKEN_OBJECT_START, JSON_TOKEN_STRING, JSON_TOKEN_TRUE, makeJsonLexContext(), PG_GETARG_TEXT_PP, PG_RETURN_TEXT_P, JsonLexContext::token_type, and type.

◆ json_unique_builder_get_throwawaybuf()

static StringInfo json_unique_builder_get_throwawaybuf ( JsonUniqueBuilderState cxt)
static

Definition at line 980 of file json.c.

981{
982 StringInfo out = &cxt->skipped_keys;
983
984 if (!out->data)
985 {
987
988 initStringInfo(out);
989 MemoryContextSwitchTo(oldcxt);
990 }
991 else
992 /* Just reset the string to empty */
993 out->len = 0;
994
995 return out;
996}
StringInfoData skipped_keys
Definition: json.c:73
MemoryContext mcxt
Definition: json.c:74

References StringInfoData::data, initStringInfo(), StringInfoData::len, JsonUniqueBuilderState::mcxt, MemoryContextSwitchTo(), and JsonUniqueBuilderState::skipped_keys.

Referenced by json_build_object_worker(), and json_object_agg_transfn_worker().

◆ json_unique_builder_init()

static void json_unique_builder_init ( JsonUniqueBuilderState cxt)
static

Definition at line 952 of file json.c.

953{
956 cxt->skipped_keys.data = NULL;
957}
static void json_unique_check_init(JsonUniqueCheckState *cxt)
Definition: json.c:934
MemoryContext CurrentMemoryContext
Definition: mcxt.c:160

References JsonUniqueBuilderState::check, CurrentMemoryContext, StringInfoData::data, json_unique_check_init(), JsonUniqueBuilderState::mcxt, and JsonUniqueBuilderState::skipped_keys.

Referenced by json_build_object_worker(), and json_object_agg_transfn_worker().

◆ json_unique_check_init()

static void json_unique_check_init ( JsonUniqueCheckState cxt)
static

Definition at line 934 of file json.c.

935{
936 HASHCTL ctl;
937
938 memset(&ctl, 0, sizeof(ctl));
939 ctl.keysize = sizeof(JsonUniqueHashEntry);
940 ctl.entrysize = sizeof(JsonUniqueHashEntry);
942 ctl.hash = json_unique_hash;
944
945 *cxt = hash_create("json object hashtable",
946 32,
947 &ctl,
949}
HTAB * hash_create(const char *tabname, int64 nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:358
#define HASH_CONTEXT
Definition: hsearch.h:102
#define HASH_ELEM
Definition: hsearch.h:95
#define HASH_COMPARE
Definition: hsearch.h:99
#define HASH_FUNCTION
Definition: hsearch.h:98
static uint32 json_unique_hash(const void *key, Size keysize)
Definition: json.c:902
static int json_unique_hash_match(const void *key1, const void *key2, Size keysize)
Definition: json.c:913
struct JsonUniqueHashEntry JsonUniqueHashEntry
tree ctl
Definition: radixtree.h:1838

References ctl, CurrentMemoryContext, HASH_COMPARE, HASH_CONTEXT, hash_create(), HASH_ELEM, HASH_FUNCTION, json_unique_hash(), and json_unique_hash_match().

Referenced by json_unique_builder_init(), and json_validate().

◆ json_unique_check_key()

static bool json_unique_check_key ( JsonUniqueCheckState cxt,
const char *  key,
int  object_id 
)
static

Definition at line 960 of file json.c.

961{
963 bool found;
964
965 entry.key = key;
966 entry.key_len = strlen(key);
967 entry.object_id = object_id;
968
969 (void) hash_search(*cxt, &entry, HASH_ENTER, &found);
970
971 return !found;
972}
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:952
@ HASH_ENTER
Definition: hsearch.h:114
const char * key
Definition: json.c:47

References HASH_ENTER, hash_search(), JsonUniqueHashEntry::key, sort-test::key, JsonUniqueHashEntry::key_len, and JsonUniqueHashEntry::object_id.

Referenced by json_build_object_worker(), json_object_agg_transfn_worker(), and json_unique_object_field_start().

◆ json_unique_hash()

static uint32 json_unique_hash ( const void *  key,
Size  keysize 
)
static

Definition at line 902 of file json.c.

903{
906
907 hash ^= hash_bytes((const unsigned char *) entry->key, entry->key_len);
908
909 return hash;
910}
uint32_t uint32
Definition: c.h:543
uint32 hash_bytes_uint32(uint32 k)
Definition: hashfn.c:610
uint32 hash_bytes(const unsigned char *k, int keylen)
Definition: hashfn.c:146
static unsigned hash(unsigned *uv, int n)
Definition: rege_dfa.c:715

References hash(), hash_bytes(), hash_bytes_uint32(), JsonUniqueHashEntry::key, sort-test::key, JsonUniqueHashEntry::key_len, and JsonUniqueHashEntry::object_id.

Referenced by json_unique_check_init().

◆ json_unique_hash_match()

static int json_unique_hash_match ( const void *  key1,
const void *  key2,
Size  keysize 
)
static

Definition at line 913 of file json.c.

914{
915 const JsonUniqueHashEntry *entry1 = (const JsonUniqueHashEntry *) key1;
916 const JsonUniqueHashEntry *entry2 = (const JsonUniqueHashEntry *) key2;
917
918 if (entry1->object_id != entry2->object_id)
919 return entry1->object_id > entry2->object_id ? 1 : -1;
920
921 if (entry1->key_len != entry2->key_len)
922 return entry1->key_len > entry2->key_len ? 1 : -1;
923
924 return strncmp(entry1->key, entry2->key, entry1->key_len);
925}

References JsonUniqueHashEntry::key, JsonUniqueHashEntry::key_len, and JsonUniqueHashEntry::object_id.

Referenced by json_unique_check_init().

◆ json_unique_object_end()

static JsonParseErrorType json_unique_object_end ( void *  _state)
static

Definition at line 1774 of file json.c.

1775{
1776 JsonUniqueParsingState *state = _state;
1777 JsonUniqueStackEntry *entry;
1778
1779 if (!state->unique)
1780 return JSON_SUCCESS;
1781
1782 entry = state->stack;
1783 state->stack = entry->parent; /* pop object from stack */
1784 pfree(entry);
1785 return JSON_SUCCESS;
1786}
struct JsonUniqueStackEntry * parent
Definition: json.c:55

References JSON_SUCCESS, JsonUniqueStackEntry::parent, and pfree().

Referenced by json_validate().

◆ json_unique_object_field_start()

static JsonParseErrorType json_unique_object_field_start ( void *  _state,
char *  field,
bool  isnull 
)
static

Definition at line 1789 of file json.c.

1790{
1791 JsonUniqueParsingState *state = _state;
1792 JsonUniqueStackEntry *entry;
1793
1794 if (!state->unique)
1795 return JSON_SUCCESS;
1796
1797 /* find key collision in the current object */
1798 if (json_unique_check_key(&state->check, field, state->stack->object_id))
1799 return JSON_SUCCESS;
1800
1801 state->unique = false;
1802
1803 /* pop all objects entries */
1804 while ((entry = state->stack))
1805 {
1806 state->stack = entry->parent;
1807 pfree(entry);
1808 }
1809 return JSON_SUCCESS;
1810}

References JSON_SUCCESS, json_unique_check_key(), JsonUniqueStackEntry::parent, and pfree().

Referenced by json_validate().

◆ json_unique_object_start()

static JsonParseErrorType json_unique_object_start ( void *  _state)
static

Definition at line 1756 of file json.c.

1757{
1758 JsonUniqueParsingState *state = _state;
1759 JsonUniqueStackEntry *entry;
1760
1761 if (!state->unique)
1762 return JSON_SUCCESS;
1763
1764 /* push object entry to stack */
1765 entry = palloc(sizeof(*entry));
1766 entry->object_id = state->id_counter++;
1767 entry->parent = state->stack;
1768 state->stack = entry;
1769
1770 return JSON_SUCCESS;
1771}

References JSON_SUCCESS, JsonUniqueStackEntry::object_id, palloc(), and JsonUniqueStackEntry::parent.

Referenced by json_validate().

◆ json_validate()

bool json_validate ( text json,
bool  check_unique_keys,
bool  throw_error 
)

Definition at line 1814 of file json.c.

1815{
1816 JsonLexContext lex;
1817 JsonSemAction uniqueSemAction = {0};
1819 JsonParseErrorType result;
1820
1821 makeJsonLexContext(&lex, json, check_unique_keys);
1822
1823 if (check_unique_keys)
1824 {
1825 state.lex = &lex;
1826 state.stack = NULL;
1827 state.id_counter = 0;
1828 state.unique = true;
1830
1831 uniqueSemAction.semstate = &state;
1832 uniqueSemAction.object_start = json_unique_object_start;
1834 uniqueSemAction.object_end = json_unique_object_end;
1835 }
1836
1837 result = pg_parse_json(&lex, check_unique_keys ? &uniqueSemAction : &nullSemAction);
1838
1839 if (result != JSON_SUCCESS)
1840 {
1841 if (throw_error)
1842 json_errsave_error(result, &lex, NULL);
1843
1844 return false; /* invalid json */
1845 }
1846
1847 if (check_unique_keys && !state.unique)
1848 {
1849 if (throw_error)
1850 ereport(ERROR,
1851 (errcode(ERRCODE_DUPLICATE_JSON_OBJECT_KEY_VALUE),
1852 errmsg("duplicate JSON object key value")));
1853
1854 return false; /* not unique keys */
1855 }
1856
1857 if (check_unique_keys)
1858 freeJsonLexContext(&lex);
1859
1860 return true; /* ok */
1861}
static JsonParseErrorType json_unique_object_start(void *_state)
Definition: json.c:1756
static JsonParseErrorType json_unique_object_field_start(void *_state, char *field, bool isnull)
Definition: json.c:1789
static JsonParseErrorType json_unique_object_end(void *_state)
Definition: json.c:1774
JsonParseErrorType pg_parse_json(JsonLexContext *lex, const JsonSemAction *sem)
Definition: jsonapi.c:744
void freeJsonLexContext(JsonLexContext *lex)
Definition: jsonapi.c:687
json_struct_action object_start
Definition: jsonapi.h:154
json_ofield_action object_field_start
Definition: jsonapi.h:158
void * semstate
Definition: jsonapi.h:153
json_struct_action object_end
Definition: jsonapi.h:155

References ereport, errcode(), errmsg(), ERROR, freeJsonLexContext(), json_errsave_error(), JSON_SUCCESS, json_unique_check_init(), json_unique_object_end(), json_unique_object_field_start(), json_unique_object_start(), makeJsonLexContext(), nullSemAction, JsonSemAction::object_end, JsonSemAction::object_field_start, JsonSemAction::object_start, pg_parse_json(), and JsonSemAction::semstate.

Referenced by ExecEvalJsonConstructor(), and ExecEvalJsonIsPredicate().

◆ JsonEncodeDateTime()

char * JsonEncodeDateTime ( char *  buf,
Datum  value,
Oid  typid,
const int *  tzp 
)

Definition at line 311 of file json.c.

312{
313 if (!buf)
314 buf = palloc(MAXDATELEN + 1);
315
316 switch (typid)
317 {
318 case DATEOID:
319 {
321 struct pg_tm tm;
322
324
325 /* Same as date_out(), but forcing DateStyle */
328 else
329 {
331 &(tm.tm_year), &(tm.tm_mon), &(tm.tm_mday));
333 }
334 }
335 break;
336 case TIMEOID:
337 {
339 struct pg_tm tt,
340 *tm = &tt;
341 fsec_t fsec;
342
343 /* Same as time_out(), but forcing DateStyle */
344 time2tm(time, tm, &fsec);
345 EncodeTimeOnly(tm, fsec, false, 0, USE_XSD_DATES, buf);
346 }
347 break;
348 case TIMETZOID:
349 {
351 struct pg_tm tt,
352 *tm = &tt;
353 fsec_t fsec;
354 int tz;
355
356 /* Same as timetz_out(), but forcing DateStyle */
357 timetz2tm(time, tm, &fsec, &tz);
358 EncodeTimeOnly(tm, fsec, true, tz, USE_XSD_DATES, buf);
359 }
360 break;
361 case TIMESTAMPOID:
362 {
364 struct pg_tm tm;
365 fsec_t fsec;
366
368 /* Same as timestamp_out(), but forcing DateStyle */
371 else if (timestamp2tm(timestamp, NULL, &tm, &fsec, NULL, NULL) == 0)
372 EncodeDateTime(&tm, fsec, false, 0, NULL, USE_XSD_DATES, buf);
373 else
375 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
376 errmsg("timestamp out of range")));
377 }
378 break;
379 case TIMESTAMPTZOID:
380 {
382 struct pg_tm tm;
383 int tz;
384 fsec_t fsec;
385 const char *tzn = NULL;
386
388
389 /*
390 * If a time zone is specified, we apply the time-zone shift,
391 * convert timestamptz to pg_tm as if it were without a time
392 * zone, and then use the specified time zone for converting
393 * the timestamp into a string.
394 */
395 if (tzp)
396 {
397 tz = *tzp;
399 }
400
401 /* Same as timestamptz_out(), but forcing DateStyle */
404 else if (timestamp2tm(timestamp, tzp ? NULL : &tz, &tm, &fsec,
405 tzp ? NULL : &tzn, NULL) == 0)
406 {
407 if (tzp)
408 tm.tm_isdst = 1; /* set time-zone presence flag */
409
410 EncodeDateTime(&tm, fsec, true, tz, tzn, USE_XSD_DATES, buf);
411 }
412 else
414 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
415 errmsg("timestamp out of range")));
416 }
417 break;
418 default:
419 elog(ERROR, "unknown jsonb value datetime type oid %u", typid);
420 return NULL;
421 }
422
423 return buf;
424}
void EncodeTimeOnly(struct pg_tm *tm, fsec_t fsec, bool print_tz, int tz, int style, char *str)
Definition: datetime.c:4434
void j2date(int jd, int *year, int *month, int *day)
Definition: datetime.c:321
void EncodeDateTime(struct pg_tm *tm, fsec_t fsec, bool print_tz, int tz, const char *tzn, int style, char *str)
Definition: datetime.c:4464
void EncodeDateOnly(struct pg_tm *tm, int style, char *str)
Definition: datetime.c:4349
void EncodeSpecialTimestamp(Timestamp dt, char *str)
Definition: timestamp.c:1587
int timestamp2tm(Timestamp dt, int *tzp, struct pg_tm *tm, fsec_t *fsec, const char **tzn, pg_tz *attimezone)
Definition: timestamp.c:1910
int64 Timestamp
Definition: timestamp.h:38
int64 TimestampTz
Definition: timestamp.h:39
int32 fsec_t
Definition: timestamp.h:41
#define USECS_PER_SEC
Definition: timestamp.h:134
#define TIMESTAMP_NOT_FINITE(j)
Definition: timestamp.h:169
#define POSTGRES_EPOCH_JDATE
Definition: timestamp.h:235
int timetz2tm(TimeTzADT *time, struct pg_tm *tm, fsec_t *fsec, int *tzp)
Definition: date.c:2550
int time2tm(TimeADT time, struct pg_tm *tm, fsec_t *fsec)
Definition: date.c:1635
void EncodeSpecialDate(DateADT dt, char *str)
Definition: date.c:302
#define DATE_NOT_FINITE(j)
Definition: date.h:43
static TimeTzADT * DatumGetTimeTzADTP(Datum X)
Definition: date.h:66
int32 DateADT
Definition: date.h:23
static DateADT DatumGetDateADT(Datum X)
Definition: date.h:54
static TimeADT DatumGetTimeADT(Datum X)
Definition: date.h:60
int64 TimeADT
Definition: date.h:25
static struct @171 value
static struct pg_tm tm
Definition: localtime.c:104
#define USE_XSD_DATES
Definition: miscadmin.h:240
long date
Definition: pgtypes_date.h:9
int64 timestamp
Definition: date.h:28
Definition: pgtime.h:35
int tm_mday
Definition: pgtime.h:39
int tm_mon
Definition: pgtime.h:40
int tm_isdst
Definition: pgtime.h:44
int tm_year
Definition: pgtime.h:41
static Timestamp DatumGetTimestamp(Datum X)
Definition: timestamp.h:28
static TimestampTz DatumGetTimestampTz(Datum X)
Definition: timestamp.h:34

References buf, DATE_NOT_FINITE, DatumGetDateADT(), DatumGetTimeADT(), DatumGetTimestamp(), DatumGetTimestampTz(), DatumGetTimeTzADTP(), elog, EncodeDateOnly(), EncodeDateTime(), EncodeSpecialDate(), EncodeSpecialTimestamp(), EncodeTimeOnly(), ereport, errcode(), errmsg(), ERROR, j2date(), MAXDATELEN, palloc(), POSTGRES_EPOCH_JDATE, time2tm(), timestamp2tm(), TIMESTAMP_NOT_FINITE, timetz2tm(), tm, pg_tm::tm_isdst, pg_tm::tm_mday, pg_tm::tm_mon, pg_tm::tm_year, USE_XSD_DATES, USECS_PER_SEC, and value.

Referenced by convertJsonbScalar(), datum_to_json_internal(), datum_to_jsonb_internal(), and executeItemOptUnwrapTarget().

◆ row_to_json()

Datum row_to_json ( PG_FUNCTION_ARGS  )

Definition at line 664 of file json.c.

665{
666 Datum array = PG_GETARG_DATUM(0);
667 StringInfoData result;
668
669 initStringInfo(&result);
670
671 composite_to_json(array, &result, false);
672
674}

References composite_to_json(), cstring_to_text_with_len(), StringInfoData::data, initStringInfo(), StringInfoData::len, PG_GETARG_DATUM, and PG_RETURN_TEXT_P.

◆ row_to_json_pretty()

Datum row_to_json_pretty ( PG_FUNCTION_ARGS  )

Definition at line 680 of file json.c.

681{
682 Datum array = PG_GETARG_DATUM(0);
683 bool use_line_feeds = PG_GETARG_BOOL(1);
684 StringInfoData result;
685
686 initStringInfo(&result);
687
688 composite_to_json(array, &result, use_line_feeds);
689
691}

References composite_to_json(), cstring_to_text_with_len(), StringInfoData::data, initStringInfo(), StringInfoData::len, PG_GETARG_BOOL, PG_GETARG_DATUM, and PG_RETURN_TEXT_P.

◆ to_json()

Datum to_json ( PG_FUNCTION_ARGS  )

Definition at line 740 of file json.c.

741{
743 Oid val_type = get_fn_expr_argtype(fcinfo->flinfo, 0);
744 JsonTypeCategory tcategory;
745 Oid outfuncoid;
746
747 if (val_type == InvalidOid)
749 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
750 errmsg("could not determine input data type")));
751
752 json_categorize_type(val_type, false,
753 &tcategory, &outfuncoid);
754
755 PG_RETURN_DATUM(datum_to_json(val, tcategory, outfuncoid));
756}
Datum datum_to_json(Datum val, JsonTypeCategory tcategory, Oid outfuncoid)
Definition: json.c:764

References datum_to_json(), ereport, errcode(), errmsg(), ERROR, get_fn_expr_argtype(), InvalidOid, json_categorize_type(), PG_GETARG_DATUM, PG_RETURN_DATUM, and val.

◆ to_json_is_immutable()

bool to_json_is_immutable ( Oid  typoid)

Definition at line 701 of file json.c.

702{
703 JsonTypeCategory tcategory;
704 Oid outfuncoid;
705
706 json_categorize_type(typoid, false, &tcategory, &outfuncoid);
707
708 switch (tcategory)
709 {
710 case JSONTYPE_BOOL:
711 case JSONTYPE_JSON:
712 case JSONTYPE_JSONB:
713 case JSONTYPE_NULL:
714 return true;
715
716 case JSONTYPE_DATE:
719 return false;
720
721 case JSONTYPE_ARRAY:
722 return false; /* TODO recurse into elements */
723
725 return false; /* TODO recurse into fields */
726
727 case JSONTYPE_NUMERIC:
728 case JSONTYPE_CAST:
729 case JSONTYPE_OTHER:
730 return func_volatile(outfuncoid) == PROVOLATILE_IMMUTABLE;
731 }
732
733 return false; /* not reached */
734}
@ JSONTYPE_OTHER
Definition: jsonfuncs.h:81
@ JSONTYPE_JSONB
Definition: jsonfuncs.h:77
char func_volatile(Oid funcid)
Definition: lsyscache.c:1947

References func_volatile(), json_categorize_type(), JSONTYPE_ARRAY, JSONTYPE_BOOL, JSONTYPE_CAST, JSONTYPE_COMPOSITE, JSONTYPE_DATE, JSONTYPE_JSON, JSONTYPE_JSONB, JSONTYPE_NULL, JSONTYPE_NUMERIC, JSONTYPE_OTHER, JSONTYPE_TIMESTAMP, and JSONTYPE_TIMESTAMPTZ.

Referenced by contain_mutable_functions_walker().